PackageManagerService.java revision c254de07364ba8adfc1383e8d8d0ae56a1c0f855
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.MANAGE_DEVICE_ADMINS;
21import static android.Manifest.permission.SET_HARMFUL_APP_WARNINGS;
22import static android.Manifest.permission.INSTALL_PACKAGES;
23import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
24import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
25import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
26import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
27import static android.content.pm.PackageManager.CERT_INPUT_RAW_X509;
28import static android.content.pm.PackageManager.CERT_INPUT_SHA256;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
31import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
32import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
33import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
34import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
39import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
40import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
41import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
42import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
43import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
44import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
45import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
50import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
51import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
52import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
53import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
54import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
57import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
58import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.isApkFile;
86import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
87import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
88import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
89import static android.system.OsConstants.O_CREAT;
90import static android.system.OsConstants.O_RDWR;
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendElement;
96import static com.android.internal.util.ArrayUtils.appendInt;
97import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
100import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
101import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
104import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
105import static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
106import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
107import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
108import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
109import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
110import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
111import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
115
116import android.Manifest;
117import android.annotation.IntDef;
118import android.annotation.NonNull;
119import android.annotation.Nullable;
120import android.annotation.UserIdInt;
121import android.app.ActivityManager;
122import android.app.ActivityManagerInternal;
123import android.app.AppOpsManager;
124import android.app.IActivityManager;
125import android.app.ResourcesManager;
126import android.app.admin.IDevicePolicyManager;
127import android.app.admin.SecurityLog;
128import android.app.backup.IBackupManager;
129import android.content.BroadcastReceiver;
130import android.content.ComponentName;
131import android.content.ContentResolver;
132import android.content.Context;
133import android.content.IIntentReceiver;
134import android.content.Intent;
135import android.content.IntentFilter;
136import android.content.IntentSender;
137import android.content.IntentSender.SendIntentException;
138import android.content.ServiceConnection;
139import android.content.pm.ActivityInfo;
140import android.content.pm.ApplicationInfo;
141import android.content.pm.AppsQueryHelper;
142import android.content.pm.AuxiliaryResolveInfo;
143import android.content.pm.ChangedPackages;
144import android.content.pm.ComponentInfo;
145import android.content.pm.FallbackCategoryProvider;
146import android.content.pm.FeatureInfo;
147import android.content.pm.IDexModuleRegisterCallback;
148import android.content.pm.IOnPermissionsChangeListener;
149import android.content.pm.IPackageDataObserver;
150import android.content.pm.IPackageDeleteObserver;
151import android.content.pm.IPackageDeleteObserver2;
152import android.content.pm.IPackageInstallObserver2;
153import android.content.pm.IPackageInstaller;
154import android.content.pm.IPackageManager;
155import android.content.pm.IPackageManagerNative;
156import android.content.pm.IPackageMoveObserver;
157import android.content.pm.IPackageStatsObserver;
158import android.content.pm.InstantAppInfo;
159import android.content.pm.InstantAppRequest;
160import android.content.pm.InstantAppResolveInfo;
161import android.content.pm.InstrumentationInfo;
162import android.content.pm.IntentFilterVerificationInfo;
163import android.content.pm.KeySet;
164import android.content.pm.PackageCleanItem;
165import android.content.pm.PackageInfo;
166import android.content.pm.PackageInfoLite;
167import android.content.pm.PackageInstaller;
168import android.content.pm.PackageList;
169import android.content.pm.PackageManager;
170import android.content.pm.PackageManagerInternal;
171import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
172import android.content.pm.PackageManagerInternal.PackageListObserver;
173import android.content.pm.PackageParser;
174import android.content.pm.PackageParser.ActivityIntentInfo;
175import android.content.pm.PackageParser.Package;
176import android.content.pm.PackageParser.PackageLite;
177import android.content.pm.PackageParser.PackageParserException;
178import android.content.pm.PackageParser.ParseFlags;
179import android.content.pm.PackageParser.ServiceIntentInfo;
180import android.content.pm.PackageParser.SigningDetails;
181import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion;
182import android.content.pm.PackageStats;
183import android.content.pm.PackageUserState;
184import android.content.pm.ParceledListSlice;
185import android.content.pm.PermissionGroupInfo;
186import android.content.pm.PermissionInfo;
187import android.content.pm.ProviderInfo;
188import android.content.pm.ResolveInfo;
189import android.content.pm.ServiceInfo;
190import android.content.pm.SharedLibraryInfo;
191import android.content.pm.Signature;
192import android.content.pm.UserInfo;
193import android.content.pm.VerifierDeviceIdentity;
194import android.content.pm.VerifierInfo;
195import android.content.pm.VersionedPackage;
196import android.content.pm.dex.ArtManager;
197import android.content.pm.dex.DexMetadataHelper;
198import android.content.pm.dex.IArtManager;
199import android.content.res.Resources;
200import android.database.ContentObserver;
201import android.graphics.Bitmap;
202import android.hardware.display.DisplayManager;
203import android.net.Uri;
204import android.os.Binder;
205import android.os.Build;
206import android.os.Bundle;
207import android.os.Debug;
208import android.os.Environment;
209import android.os.Environment.UserEnvironment;
210import android.os.FileUtils;
211import android.os.Handler;
212import android.os.IBinder;
213import android.os.Looper;
214import android.os.Message;
215import android.os.Parcel;
216import android.os.ParcelFileDescriptor;
217import android.os.PatternMatcher;
218import android.os.PersistableBundle;
219import android.os.Process;
220import android.os.RemoteCallbackList;
221import android.os.RemoteException;
222import android.os.ResultReceiver;
223import android.os.SELinux;
224import android.os.ServiceManager;
225import android.os.ShellCallback;
226import android.os.SystemClock;
227import android.os.SystemProperties;
228import android.os.Trace;
229import android.os.UserHandle;
230import android.os.UserManager;
231import android.os.UserManagerInternal;
232import android.os.storage.IStorageManager;
233import android.os.storage.StorageEventListener;
234import android.os.storage.StorageManager;
235import android.os.storage.StorageManagerInternal;
236import android.os.storage.VolumeInfo;
237import android.os.storage.VolumeRecord;
238import android.provider.Settings.Global;
239import android.provider.Settings.Secure;
240import android.security.KeyStore;
241import android.security.SystemKeyStore;
242import android.service.pm.PackageServiceDumpProto;
243import android.system.ErrnoException;
244import android.system.Os;
245import android.text.TextUtils;
246import android.text.format.DateUtils;
247import android.util.ArrayMap;
248import android.util.ArraySet;
249import android.util.Base64;
250import android.util.ByteStringUtils;
251import android.util.DisplayMetrics;
252import android.util.EventLog;
253import android.util.ExceptionUtils;
254import android.util.Log;
255import android.util.LogPrinter;
256import android.util.LongSparseArray;
257import android.util.LongSparseLongArray;
258import android.util.MathUtils;
259import android.util.PackageUtils;
260import android.util.Pair;
261import android.util.PrintStreamPrinter;
262import android.util.Slog;
263import android.util.SparseArray;
264import android.util.SparseBooleanArray;
265import android.util.SparseIntArray;
266import android.util.TimingsTraceLog;
267import android.util.Xml;
268import android.util.jar.StrictJarFile;
269import android.util.proto.ProtoOutputStream;
270import android.view.Display;
271
272import com.android.internal.R;
273import com.android.internal.annotations.GuardedBy;
274import com.android.internal.app.IMediaContainerService;
275import com.android.internal.app.ResolverActivity;
276import com.android.internal.content.NativeLibraryHelper;
277import com.android.internal.content.PackageHelper;
278import com.android.internal.logging.MetricsLogger;
279import com.android.internal.os.IParcelFileDescriptorFactory;
280import com.android.internal.os.SomeArgs;
281import com.android.internal.os.Zygote;
282import com.android.internal.telephony.CarrierAppUtils;
283import com.android.internal.util.ArrayUtils;
284import com.android.internal.util.ConcurrentUtils;
285import com.android.internal.util.DumpUtils;
286import com.android.internal.util.FastXmlSerializer;
287import com.android.internal.util.IndentingPrintWriter;
288import com.android.internal.util.Preconditions;
289import com.android.internal.util.XmlUtils;
290import com.android.server.AttributeCache;
291import com.android.server.DeviceIdleController;
292import com.android.server.EventLogTags;
293import com.android.server.FgThread;
294import com.android.server.IntentResolver;
295import com.android.server.LocalServices;
296import com.android.server.LockGuard;
297import com.android.server.ServiceThread;
298import com.android.server.SystemConfig;
299import com.android.server.SystemServerInitThreadPool;
300import com.android.server.Watchdog;
301import com.android.server.net.NetworkPolicyManagerInternal;
302import com.android.server.pm.Installer.InstallerException;
303import com.android.server.pm.Settings.DatabaseVersion;
304import com.android.server.pm.Settings.VersionInfo;
305import com.android.server.pm.dex.ArtManagerService;
306import com.android.server.pm.dex.DexLogger;
307import com.android.server.pm.dex.DexManager;
308import com.android.server.pm.dex.DexoptOptions;
309import com.android.server.pm.dex.PackageDexUsage;
310import com.android.server.pm.permission.BasePermission;
311import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
312import com.android.server.pm.permission.PermissionManagerService;
313import com.android.server.pm.permission.PermissionManagerInternal;
314import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
315import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
316import com.android.server.pm.permission.PermissionsState;
317import com.android.server.pm.permission.PermissionsState.PermissionState;
318import com.android.server.security.VerityUtils;
319import com.android.server.storage.DeviceStorageMonitorInternal;
320
321import dalvik.system.CloseGuard;
322import dalvik.system.VMRuntime;
323
324import libcore.io.IoUtils;
325
326import org.xmlpull.v1.XmlPullParser;
327import org.xmlpull.v1.XmlPullParserException;
328import org.xmlpull.v1.XmlSerializer;
329
330import java.io.BufferedOutputStream;
331import java.io.ByteArrayInputStream;
332import java.io.ByteArrayOutputStream;
333import java.io.File;
334import java.io.FileDescriptor;
335import java.io.FileInputStream;
336import java.io.FileOutputStream;
337import java.io.FilenameFilter;
338import java.io.IOException;
339import java.io.PrintWriter;
340import java.lang.annotation.Retention;
341import java.lang.annotation.RetentionPolicy;
342import java.nio.charset.StandardCharsets;
343import java.security.DigestException;
344import java.security.DigestInputStream;
345import java.security.MessageDigest;
346import java.security.NoSuchAlgorithmException;
347import java.security.PublicKey;
348import java.security.SecureRandom;
349import java.security.cert.CertificateException;
350import java.util.ArrayList;
351import java.util.Arrays;
352import java.util.Collection;
353import java.util.Collections;
354import java.util.Comparator;
355import java.util.HashMap;
356import java.util.HashSet;
357import java.util.Iterator;
358import java.util.LinkedHashSet;
359import java.util.List;
360import java.util.Map;
361import java.util.Objects;
362import java.util.Set;
363import java.util.concurrent.CountDownLatch;
364import java.util.concurrent.Future;
365import java.util.concurrent.TimeUnit;
366import java.util.concurrent.atomic.AtomicBoolean;
367import java.util.concurrent.atomic.AtomicInteger;
368
369/**
370 * Keep track of all those APKs everywhere.
371 * <p>
372 * Internally there are two important locks:
373 * <ul>
374 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
375 * and other related state. It is a fine-grained lock that should only be held
376 * momentarily, as it's one of the most contended locks in the system.
377 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
378 * operations typically involve heavy lifting of application data on disk. Since
379 * {@code installd} is single-threaded, and it's operations can often be slow,
380 * this lock should never be acquired while already holding {@link #mPackages}.
381 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
382 * holding {@link #mInstallLock}.
383 * </ul>
384 * Many internal methods rely on the caller to hold the appropriate locks, and
385 * this contract is expressed through method name suffixes:
386 * <ul>
387 * <li>fooLI(): the caller must hold {@link #mInstallLock}
388 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
389 * being modified must be frozen
390 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
391 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
392 * </ul>
393 * <p>
394 * Because this class is very central to the platform's security; please run all
395 * CTS and unit tests whenever making modifications:
396 *
397 * <pre>
398 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
399 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
400 * </pre>
401 */
402public class PackageManagerService extends IPackageManager.Stub
403        implements PackageSender {
404    static final String TAG = "PackageManager";
405    public static final boolean DEBUG_SETTINGS = false;
406    static final boolean DEBUG_PREFERRED = false;
407    static final boolean DEBUG_UPGRADE = false;
408    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
409    private static final boolean DEBUG_BACKUP = false;
410    public static final boolean DEBUG_INSTALL = false;
411    public static final boolean DEBUG_REMOVE = true;
412    private static final boolean DEBUG_BROADCASTS = false;
413    private static final boolean DEBUG_SHOW_INFO = false;
414    private static final boolean DEBUG_PACKAGE_INFO = false;
415    private static final boolean DEBUG_INTENT_MATCHING = false;
416    public static final boolean DEBUG_PACKAGE_SCANNING = false;
417    private static final boolean DEBUG_VERIFY = false;
418    private static final boolean DEBUG_FILTERS = false;
419    public static final boolean DEBUG_PERMISSIONS = false;
420    private static final boolean DEBUG_SHARED_LIBRARIES = false;
421    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
422
423    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
424    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
425    // user, but by default initialize to this.
426    public static final boolean DEBUG_DEXOPT = false;
427
428    private static final boolean DEBUG_ABI_SELECTION = false;
429    private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
430    private static final boolean DEBUG_TRIAGED_MISSING = false;
431    private static final boolean DEBUG_APP_DATA = false;
432
433    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
434    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
435
436    private static final boolean HIDE_EPHEMERAL_APIS = false;
437
438    private static final boolean ENABLE_FREE_CACHE_V2 =
439            SystemProperties.getBoolean("fw.free_cache_v2", true);
440
441    private static final int RADIO_UID = Process.PHONE_UID;
442    private static final int LOG_UID = Process.LOG_UID;
443    private static final int NFC_UID = Process.NFC_UID;
444    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
445    private static final int SHELL_UID = Process.SHELL_UID;
446    private static final int SE_UID = Process.SE_UID;
447
448    // Suffix used during package installation when copying/moving
449    // package apks to install directory.
450    private static final String INSTALL_PACKAGE_SUFFIX = "-";
451
452    static final int SCAN_NO_DEX = 1<<0;
453    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
454    static final int SCAN_NEW_INSTALL = 1<<2;
455    static final int SCAN_UPDATE_TIME = 1<<3;
456    static final int SCAN_BOOTING = 1<<4;
457    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
458    static final int SCAN_REQUIRE_KNOWN = 1<<7;
459    static final int SCAN_MOVE = 1<<8;
460    static final int SCAN_INITIAL = 1<<9;
461    static final int SCAN_CHECK_ONLY = 1<<10;
462    static final int SCAN_DONT_KILL_APP = 1<<11;
463    static final int SCAN_IGNORE_FROZEN = 1<<12;
464    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
465    static final int SCAN_AS_INSTANT_APP = 1<<14;
466    static final int SCAN_AS_FULL_APP = 1<<15;
467    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
468    static final int SCAN_AS_SYSTEM = 1<<17;
469    static final int SCAN_AS_PRIVILEGED = 1<<18;
470    static final int SCAN_AS_OEM = 1<<19;
471    static final int SCAN_AS_VENDOR = 1<<20;
472    static final int SCAN_AS_PRODUCT = 1<<21;
473
474    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
475            SCAN_NO_DEX,
476            SCAN_UPDATE_SIGNATURE,
477            SCAN_NEW_INSTALL,
478            SCAN_UPDATE_TIME,
479            SCAN_BOOTING,
480            SCAN_DELETE_DATA_ON_FAILURES,
481            SCAN_REQUIRE_KNOWN,
482            SCAN_MOVE,
483            SCAN_INITIAL,
484            SCAN_CHECK_ONLY,
485            SCAN_DONT_KILL_APP,
486            SCAN_IGNORE_FROZEN,
487            SCAN_FIRST_BOOT_OR_UPGRADE,
488            SCAN_AS_INSTANT_APP,
489            SCAN_AS_FULL_APP,
490            SCAN_AS_VIRTUAL_PRELOAD,
491    })
492    @Retention(RetentionPolicy.SOURCE)
493    public @interface ScanFlags {}
494
495    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
496    /** Extension of the compressed packages */
497    public final static String COMPRESSED_EXTENSION = ".gz";
498    /** Suffix of stub packages on the system partition */
499    public final static String STUB_SUFFIX = "-Stub";
500
501    private static final int[] EMPTY_INT_ARRAY = new int[0];
502
503    private static final int TYPE_UNKNOWN = 0;
504    private static final int TYPE_ACTIVITY = 1;
505    private static final int TYPE_RECEIVER = 2;
506    private static final int TYPE_SERVICE = 3;
507    private static final int TYPE_PROVIDER = 4;
508    @IntDef(prefix = { "TYPE_" }, value = {
509            TYPE_UNKNOWN,
510            TYPE_ACTIVITY,
511            TYPE_RECEIVER,
512            TYPE_SERVICE,
513            TYPE_PROVIDER,
514    })
515    @Retention(RetentionPolicy.SOURCE)
516    public @interface ComponentType {}
517
518    /**
519     * Timeout (in milliseconds) after which the watchdog should declare that
520     * our handler thread is wedged.  The usual default for such things is one
521     * minute but we sometimes do very lengthy I/O operations on this thread,
522     * such as installing multi-gigabyte applications, so ours needs to be longer.
523     */
524    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
525
526    /**
527     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
528     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
529     * settings entry if available, otherwise we use the hardcoded default.  If it's been
530     * more than this long since the last fstrim, we force one during the boot sequence.
531     *
532     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
533     * one gets run at the next available charging+idle time.  This final mandatory
534     * no-fstrim check kicks in only of the other scheduling criteria is never met.
535     */
536    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
537
538    /**
539     * Whether verification is enabled by default.
540     */
541    private static final boolean DEFAULT_VERIFY_ENABLE = true;
542
543    /**
544     * The default maximum time to wait for the verification agent to return in
545     * milliseconds.
546     */
547    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
548
549    /**
550     * The default response for package verification timeout.
551     *
552     * This can be either PackageManager.VERIFICATION_ALLOW or
553     * PackageManager.VERIFICATION_REJECT.
554     */
555    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
556
557    public static final String PLATFORM_PACKAGE_NAME = "android";
558
559    public static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
560
561    public static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
562            DEFAULT_CONTAINER_PACKAGE,
563            "com.android.defcontainer.DefaultContainerService");
564
565    private static final String KILL_APP_REASON_GIDS_CHANGED =
566            "permission grant or revoke changed gids";
567
568    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
569            "permissions revoked";
570
571    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
572
573    private static final String PACKAGE_SCHEME = "package";
574
575    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
576
577    private static final String PRODUCT_OVERLAY_DIR = "/product/overlay";
578
579    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
580
581    /** Canonical intent used to identify what counts as a "web browser" app */
582    private static final Intent sBrowserIntent;
583    static {
584        sBrowserIntent = new Intent();
585        sBrowserIntent.setAction(Intent.ACTION_VIEW);
586        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
587        sBrowserIntent.setData(Uri.parse("http:"));
588        sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
589    }
590
591    /**
592     * The set of all protected actions [i.e. those actions for which a high priority
593     * intent filter is disallowed].
594     */
595    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
596    static {
597        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
598        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
599        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
600        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
601    }
602
603    // Compilation reasons.
604    public static final int REASON_UNKNOWN = -1;
605    public static final int REASON_FIRST_BOOT = 0;
606    public static final int REASON_BOOT = 1;
607    public static final int REASON_INSTALL = 2;
608    public static final int REASON_BACKGROUND_DEXOPT = 3;
609    public static final int REASON_AB_OTA = 4;
610    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
611    public static final int REASON_SHARED = 6;
612
613    public static final int REASON_LAST = REASON_SHARED;
614
615    /**
616     * Version number for the package parser cache. Increment this whenever the format or
617     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
618     */
619    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
620
621    /**
622     * Whether the package parser cache is enabled.
623     */
624    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
625
626    /**
627     * Permissions required in order to receive instant application lifecycle broadcasts.
628     */
629    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
630            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
631
632    final ServiceThread mHandlerThread;
633
634    final PackageHandler mHandler;
635
636    private final ProcessLoggingHandler mProcessLoggingHandler;
637
638    /**
639     * Messages for {@link #mHandler} that need to wait for system ready before
640     * being dispatched.
641     */
642    private ArrayList<Message> mPostSystemReadyMessages;
643
644    final int mSdkVersion = Build.VERSION.SDK_INT;
645
646    final Context mContext;
647    final boolean mFactoryTest;
648    final boolean mOnlyCore;
649    final DisplayMetrics mMetrics;
650    final int mDefParseFlags;
651    final String[] mSeparateProcesses;
652    final boolean mIsUpgrade;
653    final boolean mIsPreNUpgrade;
654    final boolean mIsPreNMR1Upgrade;
655
656    // Have we told the Activity Manager to whitelist the default container service by uid yet?
657    @GuardedBy("mPackages")
658    boolean mDefaultContainerWhitelisted = false;
659
660    @GuardedBy("mPackages")
661    private boolean mDexOptDialogShown;
662
663    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
664    // LOCK HELD.  Can be called with mInstallLock held.
665    @GuardedBy("mInstallLock")
666    final Installer mInstaller;
667
668    /** Directory where installed applications are stored */
669    private static final File sAppInstallDir =
670            new File(Environment.getDataDirectory(), "app");
671    /** Directory where installed application's 32-bit native libraries are copied. */
672    private static final File sAppLib32InstallDir =
673            new File(Environment.getDataDirectory(), "app-lib");
674    /** Directory where code and non-resource assets of forward-locked applications are stored */
675    private static final File sDrmAppPrivateInstallDir =
676            new File(Environment.getDataDirectory(), "app-private");
677
678    // ----------------------------------------------------------------
679
680    // Lock for state used when installing and doing other long running
681    // operations.  Methods that must be called with this lock held have
682    // the suffix "LI".
683    final Object mInstallLock = new Object();
684
685    // ----------------------------------------------------------------
686
687    // Keys are String (package name), values are Package.  This also serves
688    // as the lock for the global state.  Methods that must be called with
689    // this lock held have the prefix "LP".
690    @GuardedBy("mPackages")
691    final ArrayMap<String, PackageParser.Package> mPackages =
692            new ArrayMap<String, PackageParser.Package>();
693
694    final ArrayMap<String, Set<String>> mKnownCodebase =
695            new ArrayMap<String, Set<String>>();
696
697    // Keys are isolated uids and values are the uid of the application
698    // that created the isolated proccess.
699    @GuardedBy("mPackages")
700    final SparseIntArray mIsolatedOwners = new SparseIntArray();
701
702    /**
703     * Tracks new system packages [received in an OTA] that we expect to
704     * find updated user-installed versions. Keys are package name, values
705     * are package location.
706     */
707    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
708    /**
709     * Tracks high priority intent filters for protected actions. During boot, certain
710     * filter actions are protected and should never be allowed to have a high priority
711     * intent filter for them. However, there is one, and only one exception -- the
712     * setup wizard. It must be able to define a high priority intent filter for these
713     * actions to ensure there are no escapes from the wizard. We need to delay processing
714     * of these during boot as we need to look at all of the system packages in order
715     * to know which component is the setup wizard.
716     */
717    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
718    /**
719     * Whether or not processing protected filters should be deferred.
720     */
721    private boolean mDeferProtectedFilters = true;
722
723    /**
724     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
725     */
726    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
727    /**
728     * Whether or not system app permissions should be promoted from install to runtime.
729     */
730    boolean mPromoteSystemApps;
731
732    @GuardedBy("mPackages")
733    final Settings mSettings;
734
735    /**
736     * Set of package names that are currently "frozen", which means active
737     * surgery is being done on the code/data for that package. The platform
738     * will refuse to launch frozen packages to avoid race conditions.
739     *
740     * @see PackageFreezer
741     */
742    @GuardedBy("mPackages")
743    final ArraySet<String> mFrozenPackages = new ArraySet<>();
744
745    final ProtectedPackages mProtectedPackages;
746
747    @GuardedBy("mLoadedVolumes")
748    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
749
750    boolean mFirstBoot;
751
752    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
753
754    @GuardedBy("mAvailableFeatures")
755    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
756
757    private final InstantAppRegistry mInstantAppRegistry;
758
759    @GuardedBy("mPackages")
760    int mChangedPackagesSequenceNumber;
761    /**
762     * List of changed [installed, removed or updated] packages.
763     * mapping from user id -> sequence number -> package name
764     */
765    @GuardedBy("mPackages")
766    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
767    /**
768     * The sequence number of the last change to a package.
769     * mapping from user id -> package name -> sequence number
770     */
771    @GuardedBy("mPackages")
772    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
773
774    @GuardedBy("mPackages")
775    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
776
777    class PackageParserCallback implements PackageParser.Callback {
778        @Override public final boolean hasFeature(String feature) {
779            return PackageManagerService.this.hasSystemFeature(feature, 0);
780        }
781
782        final List<PackageParser.Package> getStaticOverlayPackages(
783                Collection<PackageParser.Package> allPackages, String targetPackageName) {
784            if ("android".equals(targetPackageName)) {
785                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
786                // native AssetManager.
787                return null;
788            }
789
790            List<PackageParser.Package> overlayPackages = null;
791            for (PackageParser.Package p : allPackages) {
792                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
793                    if (overlayPackages == null) {
794                        overlayPackages = new ArrayList<PackageParser.Package>();
795                    }
796                    overlayPackages.add(p);
797                }
798            }
799            if (overlayPackages != null) {
800                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
801                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
802                        return p1.mOverlayPriority - p2.mOverlayPriority;
803                    }
804                };
805                Collections.sort(overlayPackages, cmp);
806            }
807            return overlayPackages;
808        }
809
810        final String[] getStaticOverlayPaths(List<PackageParser.Package> overlayPackages,
811                String targetPath, Object installLock) {
812            if (overlayPackages == null || overlayPackages.isEmpty()) {
813                return null;
814            }
815            List<String> overlayPathList = null;
816            for (PackageParser.Package overlayPackage : overlayPackages) {
817                if (targetPath == null) {
818                    if (overlayPathList == null) {
819                        overlayPathList = new ArrayList<String>();
820                    }
821                    overlayPathList.add(overlayPackage.baseCodePath);
822                    continue;
823                }
824
825                try {
826                    // Creates idmaps for system to parse correctly the Android manifest of the
827                    // target package.
828                    //
829                    // OverlayManagerService will update each of them with a correct gid from its
830                    // target package app id.
831                    if (installLock != null) {
832                        synchronized (installLock) {
833                            mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
834                                    UserHandle.getSharedAppGid(
835                                            UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
836                        }
837                    } else {
838                        // We can call mInstaller without holding mInstallLock because mInstallLock
839                        // is held before running parallel parsing.
840                        // Moreover holding mInstallLock on each parsing thread causes dead-lock.
841                        mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
842                                UserHandle.getSharedAppGid(
843                                        UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
844                    }
845                    if (overlayPathList == null) {
846                        overlayPathList = new ArrayList<String>();
847                    }
848                    overlayPathList.add(overlayPackage.baseCodePath);
849                } catch (InstallerException e) {
850                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
851                            overlayPackage.baseCodePath);
852                }
853            }
854            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
855        }
856
857        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
858            List<PackageParser.Package> overlayPackages;
859            synchronized (mPackages) {
860                overlayPackages = getStaticOverlayPackages(
861                        mPackages.values(), targetPackageName);
862            }
863            // It is safe to keep overlayPackages without holding mPackages because static overlay
864            // packages can't be uninstalled or disabled.
865            return getStaticOverlayPaths(overlayPackages, targetPath, mInstallLock);
866        }
867
868        @Override public final String[] getOverlayApks(String targetPackageName) {
869            return getStaticOverlayPaths(targetPackageName, null);
870        }
871
872        @Override public final String[] getOverlayPaths(String targetPackageName,
873                String targetPath) {
874            return getStaticOverlayPaths(targetPackageName, targetPath);
875        }
876    }
877
878    class ParallelPackageParserCallback extends PackageParserCallback {
879        List<PackageParser.Package> mOverlayPackages = null;
880
881        void findStaticOverlayPackages() {
882            synchronized (mPackages) {
883                for (PackageParser.Package p : mPackages.values()) {
884                    if (p.mOverlayIsStatic) {
885                        if (mOverlayPackages == null) {
886                            mOverlayPackages = new ArrayList<PackageParser.Package>();
887                        }
888                        mOverlayPackages.add(p);
889                    }
890                }
891            }
892        }
893
894        @Override
895        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
896            // We can trust mOverlayPackages without holding mPackages because package uninstall
897            // can't happen while running parallel parsing.
898            // Moreover holding mPackages on each parsing thread causes dead-lock.
899            return mOverlayPackages == null ? null :
900                    getStaticOverlayPaths(
901                            getStaticOverlayPackages(mOverlayPackages, targetPackageName),
902                            targetPath, null);
903        }
904    }
905
906    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
907    final ParallelPackageParserCallback mParallelPackageParserCallback =
908            new ParallelPackageParserCallback();
909
910    public static final class SharedLibraryEntry {
911        public final @Nullable String path;
912        public final @Nullable String apk;
913        public final @NonNull SharedLibraryInfo info;
914
915        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
916                String declaringPackageName, long declaringPackageVersionCode) {
917            path = _path;
918            apk = _apk;
919            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
920                    declaringPackageName, declaringPackageVersionCode), null);
921        }
922    }
923
924    // Currently known shared libraries.
925    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
926    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
927            new ArrayMap<>();
928
929    // All available activities, for your resolving pleasure.
930    final ActivityIntentResolver mActivities =
931            new ActivityIntentResolver();
932
933    // All available receivers, for your resolving pleasure.
934    final ActivityIntentResolver mReceivers =
935            new ActivityIntentResolver();
936
937    // All available services, for your resolving pleasure.
938    final ServiceIntentResolver mServices = new ServiceIntentResolver();
939
940    // All available providers, for your resolving pleasure.
941    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
942
943    // Mapping from provider base names (first directory in content URI codePath)
944    // to the provider information.
945    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
946            new ArrayMap<String, PackageParser.Provider>();
947
948    // Mapping from instrumentation class names to info about them.
949    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
950            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
951
952    // Packages whose data we have transfered into another package, thus
953    // should no longer exist.
954    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
955
956    // Broadcast actions that are only available to the system.
957    @GuardedBy("mProtectedBroadcasts")
958    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
959
960    /** List of packages waiting for verification. */
961    final SparseArray<PackageVerificationState> mPendingVerification
962            = new SparseArray<PackageVerificationState>();
963
964    final PackageInstallerService mInstallerService;
965
966    final ArtManagerService mArtManagerService;
967
968    private final PackageDexOptimizer mPackageDexOptimizer;
969    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
970    // is used by other apps).
971    private final DexManager mDexManager;
972
973    private AtomicInteger mNextMoveId = new AtomicInteger();
974    private final MoveCallbacks mMoveCallbacks;
975
976    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
977
978    // Cache of users who need badging.
979    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
980
981    /** Token for keys in mPendingVerification. */
982    private int mPendingVerificationToken = 0;
983
984    volatile boolean mSystemReady;
985    volatile boolean mSafeMode;
986    volatile boolean mHasSystemUidErrors;
987    private volatile boolean mWebInstantAppsDisabled;
988
989    ApplicationInfo mAndroidApplication;
990    final ActivityInfo mResolveActivity = new ActivityInfo();
991    final ResolveInfo mResolveInfo = new ResolveInfo();
992    ComponentName mResolveComponentName;
993    PackageParser.Package mPlatformPackage;
994    ComponentName mCustomResolverComponentName;
995
996    boolean mResolverReplaced = false;
997
998    private final @Nullable ComponentName mIntentFilterVerifierComponent;
999    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
1000
1001    private int mIntentFilterVerificationToken = 0;
1002
1003    /** The service connection to the ephemeral resolver */
1004    final InstantAppResolverConnection mInstantAppResolverConnection;
1005    /** Component used to show resolver settings for Instant Apps */
1006    final ComponentName mInstantAppResolverSettingsComponent;
1007
1008    /** Activity used to install instant applications */
1009    ActivityInfo mInstantAppInstallerActivity;
1010    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1011
1012    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1013            = new SparseArray<IntentFilterVerificationState>();
1014
1015    // TODO remove this and go through mPermissonManager directly
1016    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1017    private final PermissionManagerInternal mPermissionManager;
1018
1019    // List of packages names to keep cached, even if they are uninstalled for all users
1020    private List<String> mKeepUninstalledPackages;
1021
1022    private UserManagerInternal mUserManagerInternal;
1023    private ActivityManagerInternal mActivityManagerInternal;
1024
1025    private DeviceIdleController.LocalService mDeviceIdleController;
1026
1027    private File mCacheDir;
1028
1029    private Future<?> mPrepareAppDataFuture;
1030
1031    private static class IFVerificationParams {
1032        PackageParser.Package pkg;
1033        boolean replacing;
1034        int userId;
1035        int verifierUid;
1036
1037        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1038                int _userId, int _verifierUid) {
1039            pkg = _pkg;
1040            replacing = _replacing;
1041            userId = _userId;
1042            replacing = _replacing;
1043            verifierUid = _verifierUid;
1044        }
1045    }
1046
1047    private interface IntentFilterVerifier<T extends IntentFilter> {
1048        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1049                                               T filter, String packageName);
1050        void startVerifications(int userId);
1051        void receiveVerificationResponse(int verificationId);
1052    }
1053
1054    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1055        private Context mContext;
1056        private ComponentName mIntentFilterVerifierComponent;
1057        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1058
1059        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1060            mContext = context;
1061            mIntentFilterVerifierComponent = verifierComponent;
1062        }
1063
1064        private String getDefaultScheme() {
1065            return IntentFilter.SCHEME_HTTPS;
1066        }
1067
1068        @Override
1069        public void startVerifications(int userId) {
1070            // Launch verifications requests
1071            int count = mCurrentIntentFilterVerifications.size();
1072            for (int n=0; n<count; n++) {
1073                int verificationId = mCurrentIntentFilterVerifications.get(n);
1074                final IntentFilterVerificationState ivs =
1075                        mIntentFilterVerificationStates.get(verificationId);
1076
1077                String packageName = ivs.getPackageName();
1078
1079                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1080                final int filterCount = filters.size();
1081                ArraySet<String> domainsSet = new ArraySet<>();
1082                for (int m=0; m<filterCount; m++) {
1083                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1084                    domainsSet.addAll(filter.getHostsList());
1085                }
1086                synchronized (mPackages) {
1087                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1088                            packageName, domainsSet) != null) {
1089                        scheduleWriteSettingsLocked();
1090                    }
1091                }
1092                sendVerificationRequest(verificationId, ivs);
1093            }
1094            mCurrentIntentFilterVerifications.clear();
1095        }
1096
1097        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1098            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1099            verificationIntent.putExtra(
1100                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1101                    verificationId);
1102            verificationIntent.putExtra(
1103                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1104                    getDefaultScheme());
1105            verificationIntent.putExtra(
1106                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1107                    ivs.getHostsString());
1108            verificationIntent.putExtra(
1109                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1110                    ivs.getPackageName());
1111            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1112            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1113
1114            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1115            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1116                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1117                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1118
1119            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1120            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1121                    "Sending IntentFilter verification broadcast");
1122        }
1123
1124        public void receiveVerificationResponse(int verificationId) {
1125            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1126
1127            final boolean verified = ivs.isVerified();
1128
1129            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1130            final int count = filters.size();
1131            if (DEBUG_DOMAIN_VERIFICATION) {
1132                Slog.i(TAG, "Received verification response " + verificationId
1133                        + " for " + count + " filters, verified=" + verified);
1134            }
1135            for (int n=0; n<count; n++) {
1136                PackageParser.ActivityIntentInfo filter = filters.get(n);
1137                filter.setVerified(verified);
1138
1139                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1140                        + " verified with result:" + verified + " and hosts:"
1141                        + ivs.getHostsString());
1142            }
1143
1144            mIntentFilterVerificationStates.remove(verificationId);
1145
1146            final String packageName = ivs.getPackageName();
1147            IntentFilterVerificationInfo ivi = null;
1148
1149            synchronized (mPackages) {
1150                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1151            }
1152            if (ivi == null) {
1153                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1154                        + verificationId + " packageName:" + packageName);
1155                return;
1156            }
1157            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1158                    "Updating IntentFilterVerificationInfo for package " + packageName
1159                            +" verificationId:" + verificationId);
1160
1161            synchronized (mPackages) {
1162                if (verified) {
1163                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1164                } else {
1165                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1166                }
1167                scheduleWriteSettingsLocked();
1168
1169                final int userId = ivs.getUserId();
1170                if (userId != UserHandle.USER_ALL) {
1171                    final int userStatus =
1172                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1173
1174                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1175                    boolean needUpdate = false;
1176
1177                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1178                    // already been set by the User thru the Disambiguation dialog
1179                    switch (userStatus) {
1180                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1181                            if (verified) {
1182                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1183                            } else {
1184                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1185                            }
1186                            needUpdate = true;
1187                            break;
1188
1189                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1190                            if (verified) {
1191                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1192                                needUpdate = true;
1193                            }
1194                            break;
1195
1196                        default:
1197                            // Nothing to do
1198                    }
1199
1200                    if (needUpdate) {
1201                        mSettings.updateIntentFilterVerificationStatusLPw(
1202                                packageName, updatedStatus, userId);
1203                        scheduleWritePackageRestrictionsLocked(userId);
1204                    }
1205                }
1206            }
1207        }
1208
1209        @Override
1210        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1211                    ActivityIntentInfo filter, String packageName) {
1212            if (!hasValidDomains(filter)) {
1213                return false;
1214            }
1215            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1216            if (ivs == null) {
1217                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1218                        packageName);
1219            }
1220            if (DEBUG_DOMAIN_VERIFICATION) {
1221                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1222            }
1223            ivs.addFilter(filter);
1224            return true;
1225        }
1226
1227        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1228                int userId, int verificationId, String packageName) {
1229            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1230                    verifierUid, userId, packageName);
1231            ivs.setPendingState();
1232            synchronized (mPackages) {
1233                mIntentFilterVerificationStates.append(verificationId, ivs);
1234                mCurrentIntentFilterVerifications.add(verificationId);
1235            }
1236            return ivs;
1237        }
1238    }
1239
1240    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1241        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1242                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1243                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1244    }
1245
1246    // Set of pending broadcasts for aggregating enable/disable of components.
1247    static class PendingPackageBroadcasts {
1248        // for each user id, a map of <package name -> components within that package>
1249        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1250
1251        public PendingPackageBroadcasts() {
1252            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1253        }
1254
1255        public ArrayList<String> get(int userId, String packageName) {
1256            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1257            return packages.get(packageName);
1258        }
1259
1260        public void put(int userId, String packageName, ArrayList<String> components) {
1261            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1262            packages.put(packageName, components);
1263        }
1264
1265        public void remove(int userId, String packageName) {
1266            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1267            if (packages != null) {
1268                packages.remove(packageName);
1269            }
1270        }
1271
1272        public void remove(int userId) {
1273            mUidMap.remove(userId);
1274        }
1275
1276        public int userIdCount() {
1277            return mUidMap.size();
1278        }
1279
1280        public int userIdAt(int n) {
1281            return mUidMap.keyAt(n);
1282        }
1283
1284        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1285            return mUidMap.get(userId);
1286        }
1287
1288        public int size() {
1289            // total number of pending broadcast entries across all userIds
1290            int num = 0;
1291            for (int i = 0; i< mUidMap.size(); i++) {
1292                num += mUidMap.valueAt(i).size();
1293            }
1294            return num;
1295        }
1296
1297        public void clear() {
1298            mUidMap.clear();
1299        }
1300
1301        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1302            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1303            if (map == null) {
1304                map = new ArrayMap<String, ArrayList<String>>();
1305                mUidMap.put(userId, map);
1306            }
1307            return map;
1308        }
1309    }
1310    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1311
1312    // Service Connection to remote media container service to copy
1313    // package uri's from external media onto secure containers
1314    // or internal storage.
1315    private IMediaContainerService mContainerService = null;
1316
1317    static final int SEND_PENDING_BROADCAST = 1;
1318    static final int MCS_BOUND = 3;
1319    static final int END_COPY = 4;
1320    static final int INIT_COPY = 5;
1321    static final int MCS_UNBIND = 6;
1322    static final int START_CLEANING_PACKAGE = 7;
1323    static final int FIND_INSTALL_LOC = 8;
1324    static final int POST_INSTALL = 9;
1325    static final int MCS_RECONNECT = 10;
1326    static final int MCS_GIVE_UP = 11;
1327    static final int WRITE_SETTINGS = 13;
1328    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1329    static final int PACKAGE_VERIFIED = 15;
1330    static final int CHECK_PENDING_VERIFICATION = 16;
1331    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1332    static final int INTENT_FILTER_VERIFIED = 18;
1333    static final int WRITE_PACKAGE_LIST = 19;
1334    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1335
1336    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1337
1338    // Delay time in millisecs
1339    static final int BROADCAST_DELAY = 10 * 1000;
1340
1341    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1342            2 * 60 * 60 * 1000L; /* two hours */
1343
1344    static UserManagerService sUserManager;
1345
1346    // Stores a list of users whose package restrictions file needs to be updated
1347    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1348
1349    final private DefaultContainerConnection mDefContainerConn =
1350            new DefaultContainerConnection();
1351    class DefaultContainerConnection implements ServiceConnection {
1352        public void onServiceConnected(ComponentName name, IBinder service) {
1353            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1354            final IMediaContainerService imcs = IMediaContainerService.Stub
1355                    .asInterface(Binder.allowBlocking(service));
1356            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1357        }
1358
1359        public void onServiceDisconnected(ComponentName name) {
1360            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1361        }
1362    }
1363
1364    // Recordkeeping of restore-after-install operations that are currently in flight
1365    // between the Package Manager and the Backup Manager
1366    static class PostInstallData {
1367        public InstallArgs args;
1368        public PackageInstalledInfo res;
1369
1370        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1371            args = _a;
1372            res = _r;
1373        }
1374    }
1375
1376    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1377    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1378
1379    // XML tags for backup/restore of various bits of state
1380    private static final String TAG_PREFERRED_BACKUP = "pa";
1381    private static final String TAG_DEFAULT_APPS = "da";
1382    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1383
1384    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1385    private static final String TAG_ALL_GRANTS = "rt-grants";
1386    private static final String TAG_GRANT = "grant";
1387    private static final String ATTR_PACKAGE_NAME = "pkg";
1388
1389    private static final String TAG_PERMISSION = "perm";
1390    private static final String ATTR_PERMISSION_NAME = "name";
1391    private static final String ATTR_IS_GRANTED = "g";
1392    private static final String ATTR_USER_SET = "set";
1393    private static final String ATTR_USER_FIXED = "fixed";
1394    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1395
1396    // System/policy permission grants are not backed up
1397    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1398            FLAG_PERMISSION_POLICY_FIXED
1399            | FLAG_PERMISSION_SYSTEM_FIXED
1400            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1401
1402    // And we back up these user-adjusted states
1403    private static final int USER_RUNTIME_GRANT_MASK =
1404            FLAG_PERMISSION_USER_SET
1405            | FLAG_PERMISSION_USER_FIXED
1406            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1407
1408    final @Nullable String mRequiredVerifierPackage;
1409    final @NonNull String mRequiredInstallerPackage;
1410    final @NonNull String mRequiredUninstallerPackage;
1411    final @Nullable String mSetupWizardPackage;
1412    final @Nullable String mStorageManagerPackage;
1413    final @Nullable String mSystemTextClassifierPackage;
1414    final @NonNull String mServicesSystemSharedLibraryPackageName;
1415    final @NonNull String mSharedSystemSharedLibraryPackageName;
1416
1417    private final PackageUsage mPackageUsage = new PackageUsage();
1418    private final CompilerStats mCompilerStats = new CompilerStats();
1419
1420    class PackageHandler extends Handler {
1421        private boolean mBound = false;
1422        final ArrayList<HandlerParams> mPendingInstalls =
1423            new ArrayList<HandlerParams>();
1424
1425        private boolean connectToService() {
1426            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1427                    " DefaultContainerService");
1428            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1429            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1430            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1431                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1432                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1433                mBound = true;
1434                return true;
1435            }
1436            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1437            return false;
1438        }
1439
1440        private void disconnectService() {
1441            mContainerService = null;
1442            mBound = false;
1443            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1444            mContext.unbindService(mDefContainerConn);
1445            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1446        }
1447
1448        PackageHandler(Looper looper) {
1449            super(looper);
1450        }
1451
1452        public void handleMessage(Message msg) {
1453            try {
1454                doHandleMessage(msg);
1455            } finally {
1456                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1457            }
1458        }
1459
1460        void doHandleMessage(Message msg) {
1461            switch (msg.what) {
1462                case INIT_COPY: {
1463                    HandlerParams params = (HandlerParams) msg.obj;
1464                    int idx = mPendingInstalls.size();
1465                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1466                    // If a bind was already initiated we dont really
1467                    // need to do anything. The pending install
1468                    // will be processed later on.
1469                    if (!mBound) {
1470                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1471                                System.identityHashCode(mHandler));
1472                        // If this is the only one pending we might
1473                        // have to bind to the service again.
1474                        if (!connectToService()) {
1475                            Slog.e(TAG, "Failed to bind to media container service");
1476                            params.serviceError();
1477                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1478                                    System.identityHashCode(mHandler));
1479                            if (params.traceMethod != null) {
1480                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1481                                        params.traceCookie);
1482                            }
1483                            return;
1484                        } else {
1485                            // Once we bind to the service, the first
1486                            // pending request will be processed.
1487                            mPendingInstalls.add(idx, params);
1488                        }
1489                    } else {
1490                        mPendingInstalls.add(idx, params);
1491                        // Already bound to the service. Just make
1492                        // sure we trigger off processing the first request.
1493                        if (idx == 0) {
1494                            mHandler.sendEmptyMessage(MCS_BOUND);
1495                        }
1496                    }
1497                    break;
1498                }
1499                case MCS_BOUND: {
1500                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1501                    if (msg.obj != null) {
1502                        mContainerService = (IMediaContainerService) msg.obj;
1503                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1504                                System.identityHashCode(mHandler));
1505                    }
1506                    if (mContainerService == null) {
1507                        if (!mBound) {
1508                            // Something seriously wrong since we are not bound and we are not
1509                            // waiting for connection. Bail out.
1510                            Slog.e(TAG, "Cannot bind to media container service");
1511                            for (HandlerParams params : mPendingInstalls) {
1512                                // Indicate service bind error
1513                                params.serviceError();
1514                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1515                                        System.identityHashCode(params));
1516                                if (params.traceMethod != null) {
1517                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1518                                            params.traceMethod, params.traceCookie);
1519                                }
1520                                return;
1521                            }
1522                            mPendingInstalls.clear();
1523                        } else {
1524                            Slog.w(TAG, "Waiting to connect to media container service");
1525                        }
1526                    } else if (mPendingInstalls.size() > 0) {
1527                        HandlerParams params = mPendingInstalls.get(0);
1528                        if (params != null) {
1529                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1530                                    System.identityHashCode(params));
1531                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1532                            if (params.startCopy()) {
1533                                // We are done...  look for more work or to
1534                                // go idle.
1535                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1536                                        "Checking for more work or unbind...");
1537                                // Delete pending install
1538                                if (mPendingInstalls.size() > 0) {
1539                                    mPendingInstalls.remove(0);
1540                                }
1541                                if (mPendingInstalls.size() == 0) {
1542                                    if (mBound) {
1543                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1544                                                "Posting delayed MCS_UNBIND");
1545                                        removeMessages(MCS_UNBIND);
1546                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1547                                        // Unbind after a little delay, to avoid
1548                                        // continual thrashing.
1549                                        sendMessageDelayed(ubmsg, 10000);
1550                                    }
1551                                } else {
1552                                    // There are more pending requests in queue.
1553                                    // Just post MCS_BOUND message to trigger processing
1554                                    // of next pending install.
1555                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1556                                            "Posting MCS_BOUND for next work");
1557                                    mHandler.sendEmptyMessage(MCS_BOUND);
1558                                }
1559                            }
1560                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1561                        }
1562                    } else {
1563                        // Should never happen ideally.
1564                        Slog.w(TAG, "Empty queue");
1565                    }
1566                    break;
1567                }
1568                case MCS_RECONNECT: {
1569                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1570                    if (mPendingInstalls.size() > 0) {
1571                        if (mBound) {
1572                            disconnectService();
1573                        }
1574                        if (!connectToService()) {
1575                            Slog.e(TAG, "Failed to bind to media container service");
1576                            for (HandlerParams params : mPendingInstalls) {
1577                                // Indicate service bind error
1578                                params.serviceError();
1579                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1580                                        System.identityHashCode(params));
1581                            }
1582                            mPendingInstalls.clear();
1583                        }
1584                    }
1585                    break;
1586                }
1587                case MCS_UNBIND: {
1588                    // If there is no actual work left, then time to unbind.
1589                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1590
1591                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1592                        if (mBound) {
1593                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1594
1595                            disconnectService();
1596                        }
1597                    } else if (mPendingInstalls.size() > 0) {
1598                        // There are more pending requests in queue.
1599                        // Just post MCS_BOUND message to trigger processing
1600                        // of next pending install.
1601                        mHandler.sendEmptyMessage(MCS_BOUND);
1602                    }
1603
1604                    break;
1605                }
1606                case MCS_GIVE_UP: {
1607                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1608                    HandlerParams params = mPendingInstalls.remove(0);
1609                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1610                            System.identityHashCode(params));
1611                    break;
1612                }
1613                case SEND_PENDING_BROADCAST: {
1614                    String packages[];
1615                    ArrayList<String> components[];
1616                    int size = 0;
1617                    int uids[];
1618                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1619                    synchronized (mPackages) {
1620                        if (mPendingBroadcasts == null) {
1621                            return;
1622                        }
1623                        size = mPendingBroadcasts.size();
1624                        if (size <= 0) {
1625                            // Nothing to be done. Just return
1626                            return;
1627                        }
1628                        packages = new String[size];
1629                        components = new ArrayList[size];
1630                        uids = new int[size];
1631                        int i = 0;  // filling out the above arrays
1632
1633                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1634                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1635                            Iterator<Map.Entry<String, ArrayList<String>>> it
1636                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1637                                            .entrySet().iterator();
1638                            while (it.hasNext() && i < size) {
1639                                Map.Entry<String, ArrayList<String>> ent = it.next();
1640                                packages[i] = ent.getKey();
1641                                components[i] = ent.getValue();
1642                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1643                                uids[i] = (ps != null)
1644                                        ? UserHandle.getUid(packageUserId, ps.appId)
1645                                        : -1;
1646                                i++;
1647                            }
1648                        }
1649                        size = i;
1650                        mPendingBroadcasts.clear();
1651                    }
1652                    // Send broadcasts
1653                    for (int i = 0; i < size; i++) {
1654                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1655                    }
1656                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1657                    break;
1658                }
1659                case START_CLEANING_PACKAGE: {
1660                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1661                    final String packageName = (String)msg.obj;
1662                    final int userId = msg.arg1;
1663                    final boolean andCode = msg.arg2 != 0;
1664                    synchronized (mPackages) {
1665                        if (userId == UserHandle.USER_ALL) {
1666                            int[] users = sUserManager.getUserIds();
1667                            for (int user : users) {
1668                                mSettings.addPackageToCleanLPw(
1669                                        new PackageCleanItem(user, packageName, andCode));
1670                            }
1671                        } else {
1672                            mSettings.addPackageToCleanLPw(
1673                                    new PackageCleanItem(userId, packageName, andCode));
1674                        }
1675                    }
1676                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1677                    startCleaningPackages();
1678                } break;
1679                case POST_INSTALL: {
1680                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1681
1682                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1683                    final boolean didRestore = (msg.arg2 != 0);
1684                    mRunningInstalls.delete(msg.arg1);
1685
1686                    if (data != null) {
1687                        InstallArgs args = data.args;
1688                        PackageInstalledInfo parentRes = data.res;
1689
1690                        final boolean grantPermissions = (args.installFlags
1691                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1692                        final boolean killApp = (args.installFlags
1693                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1694                        final boolean virtualPreload = ((args.installFlags
1695                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1696                        final String[] grantedPermissions = args.installGrantPermissions;
1697
1698                        // Handle the parent package
1699                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1700                                virtualPreload, grantedPermissions, didRestore,
1701                                args.installerPackageName, args.observer);
1702
1703                        // Handle the child packages
1704                        final int childCount = (parentRes.addedChildPackages != null)
1705                                ? parentRes.addedChildPackages.size() : 0;
1706                        for (int i = 0; i < childCount; i++) {
1707                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1708                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1709                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1710                                    args.installerPackageName, args.observer);
1711                        }
1712
1713                        // Log tracing if needed
1714                        if (args.traceMethod != null) {
1715                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1716                                    args.traceCookie);
1717                        }
1718                    } else {
1719                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1720                    }
1721
1722                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1723                } break;
1724                case WRITE_SETTINGS: {
1725                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1726                    synchronized (mPackages) {
1727                        removeMessages(WRITE_SETTINGS);
1728                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1729                        mSettings.writeLPr();
1730                        mDirtyUsers.clear();
1731                    }
1732                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1733                } break;
1734                case WRITE_PACKAGE_RESTRICTIONS: {
1735                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1736                    synchronized (mPackages) {
1737                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1738                        for (int userId : mDirtyUsers) {
1739                            mSettings.writePackageRestrictionsLPr(userId);
1740                        }
1741                        mDirtyUsers.clear();
1742                    }
1743                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1744                } break;
1745                case WRITE_PACKAGE_LIST: {
1746                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1747                    synchronized (mPackages) {
1748                        removeMessages(WRITE_PACKAGE_LIST);
1749                        mSettings.writePackageListLPr(msg.arg1);
1750                    }
1751                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1752                } break;
1753                case CHECK_PENDING_VERIFICATION: {
1754                    final int verificationId = msg.arg1;
1755                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1756
1757                    if ((state != null) && !state.timeoutExtended()) {
1758                        final InstallArgs args = state.getInstallArgs();
1759                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1760
1761                        Slog.i(TAG, "Verification timed out for " + originUri);
1762                        mPendingVerification.remove(verificationId);
1763
1764                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1765
1766                        final UserHandle user = args.getUser();
1767                        if (getDefaultVerificationResponse(user)
1768                                == PackageManager.VERIFICATION_ALLOW) {
1769                            Slog.i(TAG, "Continuing with installation of " + originUri);
1770                            state.setVerifierResponse(Binder.getCallingUid(),
1771                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1772                            broadcastPackageVerified(verificationId, originUri,
1773                                    PackageManager.VERIFICATION_ALLOW, user);
1774                            try {
1775                                ret = args.copyApk(mContainerService, true);
1776                            } catch (RemoteException e) {
1777                                Slog.e(TAG, "Could not contact the ContainerService");
1778                            }
1779                        } else {
1780                            broadcastPackageVerified(verificationId, originUri,
1781                                    PackageManager.VERIFICATION_REJECT, user);
1782                        }
1783
1784                        Trace.asyncTraceEnd(
1785                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1786
1787                        processPendingInstall(args, ret);
1788                        mHandler.sendEmptyMessage(MCS_UNBIND);
1789                    }
1790                    break;
1791                }
1792                case PACKAGE_VERIFIED: {
1793                    final int verificationId = msg.arg1;
1794
1795                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1796                    if (state == null) {
1797                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1798                        break;
1799                    }
1800
1801                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1802
1803                    state.setVerifierResponse(response.callerUid, response.code);
1804
1805                    if (state.isVerificationComplete()) {
1806                        mPendingVerification.remove(verificationId);
1807
1808                        final InstallArgs args = state.getInstallArgs();
1809                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1810
1811                        int ret;
1812                        if (state.isInstallAllowed()) {
1813                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1814                            broadcastPackageVerified(verificationId, originUri,
1815                                    response.code, state.getInstallArgs().getUser());
1816                            try {
1817                                ret = args.copyApk(mContainerService, true);
1818                            } catch (RemoteException e) {
1819                                Slog.e(TAG, "Could not contact the ContainerService");
1820                            }
1821                        } else {
1822                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1823                        }
1824
1825                        Trace.asyncTraceEnd(
1826                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1827
1828                        processPendingInstall(args, ret);
1829                        mHandler.sendEmptyMessage(MCS_UNBIND);
1830                    }
1831
1832                    break;
1833                }
1834                case START_INTENT_FILTER_VERIFICATIONS: {
1835                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1836                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1837                            params.replacing, params.pkg);
1838                    break;
1839                }
1840                case INTENT_FILTER_VERIFIED: {
1841                    final int verificationId = msg.arg1;
1842
1843                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1844                            verificationId);
1845                    if (state == null) {
1846                        Slog.w(TAG, "Invalid IntentFilter verification token "
1847                                + verificationId + " received");
1848                        break;
1849                    }
1850
1851                    final int userId = state.getUserId();
1852
1853                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1854                            "Processing IntentFilter verification with token:"
1855                            + verificationId + " and userId:" + userId);
1856
1857                    final IntentFilterVerificationResponse response =
1858                            (IntentFilterVerificationResponse) msg.obj;
1859
1860                    state.setVerifierResponse(response.callerUid, response.code);
1861
1862                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1863                            "IntentFilter verification with token:" + verificationId
1864                            + " and userId:" + userId
1865                            + " is settings verifier response with response code:"
1866                            + response.code);
1867
1868                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1869                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1870                                + response.getFailedDomainsString());
1871                    }
1872
1873                    if (state.isVerificationComplete()) {
1874                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1875                    } else {
1876                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1877                                "IntentFilter verification with token:" + verificationId
1878                                + " was not said to be complete");
1879                    }
1880
1881                    break;
1882                }
1883                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1884                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1885                            mInstantAppResolverConnection,
1886                            (InstantAppRequest) msg.obj,
1887                            mInstantAppInstallerActivity,
1888                            mHandler);
1889                }
1890            }
1891        }
1892    }
1893
1894    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1895        @Override
1896        public void onGidsChanged(int appId, int userId) {
1897            mHandler.post(new Runnable() {
1898                @Override
1899                public void run() {
1900                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1901                }
1902            });
1903        }
1904        @Override
1905        public void onPermissionGranted(int uid, int userId) {
1906            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1907
1908            // Not critical; if this is lost, the application has to request again.
1909            synchronized (mPackages) {
1910                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1911            }
1912        }
1913        @Override
1914        public void onInstallPermissionGranted() {
1915            synchronized (mPackages) {
1916                scheduleWriteSettingsLocked();
1917            }
1918        }
1919        @Override
1920        public void onPermissionRevoked(int uid, int userId) {
1921            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1922
1923            synchronized (mPackages) {
1924                // Critical; after this call the application should never have the permission
1925                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1926            }
1927
1928            final int appId = UserHandle.getAppId(uid);
1929            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1930        }
1931        @Override
1932        public void onInstallPermissionRevoked() {
1933            synchronized (mPackages) {
1934                scheduleWriteSettingsLocked();
1935            }
1936        }
1937        @Override
1938        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1939            synchronized (mPackages) {
1940                for (int userId : updatedUserIds) {
1941                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1942                }
1943            }
1944        }
1945        @Override
1946        public void onInstallPermissionUpdated() {
1947            synchronized (mPackages) {
1948                scheduleWriteSettingsLocked();
1949            }
1950        }
1951        @Override
1952        public void onPermissionRemoved() {
1953            synchronized (mPackages) {
1954                mSettings.writeLPr();
1955            }
1956        }
1957    };
1958
1959    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1960            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1961            boolean launchedForRestore, String installerPackage,
1962            IPackageInstallObserver2 installObserver) {
1963        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1964            // Send the removed broadcasts
1965            if (res.removedInfo != null) {
1966                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1967            }
1968
1969            // Now that we successfully installed the package, grant runtime
1970            // permissions if requested before broadcasting the install. Also
1971            // for legacy apps in permission review mode we clear the permission
1972            // review flag which is used to emulate runtime permissions for
1973            // legacy apps.
1974            if (grantPermissions) {
1975                final int callingUid = Binder.getCallingUid();
1976                mPermissionManager.grantRequestedRuntimePermissions(
1977                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1978                        mPermissionCallback);
1979            }
1980
1981            final boolean update = res.removedInfo != null
1982                    && res.removedInfo.removedPackage != null;
1983            final String installerPackageName =
1984                    res.installerPackageName != null
1985                            ? res.installerPackageName
1986                            : res.removedInfo != null
1987                                    ? res.removedInfo.installerPackageName
1988                                    : null;
1989
1990            // If this is the first time we have child packages for a disabled privileged
1991            // app that had no children, we grant requested runtime permissions to the new
1992            // children if the parent on the system image had them already granted.
1993            if (res.pkg.parentPackage != null) {
1994                final int callingUid = Binder.getCallingUid();
1995                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1996                        res.pkg, callingUid, mPermissionCallback);
1997            }
1998
1999            synchronized (mPackages) {
2000                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
2001            }
2002
2003            final String packageName = res.pkg.applicationInfo.packageName;
2004
2005            // Determine the set of users who are adding this package for
2006            // the first time vs. those who are seeing an update.
2007            int[] firstUserIds = EMPTY_INT_ARRAY;
2008            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
2009            int[] updateUserIds = EMPTY_INT_ARRAY;
2010            int[] instantUserIds = EMPTY_INT_ARRAY;
2011            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
2012            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
2013            for (int newUser : res.newUsers) {
2014                final boolean isInstantApp = ps.getInstantApp(newUser);
2015                if (allNewUsers) {
2016                    if (isInstantApp) {
2017                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2018                    } else {
2019                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2020                    }
2021                    continue;
2022                }
2023                boolean isNew = true;
2024                for (int origUser : res.origUsers) {
2025                    if (origUser == newUser) {
2026                        isNew = false;
2027                        break;
2028                    }
2029                }
2030                if (isNew) {
2031                    if (isInstantApp) {
2032                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2033                    } else {
2034                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2035                    }
2036                } else {
2037                    if (isInstantApp) {
2038                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2039                    } else {
2040                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2041                    }
2042                }
2043            }
2044
2045            // Send installed broadcasts if the package is not a static shared lib.
2046            if (res.pkg.staticSharedLibName == null) {
2047                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2048
2049                // Send added for users that see the package for the first time
2050                // sendPackageAddedForNewUsers also deals with system apps
2051                int appId = UserHandle.getAppId(res.uid);
2052                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2053                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2054                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2055
2056                // Send added for users that don't see the package for the first time
2057                Bundle extras = new Bundle(1);
2058                extras.putInt(Intent.EXTRA_UID, res.uid);
2059                if (update) {
2060                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2061                }
2062                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2063                        extras, 0 /*flags*/,
2064                        null /*targetPackage*/, null /*finishedReceiver*/,
2065                        updateUserIds, instantUserIds);
2066                if (installerPackageName != null) {
2067                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2068                            extras, 0 /*flags*/,
2069                            installerPackageName, null /*finishedReceiver*/,
2070                            updateUserIds, instantUserIds);
2071                }
2072
2073                // Send replaced for users that don't see the package for the first time
2074                if (update) {
2075                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2076                            packageName, extras, 0 /*flags*/,
2077                            null /*targetPackage*/, null /*finishedReceiver*/,
2078                            updateUserIds, instantUserIds);
2079                    if (installerPackageName != null) {
2080                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2081                                extras, 0 /*flags*/,
2082                                installerPackageName, null /*finishedReceiver*/,
2083                                updateUserIds, instantUserIds);
2084                    }
2085                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2086                            null /*package*/, null /*extras*/, 0 /*flags*/,
2087                            packageName /*targetPackage*/,
2088                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2089                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2090                    // First-install and we did a restore, so we're responsible for the
2091                    // first-launch broadcast.
2092                    if (DEBUG_BACKUP) {
2093                        Slog.i(TAG, "Post-restore of " + packageName
2094                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2095                    }
2096                    sendFirstLaunchBroadcast(packageName, installerPackage,
2097                            firstUserIds, firstInstantUserIds);
2098                }
2099
2100                // Send broadcast package appeared if forward locked/external for all users
2101                // treat asec-hosted packages like removable media on upgrade
2102                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2103                    if (DEBUG_INSTALL) {
2104                        Slog.i(TAG, "upgrading pkg " + res.pkg
2105                                + " is ASEC-hosted -> AVAILABLE");
2106                    }
2107                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2108                    ArrayList<String> pkgList = new ArrayList<>(1);
2109                    pkgList.add(packageName);
2110                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2111                }
2112            }
2113
2114            // Work that needs to happen on first install within each user
2115            if (firstUserIds != null && firstUserIds.length > 0) {
2116                synchronized (mPackages) {
2117                    for (int userId : firstUserIds) {
2118                        // If this app is a browser and it's newly-installed for some
2119                        // users, clear any default-browser state in those users. The
2120                        // app's nature doesn't depend on the user, so we can just check
2121                        // its browser nature in any user and generalize.
2122                        if (packageIsBrowser(packageName, userId)) {
2123                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2124                        }
2125
2126                        // We may also need to apply pending (restored) runtime
2127                        // permission grants within these users.
2128                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2129                    }
2130                }
2131            }
2132
2133            if (allNewUsers && !update) {
2134                notifyPackageAdded(packageName);
2135            }
2136
2137            // Log current value of "unknown sources" setting
2138            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2139                    getUnknownSourcesSettings());
2140
2141            // Remove the replaced package's older resources safely now
2142            // We delete after a gc for applications  on sdcard.
2143            if (res.removedInfo != null && res.removedInfo.args != null) {
2144                Runtime.getRuntime().gc();
2145                synchronized (mInstallLock) {
2146                    res.removedInfo.args.doPostDeleteLI(true);
2147                }
2148            } else {
2149                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2150                // and not block here.
2151                VMRuntime.getRuntime().requestConcurrentGC();
2152            }
2153
2154            // Notify DexManager that the package was installed for new users.
2155            // The updated users should already be indexed and the package code paths
2156            // should not change.
2157            // Don't notify the manager for ephemeral apps as they are not expected to
2158            // survive long enough to benefit of background optimizations.
2159            for (int userId : firstUserIds) {
2160                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2161                // There's a race currently where some install events may interleave with an uninstall.
2162                // This can lead to package info being null (b/36642664).
2163                if (info != null) {
2164                    mDexManager.notifyPackageInstalled(info, userId);
2165                }
2166            }
2167        }
2168
2169        // If someone is watching installs - notify them
2170        if (installObserver != null) {
2171            try {
2172                Bundle extras = extrasForInstallResult(res);
2173                installObserver.onPackageInstalled(res.name, res.returnCode,
2174                        res.returnMsg, extras);
2175            } catch (RemoteException e) {
2176                Slog.i(TAG, "Observer no longer exists.");
2177            }
2178        }
2179    }
2180
2181    private StorageEventListener mStorageListener = new StorageEventListener() {
2182        @Override
2183        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2184            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2185                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2186                    final String volumeUuid = vol.getFsUuid();
2187
2188                    // Clean up any users or apps that were removed or recreated
2189                    // while this volume was missing
2190                    sUserManager.reconcileUsers(volumeUuid);
2191                    reconcileApps(volumeUuid);
2192
2193                    // Clean up any install sessions that expired or were
2194                    // cancelled while this volume was missing
2195                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2196
2197                    loadPrivatePackages(vol);
2198
2199                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2200                    unloadPrivatePackages(vol);
2201                }
2202            }
2203        }
2204
2205        @Override
2206        public void onVolumeForgotten(String fsUuid) {
2207            if (TextUtils.isEmpty(fsUuid)) {
2208                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2209                return;
2210            }
2211
2212            // Remove any apps installed on the forgotten volume
2213            synchronized (mPackages) {
2214                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2215                for (PackageSetting ps : packages) {
2216                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2217                    deletePackageVersioned(new VersionedPackage(ps.name,
2218                            PackageManager.VERSION_CODE_HIGHEST),
2219                            new LegacyPackageDeleteObserver(null).getBinder(),
2220                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2221                    // Try very hard to release any references to this package
2222                    // so we don't risk the system server being killed due to
2223                    // open FDs
2224                    AttributeCache.instance().removePackage(ps.name);
2225                }
2226
2227                mSettings.onVolumeForgotten(fsUuid);
2228                mSettings.writeLPr();
2229            }
2230        }
2231    };
2232
2233    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2234        Bundle extras = null;
2235        switch (res.returnCode) {
2236            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2237                extras = new Bundle();
2238                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2239                        res.origPermission);
2240                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2241                        res.origPackage);
2242                break;
2243            }
2244            case PackageManager.INSTALL_SUCCEEDED: {
2245                extras = new Bundle();
2246                extras.putBoolean(Intent.EXTRA_REPLACING,
2247                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2248                break;
2249            }
2250        }
2251        return extras;
2252    }
2253
2254    void scheduleWriteSettingsLocked() {
2255        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2256            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2257        }
2258    }
2259
2260    void scheduleWritePackageListLocked(int userId) {
2261        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2262            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2263            msg.arg1 = userId;
2264            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2265        }
2266    }
2267
2268    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2269        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2270        scheduleWritePackageRestrictionsLocked(userId);
2271    }
2272
2273    void scheduleWritePackageRestrictionsLocked(int userId) {
2274        final int[] userIds = (userId == UserHandle.USER_ALL)
2275                ? sUserManager.getUserIds() : new int[]{userId};
2276        for (int nextUserId : userIds) {
2277            if (!sUserManager.exists(nextUserId)) return;
2278            mDirtyUsers.add(nextUserId);
2279            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2280                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2281            }
2282        }
2283    }
2284
2285    public static PackageManagerService main(Context context, Installer installer,
2286            boolean factoryTest, boolean onlyCore) {
2287        // Self-check for initial settings.
2288        PackageManagerServiceCompilerMapping.checkProperties();
2289
2290        PackageManagerService m = new PackageManagerService(context, installer,
2291                factoryTest, onlyCore);
2292        m.enableSystemUserPackages();
2293        ServiceManager.addService("package", m);
2294        final PackageManagerNative pmn = m.new PackageManagerNative();
2295        ServiceManager.addService("package_native", pmn);
2296        return m;
2297    }
2298
2299    private void enableSystemUserPackages() {
2300        if (!UserManager.isSplitSystemUser()) {
2301            return;
2302        }
2303        // For system user, enable apps based on the following conditions:
2304        // - app is whitelisted or belong to one of these groups:
2305        //   -- system app which has no launcher icons
2306        //   -- system app which has INTERACT_ACROSS_USERS permission
2307        //   -- system IME app
2308        // - app is not in the blacklist
2309        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2310        Set<String> enableApps = new ArraySet<>();
2311        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2312                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2313                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2314        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2315        enableApps.addAll(wlApps);
2316        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2317                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2318        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2319        enableApps.removeAll(blApps);
2320        Log.i(TAG, "Applications installed for system user: " + enableApps);
2321        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2322                UserHandle.SYSTEM);
2323        final int allAppsSize = allAps.size();
2324        synchronized (mPackages) {
2325            for (int i = 0; i < allAppsSize; i++) {
2326                String pName = allAps.get(i);
2327                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2328                // Should not happen, but we shouldn't be failing if it does
2329                if (pkgSetting == null) {
2330                    continue;
2331                }
2332                boolean install = enableApps.contains(pName);
2333                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2334                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2335                            + " for system user");
2336                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2337                }
2338            }
2339            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2340        }
2341    }
2342
2343    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2344        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2345                Context.DISPLAY_SERVICE);
2346        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2347    }
2348
2349    /**
2350     * Requests that files preopted on a secondary system partition be copied to the data partition
2351     * if possible.  Note that the actual copying of the files is accomplished by init for security
2352     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2353     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2354     */
2355    private static void requestCopyPreoptedFiles() {
2356        final int WAIT_TIME_MS = 100;
2357        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2358        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2359            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2360            // We will wait for up to 100 seconds.
2361            final long timeStart = SystemClock.uptimeMillis();
2362            final long timeEnd = timeStart + 100 * 1000;
2363            long timeNow = timeStart;
2364            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2365                try {
2366                    Thread.sleep(WAIT_TIME_MS);
2367                } catch (InterruptedException e) {
2368                    // Do nothing
2369                }
2370                timeNow = SystemClock.uptimeMillis();
2371                if (timeNow > timeEnd) {
2372                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2373                    Slog.wtf(TAG, "cppreopt did not finish!");
2374                    break;
2375                }
2376            }
2377
2378            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2379        }
2380    }
2381
2382    public PackageManagerService(Context context, Installer installer,
2383            boolean factoryTest, boolean onlyCore) {
2384        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2385        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2386        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2387                SystemClock.uptimeMillis());
2388
2389        if (mSdkVersion <= 0) {
2390            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2391        }
2392
2393        mContext = context;
2394
2395        mFactoryTest = factoryTest;
2396        mOnlyCore = onlyCore;
2397        mMetrics = new DisplayMetrics();
2398        mInstaller = installer;
2399
2400        // Create sub-components that provide services / data. Order here is important.
2401        synchronized (mInstallLock) {
2402        synchronized (mPackages) {
2403            // Expose private service for system components to use.
2404            LocalServices.addService(
2405                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2406            sUserManager = new UserManagerService(context, this,
2407                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2408            mPermissionManager = PermissionManagerService.create(context,
2409                    new DefaultPermissionGrantedCallback() {
2410                        @Override
2411                        public void onDefaultRuntimePermissionsGranted(int userId) {
2412                            synchronized(mPackages) {
2413                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2414                            }
2415                        }
2416                    }, mPackages /*externalLock*/);
2417            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2418            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2419        }
2420        }
2421        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2422                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2423        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2424                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2425        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2426                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2427        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2428                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2429        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2430                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2431        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2432                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2433        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2434                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2435
2436        String separateProcesses = SystemProperties.get("debug.separate_processes");
2437        if (separateProcesses != null && separateProcesses.length() > 0) {
2438            if ("*".equals(separateProcesses)) {
2439                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2440                mSeparateProcesses = null;
2441                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2442            } else {
2443                mDefParseFlags = 0;
2444                mSeparateProcesses = separateProcesses.split(",");
2445                Slog.w(TAG, "Running with debug.separate_processes: "
2446                        + separateProcesses);
2447            }
2448        } else {
2449            mDefParseFlags = 0;
2450            mSeparateProcesses = null;
2451        }
2452
2453        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2454                "*dexopt*");
2455        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2456                installer, mInstallLock);
2457        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2458                dexManagerListener);
2459        mArtManagerService = new ArtManagerService(this, installer, mInstallLock);
2460        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2461
2462        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2463                FgThread.get().getLooper());
2464
2465        getDefaultDisplayMetrics(context, mMetrics);
2466
2467        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2468        SystemConfig systemConfig = SystemConfig.getInstance();
2469        mAvailableFeatures = systemConfig.getAvailableFeatures();
2470        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2471
2472        mProtectedPackages = new ProtectedPackages(mContext);
2473
2474        synchronized (mInstallLock) {
2475        // writer
2476        synchronized (mPackages) {
2477            mHandlerThread = new ServiceThread(TAG,
2478                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2479            mHandlerThread.start();
2480            mHandler = new PackageHandler(mHandlerThread.getLooper());
2481            mProcessLoggingHandler = new ProcessLoggingHandler();
2482            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2483            mInstantAppRegistry = new InstantAppRegistry(this);
2484
2485            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2486            final int builtInLibCount = libConfig.size();
2487            for (int i = 0; i < builtInLibCount; i++) {
2488                String name = libConfig.keyAt(i);
2489                String path = libConfig.valueAt(i);
2490                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2491                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2492            }
2493
2494            SELinuxMMAC.readInstallPolicy();
2495
2496            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2497            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2498            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2499
2500            // Clean up orphaned packages for which the code path doesn't exist
2501            // and they are an update to a system app - caused by bug/32321269
2502            final int packageSettingCount = mSettings.mPackages.size();
2503            for (int i = packageSettingCount - 1; i >= 0; i--) {
2504                PackageSetting ps = mSettings.mPackages.valueAt(i);
2505                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2506                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2507                    mSettings.mPackages.removeAt(i);
2508                    mSettings.enableSystemPackageLPw(ps.name);
2509                }
2510            }
2511
2512            if (mFirstBoot) {
2513                requestCopyPreoptedFiles();
2514            }
2515
2516            String customResolverActivity = Resources.getSystem().getString(
2517                    R.string.config_customResolverActivity);
2518            if (TextUtils.isEmpty(customResolverActivity)) {
2519                customResolverActivity = null;
2520            } else {
2521                mCustomResolverComponentName = ComponentName.unflattenFromString(
2522                        customResolverActivity);
2523            }
2524
2525            long startTime = SystemClock.uptimeMillis();
2526
2527            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2528                    startTime);
2529
2530            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2531            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2532
2533            if (bootClassPath == null) {
2534                Slog.w(TAG, "No BOOTCLASSPATH found!");
2535            }
2536
2537            if (systemServerClassPath == null) {
2538                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2539            }
2540
2541            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2542
2543            final VersionInfo ver = mSettings.getInternalVersion();
2544            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2545            if (mIsUpgrade) {
2546                logCriticalInfo(Log.INFO,
2547                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2548            }
2549
2550            // when upgrading from pre-M, promote system app permissions from install to runtime
2551            mPromoteSystemApps =
2552                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2553
2554            // When upgrading from pre-N, we need to handle package extraction like first boot,
2555            // as there is no profiling data available.
2556            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2557
2558            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2559
2560            // save off the names of pre-existing system packages prior to scanning; we don't
2561            // want to automatically grant runtime permissions for new system apps
2562            if (mPromoteSystemApps) {
2563                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2564                while (pkgSettingIter.hasNext()) {
2565                    PackageSetting ps = pkgSettingIter.next();
2566                    if (isSystemApp(ps)) {
2567                        mExistingSystemPackages.add(ps.name);
2568                    }
2569                }
2570            }
2571
2572            mCacheDir = preparePackageParserCache(mIsUpgrade);
2573
2574            // Set flag to monitor and not change apk file paths when
2575            // scanning install directories.
2576            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2577
2578            if (mIsUpgrade || mFirstBoot) {
2579                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2580            }
2581
2582            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2583            // For security and version matching reason, only consider
2584            // overlay packages if they reside in the right directory.
2585            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2586                    mDefParseFlags
2587                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2588                    scanFlags
2589                    | SCAN_AS_SYSTEM
2590                    | SCAN_AS_VENDOR,
2591                    0);
2592            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2593                    mDefParseFlags
2594                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2595                    scanFlags
2596                    | SCAN_AS_SYSTEM
2597                    | SCAN_AS_PRODUCT,
2598                    0);
2599
2600            mParallelPackageParserCallback.findStaticOverlayPackages();
2601
2602            // Find base frameworks (resource packages without code).
2603            scanDirTracedLI(frameworkDir,
2604                    mDefParseFlags
2605                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2606                    scanFlags
2607                    | SCAN_NO_DEX
2608                    | SCAN_AS_SYSTEM
2609                    | SCAN_AS_PRIVILEGED,
2610                    0);
2611
2612            // Collect privileged system packages.
2613            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2614            scanDirTracedLI(privilegedAppDir,
2615                    mDefParseFlags
2616                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2617                    scanFlags
2618                    | SCAN_AS_SYSTEM
2619                    | SCAN_AS_PRIVILEGED,
2620                    0);
2621
2622            // Collect ordinary system packages.
2623            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2624            scanDirTracedLI(systemAppDir,
2625                    mDefParseFlags
2626                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2627                    scanFlags
2628                    | SCAN_AS_SYSTEM,
2629                    0);
2630
2631            // Collect privileged vendor packages.
2632            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2633            try {
2634                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2635            } catch (IOException e) {
2636                // failed to look up canonical path, continue with original one
2637            }
2638            scanDirTracedLI(privilegedVendorAppDir,
2639                    mDefParseFlags
2640                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2641                    scanFlags
2642                    | SCAN_AS_SYSTEM
2643                    | SCAN_AS_VENDOR
2644                    | SCAN_AS_PRIVILEGED,
2645                    0);
2646
2647            // Collect ordinary vendor packages.
2648            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2649            try {
2650                vendorAppDir = vendorAppDir.getCanonicalFile();
2651            } catch (IOException e) {
2652                // failed to look up canonical path, continue with original one
2653            }
2654            scanDirTracedLI(vendorAppDir,
2655                    mDefParseFlags
2656                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2657                    scanFlags
2658                    | SCAN_AS_SYSTEM
2659                    | SCAN_AS_VENDOR,
2660                    0);
2661
2662            // Collect privileged odm packages. /odm is another vendor partition
2663            // other than /vendor.
2664            File privilegedOdmAppDir = new File(Environment.getOdmDirectory(),
2665                        "priv-app");
2666            try {
2667                privilegedOdmAppDir = privilegedOdmAppDir.getCanonicalFile();
2668            } catch (IOException e) {
2669                // failed to look up canonical path, continue with original one
2670            }
2671            scanDirTracedLI(privilegedOdmAppDir,
2672                    mDefParseFlags
2673                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2674                    scanFlags
2675                    | SCAN_AS_SYSTEM
2676                    | SCAN_AS_VENDOR
2677                    | SCAN_AS_PRIVILEGED,
2678                    0);
2679
2680            // Collect ordinary odm packages. /odm is another vendor partition
2681            // other than /vendor.
2682            File odmAppDir = new File(Environment.getOdmDirectory(), "app");
2683            try {
2684                odmAppDir = odmAppDir.getCanonicalFile();
2685            } catch (IOException e) {
2686                // failed to look up canonical path, continue with original one
2687            }
2688            scanDirTracedLI(odmAppDir,
2689                    mDefParseFlags
2690                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2691                    scanFlags
2692                    | SCAN_AS_SYSTEM
2693                    | SCAN_AS_VENDOR,
2694                    0);
2695
2696            // Collect all OEM packages.
2697            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2698            scanDirTracedLI(oemAppDir,
2699                    mDefParseFlags
2700                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2701                    scanFlags
2702                    | SCAN_AS_SYSTEM
2703                    | SCAN_AS_OEM,
2704                    0);
2705
2706            // Collected privileged product packages.
2707            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2708            try {
2709                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2710            } catch (IOException e) {
2711                // failed to look up canonical path, continue with original one
2712            }
2713            scanDirTracedLI(privilegedProductAppDir,
2714                    mDefParseFlags
2715                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2716                    scanFlags
2717                    | SCAN_AS_SYSTEM
2718                    | SCAN_AS_PRODUCT
2719                    | SCAN_AS_PRIVILEGED,
2720                    0);
2721
2722            // Collect ordinary product packages.
2723            File productAppDir = new File(Environment.getProductDirectory(), "app");
2724            try {
2725                productAppDir = productAppDir.getCanonicalFile();
2726            } catch (IOException e) {
2727                // failed to look up canonical path, continue with original one
2728            }
2729            scanDirTracedLI(productAppDir,
2730                    mDefParseFlags
2731                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2732                    scanFlags
2733                    | SCAN_AS_SYSTEM
2734                    | SCAN_AS_PRODUCT,
2735                    0);
2736
2737            // Prune any system packages that no longer exist.
2738            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2739            // Stub packages must either be replaced with full versions in the /data
2740            // partition or be disabled.
2741            final List<String> stubSystemApps = new ArrayList<>();
2742            if (!mOnlyCore) {
2743                // do this first before mucking with mPackages for the "expecting better" case
2744                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2745                while (pkgIterator.hasNext()) {
2746                    final PackageParser.Package pkg = pkgIterator.next();
2747                    if (pkg.isStub) {
2748                        stubSystemApps.add(pkg.packageName);
2749                    }
2750                }
2751
2752                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2753                while (psit.hasNext()) {
2754                    PackageSetting ps = psit.next();
2755
2756                    /*
2757                     * If this is not a system app, it can't be a
2758                     * disable system app.
2759                     */
2760                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2761                        continue;
2762                    }
2763
2764                    /*
2765                     * If the package is scanned, it's not erased.
2766                     */
2767                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2768                    if (scannedPkg != null) {
2769                        /*
2770                         * If the system app is both scanned and in the
2771                         * disabled packages list, then it must have been
2772                         * added via OTA. Remove it from the currently
2773                         * scanned package so the previously user-installed
2774                         * application can be scanned.
2775                         */
2776                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2777                            logCriticalInfo(Log.WARN,
2778                                    "Expecting better updated system app for " + ps.name
2779                                    + "; removing system app.  Last known"
2780                                    + " codePath=" + ps.codePathString
2781                                    + ", versionCode=" + ps.versionCode
2782                                    + "; scanned versionCode=" + scannedPkg.getLongVersionCode());
2783                            removePackageLI(scannedPkg, true);
2784                            mExpectingBetter.put(ps.name, ps.codePath);
2785                        }
2786
2787                        continue;
2788                    }
2789
2790                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2791                        psit.remove();
2792                        logCriticalInfo(Log.WARN, "System package " + ps.name
2793                                + " no longer exists; it's data will be wiped");
2794                        // Actual deletion of code and data will be handled by later
2795                        // reconciliation step
2796                    } else {
2797                        // we still have a disabled system package, but, it still might have
2798                        // been removed. check the code path still exists and check there's
2799                        // still a package. the latter can happen if an OTA keeps the same
2800                        // code path, but, changes the package name.
2801                        final PackageSetting disabledPs =
2802                                mSettings.getDisabledSystemPkgLPr(ps.name);
2803                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2804                                || disabledPs.pkg == null) {
2805                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2806                        }
2807                    }
2808                }
2809            }
2810
2811            //delete tmp files
2812            deleteTempPackageFiles();
2813
2814            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2815
2816            // Remove any shared userIDs that have no associated packages
2817            mSettings.pruneSharedUsersLPw();
2818            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2819            final int systemPackagesCount = mPackages.size();
2820            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2821                    + " ms, packageCount: " + systemPackagesCount
2822                    + " , timePerPackage: "
2823                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2824                    + " , cached: " + cachedSystemApps);
2825            if (mIsUpgrade && systemPackagesCount > 0) {
2826                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2827                        ((int) systemScanTime) / systemPackagesCount);
2828            }
2829            if (!mOnlyCore) {
2830                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2831                        SystemClock.uptimeMillis());
2832                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2833
2834                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2835                        | PackageParser.PARSE_FORWARD_LOCK,
2836                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2837
2838                // Remove disable package settings for updated system apps that were
2839                // removed via an OTA. If the update is no longer present, remove the
2840                // app completely. Otherwise, revoke their system privileges.
2841                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2842                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2843                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2844                    final String msg;
2845                    if (deletedPkg == null) {
2846                        // should have found an update, but, we didn't; remove everything
2847                        msg = "Updated system package " + deletedAppName
2848                                + " no longer exists; removing its data";
2849                        // Actual deletion of code and data will be handled by later
2850                        // reconciliation step
2851                    } else {
2852                        // found an update; revoke system privileges
2853                        msg = "Updated system package + " + deletedAppName
2854                                + " no longer exists; revoking system privileges";
2855
2856                        // Don't do anything if a stub is removed from the system image. If
2857                        // we were to remove the uncompressed version from the /data partition,
2858                        // this is where it'd be done.
2859
2860                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2861                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2862                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2863                    }
2864                    logCriticalInfo(Log.WARN, msg);
2865                }
2866
2867                /*
2868                 * Make sure all system apps that we expected to appear on
2869                 * the userdata partition actually showed up. If they never
2870                 * appeared, crawl back and revive the system version.
2871                 */
2872                for (int i = 0; i < mExpectingBetter.size(); i++) {
2873                    final String packageName = mExpectingBetter.keyAt(i);
2874                    if (!mPackages.containsKey(packageName)) {
2875                        final File scanFile = mExpectingBetter.valueAt(i);
2876
2877                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2878                                + " but never showed up; reverting to system");
2879
2880                        final @ParseFlags int reparseFlags;
2881                        final @ScanFlags int rescanFlags;
2882                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2883                            reparseFlags =
2884                                    mDefParseFlags |
2885                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2886                            rescanFlags =
2887                                    scanFlags
2888                                    | SCAN_AS_SYSTEM
2889                                    | SCAN_AS_PRIVILEGED;
2890                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2891                            reparseFlags =
2892                                    mDefParseFlags |
2893                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2894                            rescanFlags =
2895                                    scanFlags
2896                                    | SCAN_AS_SYSTEM;
2897                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)
2898                                || FileUtils.contains(privilegedOdmAppDir, scanFile)) {
2899                            reparseFlags =
2900                                    mDefParseFlags |
2901                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2902                            rescanFlags =
2903                                    scanFlags
2904                                    | SCAN_AS_SYSTEM
2905                                    | SCAN_AS_VENDOR
2906                                    | SCAN_AS_PRIVILEGED;
2907                        } else if (FileUtils.contains(vendorAppDir, scanFile)
2908                                || FileUtils.contains(odmAppDir, scanFile)) {
2909                            reparseFlags =
2910                                    mDefParseFlags |
2911                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2912                            rescanFlags =
2913                                    scanFlags
2914                                    | SCAN_AS_SYSTEM
2915                                    | SCAN_AS_VENDOR;
2916                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2917                            reparseFlags =
2918                                    mDefParseFlags |
2919                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2920                            rescanFlags =
2921                                    scanFlags
2922                                    | SCAN_AS_SYSTEM
2923                                    | SCAN_AS_OEM;
2924                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2925                            reparseFlags =
2926                                    mDefParseFlags |
2927                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2928                            rescanFlags =
2929                                    scanFlags
2930                                    | SCAN_AS_SYSTEM
2931                                    | SCAN_AS_PRODUCT
2932                                    | SCAN_AS_PRIVILEGED;
2933                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2934                            reparseFlags =
2935                                    mDefParseFlags |
2936                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2937                            rescanFlags =
2938                                    scanFlags
2939                                    | SCAN_AS_SYSTEM
2940                                    | SCAN_AS_PRODUCT;
2941                        } else {
2942                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2943                            continue;
2944                        }
2945
2946                        mSettings.enableSystemPackageLPw(packageName);
2947
2948                        try {
2949                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2950                        } catch (PackageManagerException e) {
2951                            Slog.e(TAG, "Failed to parse original system package: "
2952                                    + e.getMessage());
2953                        }
2954                    }
2955                }
2956
2957                // Uncompress and install any stubbed system applications.
2958                // This must be done last to ensure all stubs are replaced or disabled.
2959                decompressSystemApplications(stubSystemApps, scanFlags);
2960
2961                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2962                                - cachedSystemApps;
2963
2964                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2965                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2966                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2967                        + " ms, packageCount: " + dataPackagesCount
2968                        + " , timePerPackage: "
2969                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2970                        + " , cached: " + cachedNonSystemApps);
2971                if (mIsUpgrade && dataPackagesCount > 0) {
2972                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2973                            ((int) dataScanTime) / dataPackagesCount);
2974                }
2975            }
2976            mExpectingBetter.clear();
2977
2978            // Resolve the storage manager.
2979            mStorageManagerPackage = getStorageManagerPackageName();
2980
2981            // Resolve protected action filters. Only the setup wizard is allowed to
2982            // have a high priority filter for these actions.
2983            mSetupWizardPackage = getSetupWizardPackageName();
2984            if (mProtectedFilters.size() > 0) {
2985                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2986                    Slog.i(TAG, "No setup wizard;"
2987                        + " All protected intents capped to priority 0");
2988                }
2989                for (ActivityIntentInfo filter : mProtectedFilters) {
2990                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2991                        if (DEBUG_FILTERS) {
2992                            Slog.i(TAG, "Found setup wizard;"
2993                                + " allow priority " + filter.getPriority() + ";"
2994                                + " package: " + filter.activity.info.packageName
2995                                + " activity: " + filter.activity.className
2996                                + " priority: " + filter.getPriority());
2997                        }
2998                        // skip setup wizard; allow it to keep the high priority filter
2999                        continue;
3000                    }
3001                    if (DEBUG_FILTERS) {
3002                        Slog.i(TAG, "Protected action; cap priority to 0;"
3003                                + " package: " + filter.activity.info.packageName
3004                                + " activity: " + filter.activity.className
3005                                + " origPrio: " + filter.getPriority());
3006                    }
3007                    filter.setPriority(0);
3008                }
3009            }
3010
3011            mSystemTextClassifierPackage = getSystemTextClassifierPackageName();
3012
3013            mDeferProtectedFilters = false;
3014            mProtectedFilters.clear();
3015
3016            // Now that we know all of the shared libraries, update all clients to have
3017            // the correct library paths.
3018            updateAllSharedLibrariesLPw(null);
3019
3020            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
3021                // NOTE: We ignore potential failures here during a system scan (like
3022                // the rest of the commands above) because there's precious little we
3023                // can do about it. A settings error is reported, though.
3024                final List<String> changedAbiCodePath =
3025                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
3026                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
3027                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
3028                        final String codePathString = changedAbiCodePath.get(i);
3029                        try {
3030                            mInstaller.rmdex(codePathString,
3031                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
3032                        } catch (InstallerException ignored) {
3033                        }
3034                    }
3035                }
3036                // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same
3037                // SELinux domain.
3038                setting.fixSeInfoLocked();
3039            }
3040
3041            // Now that we know all the packages we are keeping,
3042            // read and update their last usage times.
3043            mPackageUsage.read(mPackages);
3044            mCompilerStats.read();
3045
3046            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
3047                    SystemClock.uptimeMillis());
3048            Slog.i(TAG, "Time to scan packages: "
3049                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
3050                    + " seconds");
3051
3052            // If the platform SDK has changed since the last time we booted,
3053            // we need to re-grant app permission to catch any new ones that
3054            // appear.  This is really a hack, and means that apps can in some
3055            // cases get permissions that the user didn't initially explicitly
3056            // allow...  it would be nice to have some better way to handle
3057            // this situation.
3058            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3059            if (sdkUpdated) {
3060                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3061                        + mSdkVersion + "; regranting permissions for internal storage");
3062            }
3063            mPermissionManager.updateAllPermissions(
3064                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3065                    mPermissionCallback);
3066            ver.sdkVersion = mSdkVersion;
3067
3068            // If this is the first boot or an update from pre-M, and it is a normal
3069            // boot, then we need to initialize the default preferred apps across
3070            // all defined users.
3071            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3072                for (UserInfo user : sUserManager.getUsers(true)) {
3073                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3074                    applyFactoryDefaultBrowserLPw(user.id);
3075                    primeDomainVerificationsLPw(user.id);
3076                }
3077            }
3078
3079            // Prepare storage for system user really early during boot,
3080            // since core system apps like SettingsProvider and SystemUI
3081            // can't wait for user to start
3082            final int storageFlags;
3083            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3084                storageFlags = StorageManager.FLAG_STORAGE_DE;
3085            } else {
3086                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3087            }
3088            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3089                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3090                    true /* onlyCoreApps */);
3091            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3092                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3093                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3094                traceLog.traceBegin("AppDataFixup");
3095                try {
3096                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3097                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3098                } catch (InstallerException e) {
3099                    Slog.w(TAG, "Trouble fixing GIDs", e);
3100                }
3101                traceLog.traceEnd();
3102
3103                traceLog.traceBegin("AppDataPrepare");
3104                if (deferPackages == null || deferPackages.isEmpty()) {
3105                    return;
3106                }
3107                int count = 0;
3108                for (String pkgName : deferPackages) {
3109                    PackageParser.Package pkg = null;
3110                    synchronized (mPackages) {
3111                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3112                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3113                            pkg = ps.pkg;
3114                        }
3115                    }
3116                    if (pkg != null) {
3117                        synchronized (mInstallLock) {
3118                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3119                                    true /* maybeMigrateAppData */);
3120                        }
3121                        count++;
3122                    }
3123                }
3124                traceLog.traceEnd();
3125                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3126            }, "prepareAppData");
3127
3128            // If this is first boot after an OTA, and a normal boot, then
3129            // we need to clear code cache directories.
3130            // Note that we do *not* clear the application profiles. These remain valid
3131            // across OTAs and are used to drive profile verification (post OTA) and
3132            // profile compilation (without waiting to collect a fresh set of profiles).
3133            if (mIsUpgrade && !onlyCore) {
3134                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3135                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3136                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3137                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3138                        // No apps are running this early, so no need to freeze
3139                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3140                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3141                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3142                    }
3143                }
3144                ver.fingerprint = Build.FINGERPRINT;
3145            }
3146
3147            checkDefaultBrowser();
3148
3149            // clear only after permissions and other defaults have been updated
3150            mExistingSystemPackages.clear();
3151            mPromoteSystemApps = false;
3152
3153            // All the changes are done during package scanning.
3154            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3155
3156            // can downgrade to reader
3157            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3158            mSettings.writeLPr();
3159            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3160            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3161                    SystemClock.uptimeMillis());
3162
3163            if (!mOnlyCore) {
3164                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3165                mRequiredInstallerPackage = getRequiredInstallerLPr();
3166                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3167                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3168                if (mIntentFilterVerifierComponent != null) {
3169                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3170                            mIntentFilterVerifierComponent);
3171                } else {
3172                    mIntentFilterVerifier = null;
3173                }
3174                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3175                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3176                        SharedLibraryInfo.VERSION_UNDEFINED);
3177                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3178                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3179                        SharedLibraryInfo.VERSION_UNDEFINED);
3180            } else {
3181                mRequiredVerifierPackage = null;
3182                mRequiredInstallerPackage = null;
3183                mRequiredUninstallerPackage = null;
3184                mIntentFilterVerifierComponent = null;
3185                mIntentFilterVerifier = null;
3186                mServicesSystemSharedLibraryPackageName = null;
3187                mSharedSystemSharedLibraryPackageName = null;
3188            }
3189
3190            mInstallerService = new PackageInstallerService(context, this);
3191            final Pair<ComponentName, String> instantAppResolverComponent =
3192                    getInstantAppResolverLPr();
3193            if (instantAppResolverComponent != null) {
3194                if (DEBUG_INSTANT) {
3195                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3196                }
3197                mInstantAppResolverConnection = new InstantAppResolverConnection(
3198                        mContext, instantAppResolverComponent.first,
3199                        instantAppResolverComponent.second);
3200                mInstantAppResolverSettingsComponent =
3201                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3202            } else {
3203                mInstantAppResolverConnection = null;
3204                mInstantAppResolverSettingsComponent = null;
3205            }
3206            updateInstantAppInstallerLocked(null);
3207
3208            // Read and update the usage of dex files.
3209            // Do this at the end of PM init so that all the packages have their
3210            // data directory reconciled.
3211            // At this point we know the code paths of the packages, so we can validate
3212            // the disk file and build the internal cache.
3213            // The usage file is expected to be small so loading and verifying it
3214            // should take a fairly small time compare to the other activities (e.g. package
3215            // scanning).
3216            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3217            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3218            for (int userId : currentUserIds) {
3219                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3220            }
3221            mDexManager.load(userPackages);
3222            if (mIsUpgrade) {
3223                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3224                        (int) (SystemClock.uptimeMillis() - startTime));
3225            }
3226        } // synchronized (mPackages)
3227        } // synchronized (mInstallLock)
3228
3229        // Now after opening every single application zip, make sure they
3230        // are all flushed.  Not really needed, but keeps things nice and
3231        // tidy.
3232        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3233        Runtime.getRuntime().gc();
3234        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3235
3236        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3237        FallbackCategoryProvider.loadFallbacks();
3238        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3239
3240        // The initial scanning above does many calls into installd while
3241        // holding the mPackages lock, but we're mostly interested in yelling
3242        // once we have a booted system.
3243        mInstaller.setWarnIfHeld(mPackages);
3244
3245        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3246    }
3247
3248    /**
3249     * Uncompress and install stub applications.
3250     * <p>In order to save space on the system partition, some applications are shipped in a
3251     * compressed form. In addition the compressed bits for the full application, the
3252     * system image contains a tiny stub comprised of only the Android manifest.
3253     * <p>During the first boot, attempt to uncompress and install the full application. If
3254     * the application can't be installed for any reason, disable the stub and prevent
3255     * uncompressing the full application during future boots.
3256     * <p>In order to forcefully attempt an installation of a full application, go to app
3257     * settings and enable the application.
3258     */
3259    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3260        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3261            final String pkgName = stubSystemApps.get(i);
3262            // skip if the system package is already disabled
3263            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3264                stubSystemApps.remove(i);
3265                continue;
3266            }
3267            // skip if the package isn't installed (?!); this should never happen
3268            final PackageParser.Package pkg = mPackages.get(pkgName);
3269            if (pkg == null) {
3270                stubSystemApps.remove(i);
3271                continue;
3272            }
3273            // skip if the package has been disabled by the user
3274            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3275            if (ps != null) {
3276                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3277                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3278                    stubSystemApps.remove(i);
3279                    continue;
3280                }
3281            }
3282
3283            if (DEBUG_COMPRESSION) {
3284                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3285            }
3286
3287            // uncompress the binary to its eventual destination on /data
3288            final File scanFile = decompressPackage(pkg);
3289            if (scanFile == null) {
3290                continue;
3291            }
3292
3293            // install the package to replace the stub on /system
3294            try {
3295                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3296                removePackageLI(pkg, true /*chatty*/);
3297                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3298                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3299                        UserHandle.USER_SYSTEM, "android");
3300                stubSystemApps.remove(i);
3301                continue;
3302            } catch (PackageManagerException e) {
3303                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3304            }
3305
3306            // any failed attempt to install the package will be cleaned up later
3307        }
3308
3309        // disable any stub still left; these failed to install the full application
3310        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3311            final String pkgName = stubSystemApps.get(i);
3312            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3313            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3314                    UserHandle.USER_SYSTEM, "android");
3315            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3316        }
3317    }
3318
3319    /**
3320     * Decompresses the given package on the system image onto
3321     * the /data partition.
3322     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3323     */
3324    private File decompressPackage(PackageParser.Package pkg) {
3325        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3326        if (compressedFiles == null || compressedFiles.length == 0) {
3327            if (DEBUG_COMPRESSION) {
3328                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3329            }
3330            return null;
3331        }
3332        final File dstCodePath =
3333                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3334        int ret = PackageManager.INSTALL_SUCCEEDED;
3335        try {
3336            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3337            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3338            for (File srcFile : compressedFiles) {
3339                final String srcFileName = srcFile.getName();
3340                final String dstFileName = srcFileName.substring(
3341                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3342                final File dstFile = new File(dstCodePath, dstFileName);
3343                ret = decompressFile(srcFile, dstFile);
3344                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3345                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3346                            + "; pkg: " + pkg.packageName
3347                            + ", file: " + dstFileName);
3348                    break;
3349                }
3350            }
3351        } catch (ErrnoException e) {
3352            logCriticalInfo(Log.ERROR, "Failed to decompress"
3353                    + "; pkg: " + pkg.packageName
3354                    + ", err: " + e.errno);
3355        }
3356        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3357            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3358            NativeLibraryHelper.Handle handle = null;
3359            try {
3360                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3361                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3362                        null /*abiOverride*/);
3363            } catch (IOException e) {
3364                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3365                        + "; pkg: " + pkg.packageName);
3366                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3367            } finally {
3368                IoUtils.closeQuietly(handle);
3369            }
3370        }
3371        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3372            if (dstCodePath == null || !dstCodePath.exists()) {
3373                return null;
3374            }
3375            removeCodePathLI(dstCodePath);
3376            return null;
3377        }
3378
3379        return dstCodePath;
3380    }
3381
3382    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3383        // we're only interested in updating the installer appliction when 1) it's not
3384        // already set or 2) the modified package is the installer
3385        if (mInstantAppInstallerActivity != null
3386                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3387                        .equals(modifiedPackage)) {
3388            return;
3389        }
3390        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3391    }
3392
3393    private static File preparePackageParserCache(boolean isUpgrade) {
3394        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3395            return null;
3396        }
3397
3398        // Disable package parsing on eng builds to allow for faster incremental development.
3399        if (Build.IS_ENG) {
3400            return null;
3401        }
3402
3403        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3404            Slog.i(TAG, "Disabling package parser cache due to system property.");
3405            return null;
3406        }
3407
3408        // The base directory for the package parser cache lives under /data/system/.
3409        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3410                "package_cache");
3411        if (cacheBaseDir == null) {
3412            return null;
3413        }
3414
3415        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3416        // This also serves to "GC" unused entries when the package cache version changes (which
3417        // can only happen during upgrades).
3418        if (isUpgrade) {
3419            FileUtils.deleteContents(cacheBaseDir);
3420        }
3421
3422
3423        // Return the versioned package cache directory. This is something like
3424        // "/data/system/package_cache/1"
3425        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3426
3427        if (cacheDir == null) {
3428            // Something went wrong. Attempt to delete everything and return.
3429            Slog.wtf(TAG, "Cache directory cannot be created - wiping base dir " + cacheBaseDir);
3430            FileUtils.deleteContentsAndDir(cacheBaseDir);
3431            return null;
3432        }
3433
3434        // The following is a workaround to aid development on non-numbered userdebug
3435        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3436        // the system partition is newer.
3437        //
3438        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3439        // that starts with "eng." to signify that this is an engineering build and not
3440        // destined for release.
3441        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3442            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3443
3444            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3445            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3446            // in general and should not be used for production changes. In this specific case,
3447            // we know that they will work.
3448            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3449            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3450                FileUtils.deleteContents(cacheBaseDir);
3451                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3452            }
3453        }
3454
3455        return cacheDir;
3456    }
3457
3458    @Override
3459    public boolean isFirstBoot() {
3460        // allow instant applications
3461        return mFirstBoot;
3462    }
3463
3464    @Override
3465    public boolean isOnlyCoreApps() {
3466        // allow instant applications
3467        return mOnlyCore;
3468    }
3469
3470    @Override
3471    public boolean isUpgrade() {
3472        // allow instant applications
3473        // The system property allows testing ota flow when upgraded to the same image.
3474        return mIsUpgrade || SystemProperties.getBoolean(
3475                "persist.pm.mock-upgrade", false /* default */);
3476    }
3477
3478    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3479        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3480
3481        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3482                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3483                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3484        if (matches.size() == 1) {
3485            return matches.get(0).getComponentInfo().packageName;
3486        } else if (matches.size() == 0) {
3487            Log.e(TAG, "There should probably be a verifier, but, none were found");
3488            return null;
3489        }
3490        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3491    }
3492
3493    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3494        synchronized (mPackages) {
3495            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3496            if (libraryEntry == null) {
3497                throw new IllegalStateException("Missing required shared library:" + name);
3498            }
3499            return libraryEntry.apk;
3500        }
3501    }
3502
3503    private @NonNull String getRequiredInstallerLPr() {
3504        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3505        intent.addCategory(Intent.CATEGORY_DEFAULT);
3506        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3507
3508        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3509                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3510                UserHandle.USER_SYSTEM);
3511        if (matches.size() == 1) {
3512            ResolveInfo resolveInfo = matches.get(0);
3513            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3514                throw new RuntimeException("The installer must be a privileged app");
3515            }
3516            return matches.get(0).getComponentInfo().packageName;
3517        } else {
3518            throw new RuntimeException("There must be exactly one installer; found " + matches);
3519        }
3520    }
3521
3522    private @NonNull String getRequiredUninstallerLPr() {
3523        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3524        intent.addCategory(Intent.CATEGORY_DEFAULT);
3525        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3526
3527        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3528                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3529                UserHandle.USER_SYSTEM);
3530        if (resolveInfo == null ||
3531                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3532            throw new RuntimeException("There must be exactly one uninstaller; found "
3533                    + resolveInfo);
3534        }
3535        return resolveInfo.getComponentInfo().packageName;
3536    }
3537
3538    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3539        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3540
3541        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3542                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3543                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3544        ResolveInfo best = null;
3545        final int N = matches.size();
3546        for (int i = 0; i < N; i++) {
3547            final ResolveInfo cur = matches.get(i);
3548            final String packageName = cur.getComponentInfo().packageName;
3549            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3550                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3551                continue;
3552            }
3553
3554            if (best == null || cur.priority > best.priority) {
3555                best = cur;
3556            }
3557        }
3558
3559        if (best != null) {
3560            return best.getComponentInfo().getComponentName();
3561        }
3562        Slog.w(TAG, "Intent filter verifier not found");
3563        return null;
3564    }
3565
3566    @Override
3567    public @Nullable ComponentName getInstantAppResolverComponent() {
3568        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3569            return null;
3570        }
3571        synchronized (mPackages) {
3572            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3573            if (instantAppResolver == null) {
3574                return null;
3575            }
3576            return instantAppResolver.first;
3577        }
3578    }
3579
3580    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3581        final String[] packageArray =
3582                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3583        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3584            if (DEBUG_INSTANT) {
3585                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3586            }
3587            return null;
3588        }
3589
3590        final int callingUid = Binder.getCallingUid();
3591        final int resolveFlags =
3592                MATCH_DIRECT_BOOT_AWARE
3593                | MATCH_DIRECT_BOOT_UNAWARE
3594                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3595        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3596        final Intent resolverIntent = new Intent(actionName);
3597        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3598                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3599        final int N = resolvers.size();
3600        if (N == 0) {
3601            if (DEBUG_INSTANT) {
3602                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3603            }
3604            return null;
3605        }
3606
3607        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3608        for (int i = 0; i < N; i++) {
3609            final ResolveInfo info = resolvers.get(i);
3610
3611            if (info.serviceInfo == null) {
3612                continue;
3613            }
3614
3615            final String packageName = info.serviceInfo.packageName;
3616            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3617                if (DEBUG_INSTANT) {
3618                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3619                            + " pkg: " + packageName + ", info:" + info);
3620                }
3621                continue;
3622            }
3623
3624            if (DEBUG_INSTANT) {
3625                Slog.v(TAG, "Ephemeral resolver found;"
3626                        + " pkg: " + packageName + ", info:" + info);
3627            }
3628            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3629        }
3630        if (DEBUG_INSTANT) {
3631            Slog.v(TAG, "Ephemeral resolver NOT found");
3632        }
3633        return null;
3634    }
3635
3636    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3637        String[] orderedActions = Build.IS_ENG
3638                ? new String[]{
3639                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3640                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3641                : new String[]{
3642                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3643
3644        final int resolveFlags =
3645                MATCH_DIRECT_BOOT_AWARE
3646                        | MATCH_DIRECT_BOOT_UNAWARE
3647                        | Intent.FLAG_IGNORE_EPHEMERAL
3648                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3649        final Intent intent = new Intent();
3650        intent.addCategory(Intent.CATEGORY_DEFAULT);
3651        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3652        List<ResolveInfo> matches = null;
3653        for (String action : orderedActions) {
3654            intent.setAction(action);
3655            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3656                    resolveFlags, UserHandle.USER_SYSTEM);
3657            if (matches.isEmpty()) {
3658                if (DEBUG_INSTANT) {
3659                    Slog.d(TAG, "Instant App installer not found with " + action);
3660                }
3661            } else {
3662                break;
3663            }
3664        }
3665        Iterator<ResolveInfo> iter = matches.iterator();
3666        while (iter.hasNext()) {
3667            final ResolveInfo rInfo = iter.next();
3668            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3669            if (ps != null) {
3670                final PermissionsState permissionsState = ps.getPermissionsState();
3671                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3672                        || Build.IS_ENG) {
3673                    continue;
3674                }
3675            }
3676            iter.remove();
3677        }
3678        if (matches.size() == 0) {
3679            return null;
3680        } else if (matches.size() == 1) {
3681            return (ActivityInfo) matches.get(0).getComponentInfo();
3682        } else {
3683            throw new RuntimeException(
3684                    "There must be at most one ephemeral installer; found " + matches);
3685        }
3686    }
3687
3688    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3689            @NonNull ComponentName resolver) {
3690        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3691                .addCategory(Intent.CATEGORY_DEFAULT)
3692                .setPackage(resolver.getPackageName());
3693        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3694        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3695                UserHandle.USER_SYSTEM);
3696        if (matches.isEmpty()) {
3697            return null;
3698        }
3699        return matches.get(0).getComponentInfo().getComponentName();
3700    }
3701
3702    private void primeDomainVerificationsLPw(int userId) {
3703        if (DEBUG_DOMAIN_VERIFICATION) {
3704            Slog.d(TAG, "Priming domain verifications in user " + userId);
3705        }
3706
3707        SystemConfig systemConfig = SystemConfig.getInstance();
3708        ArraySet<String> packages = systemConfig.getLinkedApps();
3709
3710        for (String packageName : packages) {
3711            PackageParser.Package pkg = mPackages.get(packageName);
3712            if (pkg != null) {
3713                if (!pkg.isSystem()) {
3714                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3715                    continue;
3716                }
3717
3718                ArraySet<String> domains = null;
3719                for (PackageParser.Activity a : pkg.activities) {
3720                    for (ActivityIntentInfo filter : a.intents) {
3721                        if (hasValidDomains(filter)) {
3722                            if (domains == null) {
3723                                domains = new ArraySet<String>();
3724                            }
3725                            domains.addAll(filter.getHostsList());
3726                        }
3727                    }
3728                }
3729
3730                if (domains != null && domains.size() > 0) {
3731                    if (DEBUG_DOMAIN_VERIFICATION) {
3732                        Slog.v(TAG, "      + " + packageName);
3733                    }
3734                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3735                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3736                    // and then 'always' in the per-user state actually used for intent resolution.
3737                    final IntentFilterVerificationInfo ivi;
3738                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3739                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3740                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3741                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3742                } else {
3743                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3744                            + "' does not handle web links");
3745                }
3746            } else {
3747                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3748            }
3749        }
3750
3751        scheduleWritePackageRestrictionsLocked(userId);
3752        scheduleWriteSettingsLocked();
3753    }
3754
3755    private void applyFactoryDefaultBrowserLPw(int userId) {
3756        // The default browser app's package name is stored in a string resource,
3757        // with a product-specific overlay used for vendor customization.
3758        String browserPkg = mContext.getResources().getString(
3759                com.android.internal.R.string.default_browser);
3760        if (!TextUtils.isEmpty(browserPkg)) {
3761            // non-empty string => required to be a known package
3762            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3763            if (ps == null) {
3764                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3765                browserPkg = null;
3766            } else {
3767                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3768            }
3769        }
3770
3771        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3772        // default.  If there's more than one, just leave everything alone.
3773        if (browserPkg == null) {
3774            calculateDefaultBrowserLPw(userId);
3775        }
3776    }
3777
3778    private void calculateDefaultBrowserLPw(int userId) {
3779        List<String> allBrowsers = resolveAllBrowserApps(userId);
3780        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3781        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3782    }
3783
3784    private List<String> resolveAllBrowserApps(int userId) {
3785        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3786        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3787                PackageManager.MATCH_ALL, userId);
3788
3789        final int count = list.size();
3790        List<String> result = new ArrayList<String>(count);
3791        for (int i=0; i<count; i++) {
3792            ResolveInfo info = list.get(i);
3793            if (info.activityInfo == null
3794                    || !info.handleAllWebDataURI
3795                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3796                    || result.contains(info.activityInfo.packageName)) {
3797                continue;
3798            }
3799            result.add(info.activityInfo.packageName);
3800        }
3801
3802        return result;
3803    }
3804
3805    private boolean packageIsBrowser(String packageName, int userId) {
3806        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3807                PackageManager.MATCH_ALL, userId);
3808        final int N = list.size();
3809        for (int i = 0; i < N; i++) {
3810            ResolveInfo info = list.get(i);
3811            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3812                return true;
3813            }
3814        }
3815        return false;
3816    }
3817
3818    private void checkDefaultBrowser() {
3819        final int myUserId = UserHandle.myUserId();
3820        final String packageName = getDefaultBrowserPackageName(myUserId);
3821        if (packageName != null) {
3822            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3823            if (info == null) {
3824                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3825                synchronized (mPackages) {
3826                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3827                }
3828            }
3829        }
3830    }
3831
3832    @Override
3833    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3834            throws RemoteException {
3835        try {
3836            return super.onTransact(code, data, reply, flags);
3837        } catch (RuntimeException e) {
3838            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3839                Slog.wtf(TAG, "Package Manager Crash", e);
3840            }
3841            throw e;
3842        }
3843    }
3844
3845    static int[] appendInts(int[] cur, int[] add) {
3846        if (add == null) return cur;
3847        if (cur == null) return add;
3848        final int N = add.length;
3849        for (int i=0; i<N; i++) {
3850            cur = appendInt(cur, add[i]);
3851        }
3852        return cur;
3853    }
3854
3855    /**
3856     * Returns whether or not a full application can see an instant application.
3857     * <p>
3858     * Currently, there are three cases in which this can occur:
3859     * <ol>
3860     * <li>The calling application is a "special" process. Special processes
3861     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3862     * <li>The calling application has the permission
3863     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3864     * <li>The calling application is the default launcher on the
3865     *     system partition.</li>
3866     * </ol>
3867     */
3868    private boolean canViewInstantApps(int callingUid, int userId) {
3869        if (callingUid < Process.FIRST_APPLICATION_UID) {
3870            return true;
3871        }
3872        if (mContext.checkCallingOrSelfPermission(
3873                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3874            return true;
3875        }
3876        if (mContext.checkCallingOrSelfPermission(
3877                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3878            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3879            if (homeComponent != null
3880                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3881                return true;
3882            }
3883        }
3884        return false;
3885    }
3886
3887    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3888        if (!sUserManager.exists(userId)) return null;
3889        if (ps == null) {
3890            return null;
3891        }
3892        final int callingUid = Binder.getCallingUid();
3893        // Filter out ephemeral app metadata:
3894        //   * The system/shell/root can see metadata for any app
3895        //   * An installed app can see metadata for 1) other installed apps
3896        //     and 2) ephemeral apps that have explicitly interacted with it
3897        //   * Ephemeral apps can only see their own data and exposed installed apps
3898        //   * Holding a signature permission allows seeing instant apps
3899        if (filterAppAccessLPr(ps, callingUid, userId)) {
3900            return null;
3901        }
3902
3903        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3904                && ps.isSystem()) {
3905            flags |= MATCH_ANY_USER;
3906        }
3907
3908        final PackageUserState state = ps.readUserState(userId);
3909        PackageParser.Package p = ps.pkg;
3910        if (p != null) {
3911            final PermissionsState permissionsState = ps.getPermissionsState();
3912
3913            // Compute GIDs only if requested
3914            final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3915                    ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3916            // Compute granted permissions only if package has requested permissions
3917            final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3918                    ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3919
3920            PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3921                    ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3922
3923            if (packageInfo == null) {
3924                return null;
3925            }
3926
3927            packageInfo.packageName = packageInfo.applicationInfo.packageName =
3928                    resolveExternalPackageNameLPr(p);
3929
3930            return packageInfo;
3931        } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
3932            PackageInfo pi = new PackageInfo();
3933            pi.packageName = ps.name;
3934            pi.setLongVersionCode(ps.versionCode);
3935            pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
3936            pi.firstInstallTime = ps.firstInstallTime;
3937            pi.lastUpdateTime = ps.lastUpdateTime;
3938
3939            ApplicationInfo ai = new ApplicationInfo();
3940            ai.packageName = ps.name;
3941            ai.uid = UserHandle.getUid(userId, ps.appId);
3942            ai.primaryCpuAbi = ps.primaryCpuAbiString;
3943            ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
3944            ai.versionCode = ps.versionCode;
3945            ai.flags = ps.pkgFlags;
3946            ai.privateFlags = ps.pkgPrivateFlags;
3947            pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
3948
3949            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
3950                    + ps.name + "]. Provides a minimum info.");
3951            return pi;
3952        } else {
3953            return null;
3954        }
3955    }
3956
3957    @Override
3958    public void checkPackageStartable(String packageName, int userId) {
3959        final int callingUid = Binder.getCallingUid();
3960        if (getInstantAppPackageName(callingUid) != null) {
3961            throw new SecurityException("Instant applications don't have access to this method");
3962        }
3963        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3964        synchronized (mPackages) {
3965            final PackageSetting ps = mSettings.mPackages.get(packageName);
3966            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3967                throw new SecurityException("Package " + packageName + " was not found!");
3968            }
3969
3970            if (!ps.getInstalled(userId)) {
3971                throw new SecurityException(
3972                        "Package " + packageName + " was not installed for user " + userId + "!");
3973            }
3974
3975            if (mSafeMode && !ps.isSystem()) {
3976                throw new SecurityException("Package " + packageName + " not a system app!");
3977            }
3978
3979            if (mFrozenPackages.contains(packageName)) {
3980                throw new SecurityException("Package " + packageName + " is currently frozen!");
3981            }
3982
3983            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3984                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3985            }
3986        }
3987    }
3988
3989    @Override
3990    public boolean isPackageAvailable(String packageName, int userId) {
3991        if (!sUserManager.exists(userId)) return false;
3992        final int callingUid = Binder.getCallingUid();
3993        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3994                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3995        synchronized (mPackages) {
3996            PackageParser.Package p = mPackages.get(packageName);
3997            if (p != null) {
3998                final PackageSetting ps = (PackageSetting) p.mExtras;
3999                if (filterAppAccessLPr(ps, callingUid, userId)) {
4000                    return false;
4001                }
4002                if (ps != null) {
4003                    final PackageUserState state = ps.readUserState(userId);
4004                    if (state != null) {
4005                        return PackageParser.isAvailable(state);
4006                    }
4007                }
4008            }
4009        }
4010        return false;
4011    }
4012
4013    @Override
4014    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
4015        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
4016                flags, Binder.getCallingUid(), userId);
4017    }
4018
4019    @Override
4020    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
4021            int flags, int userId) {
4022        return getPackageInfoInternal(versionedPackage.getPackageName(),
4023                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
4024    }
4025
4026    /**
4027     * Important: The provided filterCallingUid is used exclusively to filter out packages
4028     * that can be seen based on user state. It's typically the original caller uid prior
4029     * to clearing. Because it can only be provided by trusted code, it's value can be
4030     * trusted and will be used as-is; unlike userId which will be validated by this method.
4031     */
4032    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
4033            int flags, int filterCallingUid, int userId) {
4034        if (!sUserManager.exists(userId)) return null;
4035        flags = updateFlagsForPackage(flags, userId, packageName);
4036        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4037                false /* requireFullPermission */, false /* checkShell */, "get package info");
4038
4039        // reader
4040        synchronized (mPackages) {
4041            // Normalize package name to handle renamed packages and static libs
4042            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
4043
4044            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
4045            if (matchFactoryOnly) {
4046                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
4047                if (ps != null) {
4048                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4049                        return null;
4050                    }
4051                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4052                        return null;
4053                    }
4054                    return generatePackageInfo(ps, flags, userId);
4055                }
4056            }
4057
4058            PackageParser.Package p = mPackages.get(packageName);
4059            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
4060                return null;
4061            }
4062            if (DEBUG_PACKAGE_INFO)
4063                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4064            if (p != null) {
4065                final PackageSetting ps = (PackageSetting) p.mExtras;
4066                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4067                    return null;
4068                }
4069                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4070                    return null;
4071                }
4072                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4073            }
4074            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4075                final PackageSetting ps = mSettings.mPackages.get(packageName);
4076                if (ps == null) return null;
4077                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4078                    return null;
4079                }
4080                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4081                    return null;
4082                }
4083                return generatePackageInfo(ps, flags, userId);
4084            }
4085        }
4086        return null;
4087    }
4088
4089    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4090        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4091            return true;
4092        }
4093        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4094            return true;
4095        }
4096        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4097            return true;
4098        }
4099        return false;
4100    }
4101
4102    private boolean isComponentVisibleToInstantApp(
4103            @Nullable ComponentName component, @ComponentType int type) {
4104        if (type == TYPE_ACTIVITY) {
4105            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4106            if (activity == null) {
4107                return false;
4108            }
4109            final boolean visibleToInstantApp =
4110                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4111            final boolean explicitlyVisibleToInstantApp =
4112                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4113            return visibleToInstantApp && explicitlyVisibleToInstantApp;
4114        } else if (type == TYPE_RECEIVER) {
4115            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4116            if (activity == null) {
4117                return false;
4118            }
4119            final boolean visibleToInstantApp =
4120                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4121            final boolean explicitlyVisibleToInstantApp =
4122                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4123            return visibleToInstantApp && !explicitlyVisibleToInstantApp;
4124        } else if (type == TYPE_SERVICE) {
4125            final PackageParser.Service service = mServices.mServices.get(component);
4126            return service != null
4127                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4128                    : false;
4129        } else if (type == TYPE_PROVIDER) {
4130            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4131            return provider != null
4132                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4133                    : false;
4134        } else if (type == TYPE_UNKNOWN) {
4135            return isComponentVisibleToInstantApp(component);
4136        }
4137        return false;
4138    }
4139
4140    /**
4141     * Returns whether or not access to the application should be filtered.
4142     * <p>
4143     * Access may be limited based upon whether the calling or target applications
4144     * are instant applications.
4145     *
4146     * @see #canAccessInstantApps(int)
4147     */
4148    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4149            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4150        // if we're in an isolated process, get the real calling UID
4151        if (Process.isIsolated(callingUid)) {
4152            callingUid = mIsolatedOwners.get(callingUid);
4153        }
4154        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4155        final boolean callerIsInstantApp = instantAppPkgName != null;
4156        if (ps == null) {
4157            if (callerIsInstantApp) {
4158                // pretend the application exists, but, needs to be filtered
4159                return true;
4160            }
4161            return false;
4162        }
4163        // if the target and caller are the same application, don't filter
4164        if (isCallerSameApp(ps.name, callingUid)) {
4165            return false;
4166        }
4167        if (callerIsInstantApp) {
4168            // both caller and target are both instant, but, different applications, filter
4169            if (ps.getInstantApp(userId)) {
4170                return true;
4171            }
4172            // request for a specific component; if it hasn't been explicitly exposed through
4173            // property or instrumentation target, filter
4174            if (component != null) {
4175                final PackageParser.Instrumentation instrumentation =
4176                        mInstrumentation.get(component);
4177                if (instrumentation != null
4178                        && isCallerSameApp(instrumentation.info.targetPackage, callingUid)) {
4179                    return false;
4180                }
4181                return !isComponentVisibleToInstantApp(component, componentType);
4182            }
4183            // request for application; if no components have been explicitly exposed, filter
4184            return !ps.pkg.visibleToInstantApps;
4185        }
4186        if (ps.getInstantApp(userId)) {
4187            // caller can see all components of all instant applications, don't filter
4188            if (canViewInstantApps(callingUid, userId)) {
4189                return false;
4190            }
4191            // request for a specific instant application component, filter
4192            if (component != null) {
4193                return true;
4194            }
4195            // request for an instant application; if the caller hasn't been granted access, filter
4196            return !mInstantAppRegistry.isInstantAccessGranted(
4197                    userId, UserHandle.getAppId(callingUid), ps.appId);
4198        }
4199        return false;
4200    }
4201
4202    /**
4203     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4204     */
4205    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4206        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4207    }
4208
4209    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4210            int flags) {
4211        // Callers can access only the libs they depend on, otherwise they need to explicitly
4212        // ask for the shared libraries given the caller is allowed to access all static libs.
4213        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4214            // System/shell/root get to see all static libs
4215            final int appId = UserHandle.getAppId(uid);
4216            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4217                    || appId == Process.ROOT_UID) {
4218                return false;
4219            }
4220        }
4221
4222        // No package means no static lib as it is always on internal storage
4223        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4224            return false;
4225        }
4226
4227        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4228                ps.pkg.staticSharedLibVersion);
4229        if (libEntry == null) {
4230            return false;
4231        }
4232
4233        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4234        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4235        if (uidPackageNames == null) {
4236            return true;
4237        }
4238
4239        for (String uidPackageName : uidPackageNames) {
4240            if (ps.name.equals(uidPackageName)) {
4241                return false;
4242            }
4243            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4244            if (uidPs != null) {
4245                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4246                        libEntry.info.getName());
4247                if (index < 0) {
4248                    continue;
4249                }
4250                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4251                    return false;
4252                }
4253            }
4254        }
4255        return true;
4256    }
4257
4258    @Override
4259    public String[] currentToCanonicalPackageNames(String[] names) {
4260        final int callingUid = Binder.getCallingUid();
4261        if (getInstantAppPackageName(callingUid) != null) {
4262            return names;
4263        }
4264        final String[] out = new String[names.length];
4265        // reader
4266        synchronized (mPackages) {
4267            final int callingUserId = UserHandle.getUserId(callingUid);
4268            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4269            for (int i=names.length-1; i>=0; i--) {
4270                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4271                boolean translateName = false;
4272                if (ps != null && ps.realName != null) {
4273                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4274                    translateName = !targetIsInstantApp
4275                            || canViewInstantApps
4276                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4277                                    UserHandle.getAppId(callingUid), ps.appId);
4278                }
4279                out[i] = translateName ? ps.realName : names[i];
4280            }
4281        }
4282        return out;
4283    }
4284
4285    @Override
4286    public String[] canonicalToCurrentPackageNames(String[] names) {
4287        final int callingUid = Binder.getCallingUid();
4288        if (getInstantAppPackageName(callingUid) != null) {
4289            return names;
4290        }
4291        final String[] out = new String[names.length];
4292        // reader
4293        synchronized (mPackages) {
4294            final int callingUserId = UserHandle.getUserId(callingUid);
4295            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4296            for (int i=names.length-1; i>=0; i--) {
4297                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4298                boolean translateName = false;
4299                if (cur != null) {
4300                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4301                    final boolean targetIsInstantApp =
4302                            ps != null && ps.getInstantApp(callingUserId);
4303                    translateName = !targetIsInstantApp
4304                            || canViewInstantApps
4305                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4306                                    UserHandle.getAppId(callingUid), ps.appId);
4307                }
4308                out[i] = translateName ? cur : names[i];
4309            }
4310        }
4311        return out;
4312    }
4313
4314    @Override
4315    public int getPackageUid(String packageName, int flags, int userId) {
4316        if (!sUserManager.exists(userId)) return -1;
4317        final int callingUid = Binder.getCallingUid();
4318        flags = updateFlagsForPackage(flags, userId, packageName);
4319        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4320                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4321
4322        // reader
4323        synchronized (mPackages) {
4324            final PackageParser.Package p = mPackages.get(packageName);
4325            if (p != null && p.isMatch(flags)) {
4326                PackageSetting ps = (PackageSetting) p.mExtras;
4327                if (filterAppAccessLPr(ps, callingUid, userId)) {
4328                    return -1;
4329                }
4330                return UserHandle.getUid(userId, p.applicationInfo.uid);
4331            }
4332            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4333                final PackageSetting ps = mSettings.mPackages.get(packageName);
4334                if (ps != null && ps.isMatch(flags)
4335                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4336                    return UserHandle.getUid(userId, ps.appId);
4337                }
4338            }
4339        }
4340
4341        return -1;
4342    }
4343
4344    @Override
4345    public int[] getPackageGids(String packageName, int flags, int userId) {
4346        if (!sUserManager.exists(userId)) return null;
4347        final int callingUid = Binder.getCallingUid();
4348        flags = updateFlagsForPackage(flags, userId, packageName);
4349        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4350                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4351
4352        // reader
4353        synchronized (mPackages) {
4354            final PackageParser.Package p = mPackages.get(packageName);
4355            if (p != null && p.isMatch(flags)) {
4356                PackageSetting ps = (PackageSetting) p.mExtras;
4357                if (filterAppAccessLPr(ps, callingUid, userId)) {
4358                    return null;
4359                }
4360                // TODO: Shouldn't this be checking for package installed state for userId and
4361                // return null?
4362                return ps.getPermissionsState().computeGids(userId);
4363            }
4364            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4365                final PackageSetting ps = mSettings.mPackages.get(packageName);
4366                if (ps != null && ps.isMatch(flags)
4367                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4368                    return ps.getPermissionsState().computeGids(userId);
4369                }
4370            }
4371        }
4372
4373        return null;
4374    }
4375
4376    @Override
4377    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4378        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4379    }
4380
4381    @Override
4382    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4383            int flags) {
4384        final List<PermissionInfo> permissionList =
4385                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4386        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4387    }
4388
4389    @Override
4390    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4391        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4392    }
4393
4394    @Override
4395    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4396        final List<PermissionGroupInfo> permissionList =
4397                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4398        return (permissionList == null)
4399                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4400    }
4401
4402    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4403            int filterCallingUid, int userId) {
4404        if (!sUserManager.exists(userId)) return null;
4405        PackageSetting ps = mSettings.mPackages.get(packageName);
4406        if (ps != null) {
4407            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4408                return null;
4409            }
4410            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4411                return null;
4412            }
4413            if (ps.pkg == null) {
4414                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4415                if (pInfo != null) {
4416                    return pInfo.applicationInfo;
4417                }
4418                return null;
4419            }
4420            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4421                    ps.readUserState(userId), userId);
4422            if (ai != null) {
4423                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4424            }
4425            return ai;
4426        }
4427        return null;
4428    }
4429
4430    @Override
4431    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4432        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4433    }
4434
4435    /**
4436     * Important: The provided filterCallingUid is used exclusively to filter out applications
4437     * that can be seen based on user state. It's typically the original caller uid prior
4438     * to clearing. Because it can only be provided by trusted code, it's value can be
4439     * trusted and will be used as-is; unlike userId which will be validated by this method.
4440     */
4441    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4442            int filterCallingUid, int userId) {
4443        if (!sUserManager.exists(userId)) return null;
4444        flags = updateFlagsForApplication(flags, userId, packageName);
4445        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4446                false /* requireFullPermission */, false /* checkShell */, "get application info");
4447
4448        // writer
4449        synchronized (mPackages) {
4450            // Normalize package name to handle renamed packages and static libs
4451            packageName = resolveInternalPackageNameLPr(packageName,
4452                    PackageManager.VERSION_CODE_HIGHEST);
4453
4454            PackageParser.Package p = mPackages.get(packageName);
4455            if (DEBUG_PACKAGE_INFO) Log.v(
4456                    TAG, "getApplicationInfo " + packageName
4457                    + ": " + p);
4458            if (p != null) {
4459                PackageSetting ps = mSettings.mPackages.get(packageName);
4460                if (ps == null) return null;
4461                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4462                    return null;
4463                }
4464                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4465                    return null;
4466                }
4467                // Note: isEnabledLP() does not apply here - always return info
4468                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4469                        p, flags, ps.readUserState(userId), userId);
4470                if (ai != null) {
4471                    ai.packageName = resolveExternalPackageNameLPr(p);
4472                }
4473                return ai;
4474            }
4475            if ("android".equals(packageName)||"system".equals(packageName)) {
4476                return mAndroidApplication;
4477            }
4478            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4479                // Already generates the external package name
4480                return generateApplicationInfoFromSettingsLPw(packageName,
4481                        flags, filterCallingUid, userId);
4482            }
4483        }
4484        return null;
4485    }
4486
4487    private String normalizePackageNameLPr(String packageName) {
4488        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4489        return normalizedPackageName != null ? normalizedPackageName : packageName;
4490    }
4491
4492    @Override
4493    public void deletePreloadsFileCache() {
4494        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4495            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4496        }
4497        File dir = Environment.getDataPreloadsFileCacheDirectory();
4498        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4499        FileUtils.deleteContents(dir);
4500    }
4501
4502    @Override
4503    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4504            final int storageFlags, final IPackageDataObserver observer) {
4505        mContext.enforceCallingOrSelfPermission(
4506                android.Manifest.permission.CLEAR_APP_CACHE, null);
4507        mHandler.post(() -> {
4508            boolean success = false;
4509            try {
4510                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4511                success = true;
4512            } catch (IOException e) {
4513                Slog.w(TAG, e);
4514            }
4515            if (observer != null) {
4516                try {
4517                    observer.onRemoveCompleted(null, success);
4518                } catch (RemoteException e) {
4519                    Slog.w(TAG, e);
4520                }
4521            }
4522        });
4523    }
4524
4525    @Override
4526    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4527            final int storageFlags, final IntentSender pi) {
4528        mContext.enforceCallingOrSelfPermission(
4529                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4530        mHandler.post(() -> {
4531            boolean success = false;
4532            try {
4533                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4534                success = true;
4535            } catch (IOException e) {
4536                Slog.w(TAG, e);
4537            }
4538            if (pi != null) {
4539                try {
4540                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4541                } catch (SendIntentException e) {
4542                    Slog.w(TAG, e);
4543                }
4544            }
4545        });
4546    }
4547
4548    /**
4549     * Blocking call to clear various types of cached data across the system
4550     * until the requested bytes are available.
4551     */
4552    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4553        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4554        final File file = storage.findPathForUuid(volumeUuid);
4555        if (file.getUsableSpace() >= bytes) return;
4556
4557        if (ENABLE_FREE_CACHE_V2) {
4558            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4559                    volumeUuid);
4560            final boolean aggressive = (storageFlags
4561                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4562            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4563
4564            // 1. Pre-flight to determine if we have any chance to succeed
4565            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4566            if (internalVolume && (aggressive || SystemProperties
4567                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4568                deletePreloadsFileCache();
4569                if (file.getUsableSpace() >= bytes) return;
4570            }
4571
4572            // 3. Consider parsed APK data (aggressive only)
4573            if (internalVolume && aggressive) {
4574                FileUtils.deleteContents(mCacheDir);
4575                if (file.getUsableSpace() >= bytes) return;
4576            }
4577
4578            // 4. Consider cached app data (above quotas)
4579            try {
4580                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4581                        Installer.FLAG_FREE_CACHE_V2);
4582            } catch (InstallerException ignored) {
4583            }
4584            if (file.getUsableSpace() >= bytes) return;
4585
4586            // 5. Consider shared libraries with refcount=0 and age>min cache period
4587            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4588                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4589                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4590                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4591                return;
4592            }
4593
4594            // 6. Consider dexopt output (aggressive only)
4595            // TODO: Implement
4596
4597            // 7. Consider installed instant apps unused longer than min cache period
4598            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4599                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4600                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4601                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4602                return;
4603            }
4604
4605            // 8. Consider cached app data (below quotas)
4606            try {
4607                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4608                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4609            } catch (InstallerException ignored) {
4610            }
4611            if (file.getUsableSpace() >= bytes) return;
4612
4613            // 9. Consider DropBox entries
4614            // TODO: Implement
4615
4616            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4617            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4618                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4619                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4620                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4621                return;
4622            }
4623        } else {
4624            try {
4625                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4626            } catch (InstallerException ignored) {
4627            }
4628            if (file.getUsableSpace() >= bytes) return;
4629        }
4630
4631        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4632    }
4633
4634    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4635            throws IOException {
4636        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4637        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4638
4639        List<VersionedPackage> packagesToDelete = null;
4640        final long now = System.currentTimeMillis();
4641
4642        synchronized (mPackages) {
4643            final int[] allUsers = sUserManager.getUserIds();
4644            final int libCount = mSharedLibraries.size();
4645            for (int i = 0; i < libCount; i++) {
4646                final LongSparseArray<SharedLibraryEntry> versionedLib
4647                        = mSharedLibraries.valueAt(i);
4648                if (versionedLib == null) {
4649                    continue;
4650                }
4651                final int versionCount = versionedLib.size();
4652                for (int j = 0; j < versionCount; j++) {
4653                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4654                    // Skip packages that are not static shared libs.
4655                    if (!libInfo.isStatic()) {
4656                        break;
4657                    }
4658                    // Important: We skip static shared libs used for some user since
4659                    // in such a case we need to keep the APK on the device. The check for
4660                    // a lib being used for any user is performed by the uninstall call.
4661                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4662                    // Resolve the package name - we use synthetic package names internally
4663                    final String internalPackageName = resolveInternalPackageNameLPr(
4664                            declaringPackage.getPackageName(),
4665                            declaringPackage.getLongVersionCode());
4666                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4667                    // Skip unused static shared libs cached less than the min period
4668                    // to prevent pruning a lib needed by a subsequently installed package.
4669                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4670                        continue;
4671                    }
4672                    if (packagesToDelete == null) {
4673                        packagesToDelete = new ArrayList<>();
4674                    }
4675                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4676                            declaringPackage.getLongVersionCode()));
4677                }
4678            }
4679        }
4680
4681        if (packagesToDelete != null) {
4682            final int packageCount = packagesToDelete.size();
4683            for (int i = 0; i < packageCount; i++) {
4684                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4685                // Delete the package synchronously (will fail of the lib used for any user).
4686                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4687                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4688                                == PackageManager.DELETE_SUCCEEDED) {
4689                    if (volume.getUsableSpace() >= neededSpace) {
4690                        return true;
4691                    }
4692                }
4693            }
4694        }
4695
4696        return false;
4697    }
4698
4699    /**
4700     * Update given flags based on encryption status of current user.
4701     */
4702    private int updateFlags(int flags, int userId) {
4703        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4704                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4705            // Caller expressed an explicit opinion about what encryption
4706            // aware/unaware components they want to see, so fall through and
4707            // give them what they want
4708        } else {
4709            // Caller expressed no opinion, so match based on user state
4710            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4711                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4712            } else {
4713                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4714            }
4715        }
4716        return flags;
4717    }
4718
4719    private UserManagerInternal getUserManagerInternal() {
4720        if (mUserManagerInternal == null) {
4721            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4722        }
4723        return mUserManagerInternal;
4724    }
4725
4726    private ActivityManagerInternal getActivityManagerInternal() {
4727        if (mActivityManagerInternal == null) {
4728            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4729        }
4730        return mActivityManagerInternal;
4731    }
4732
4733
4734    private DeviceIdleController.LocalService getDeviceIdleController() {
4735        if (mDeviceIdleController == null) {
4736            mDeviceIdleController =
4737                    LocalServices.getService(DeviceIdleController.LocalService.class);
4738        }
4739        return mDeviceIdleController;
4740    }
4741
4742    /**
4743     * Update given flags when being used to request {@link PackageInfo}.
4744     */
4745    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4746        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4747        boolean triaged = true;
4748        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4749                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4750            // Caller is asking for component details, so they'd better be
4751            // asking for specific encryption matching behavior, or be triaged
4752            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4753                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4754                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4755                triaged = false;
4756            }
4757        }
4758        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4759                | PackageManager.MATCH_SYSTEM_ONLY
4760                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4761            triaged = false;
4762        }
4763        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4764            mPermissionManager.enforceCrossUserPermission(
4765                    Binder.getCallingUid(), userId, false, false,
4766                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4767                    + Debug.getCallers(5));
4768        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4769                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4770            // If the caller wants all packages and has a restricted profile associated with it,
4771            // then match all users. This is to make sure that launchers that need to access work
4772            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4773            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4774            flags |= PackageManager.MATCH_ANY_USER;
4775        }
4776        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4777            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4778                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4779        }
4780        return updateFlags(flags, userId);
4781    }
4782
4783    /**
4784     * Update given flags when being used to request {@link ApplicationInfo}.
4785     */
4786    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4787        return updateFlagsForPackage(flags, userId, cookie);
4788    }
4789
4790    /**
4791     * Update given flags when being used to request {@link ComponentInfo}.
4792     */
4793    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4794        if (cookie instanceof Intent) {
4795            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4796                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4797            }
4798        }
4799
4800        boolean triaged = true;
4801        // Caller is asking for component details, so they'd better be
4802        // asking for specific encryption matching behavior, or be triaged
4803        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4804                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4805                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4806            triaged = false;
4807        }
4808        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4809            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4810                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4811        }
4812
4813        return updateFlags(flags, userId);
4814    }
4815
4816    /**
4817     * Update given intent when being used to request {@link ResolveInfo}.
4818     */
4819    private Intent updateIntentForResolve(Intent intent) {
4820        if (intent.getSelector() != null) {
4821            intent = intent.getSelector();
4822        }
4823        if (DEBUG_PREFERRED) {
4824            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4825        }
4826        return intent;
4827    }
4828
4829    /**
4830     * Update given flags when being used to request {@link ResolveInfo}.
4831     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4832     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4833     * flag set. However, this flag is only honoured in three circumstances:
4834     * <ul>
4835     * <li>when called from a system process</li>
4836     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4837     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4838     * action and a {@code android.intent.category.BROWSABLE} category</li>
4839     * </ul>
4840     */
4841    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4842        return updateFlagsForResolve(flags, userId, intent, callingUid,
4843                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4844    }
4845    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4846            boolean wantInstantApps) {
4847        return updateFlagsForResolve(flags, userId, intent, callingUid,
4848                wantInstantApps, false /*onlyExposedExplicitly*/);
4849    }
4850    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4851            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4852        // Safe mode means we shouldn't match any third-party components
4853        if (mSafeMode) {
4854            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4855        }
4856        if (getInstantAppPackageName(callingUid) != null) {
4857            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4858            if (onlyExposedExplicitly) {
4859                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4860            }
4861            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4862            flags |= PackageManager.MATCH_INSTANT;
4863        } else {
4864            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4865            final boolean allowMatchInstant = wantInstantApps
4866                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4867            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4868                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4869            if (!allowMatchInstant) {
4870                flags &= ~PackageManager.MATCH_INSTANT;
4871            }
4872        }
4873        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4874    }
4875
4876    @Override
4877    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4878        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4879    }
4880
4881    /**
4882     * Important: The provided filterCallingUid is used exclusively to filter out activities
4883     * that can be seen based on user state. It's typically the original caller uid prior
4884     * to clearing. Because it can only be provided by trusted code, it's value can be
4885     * trusted and will be used as-is; unlike userId which will be validated by this method.
4886     */
4887    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4888            int filterCallingUid, int userId) {
4889        if (!sUserManager.exists(userId)) return null;
4890        flags = updateFlagsForComponent(flags, userId, component);
4891
4892        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4893            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4894                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4895        }
4896
4897        synchronized (mPackages) {
4898            PackageParser.Activity a = mActivities.mActivities.get(component);
4899
4900            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4901            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4902                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4903                if (ps == null) return null;
4904                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4905                    return null;
4906                }
4907                return PackageParser.generateActivityInfo(
4908                        a, flags, ps.readUserState(userId), userId);
4909            }
4910            if (mResolveComponentName.equals(component)) {
4911                return PackageParser.generateActivityInfo(
4912                        mResolveActivity, flags, new PackageUserState(), userId);
4913            }
4914        }
4915        return null;
4916    }
4917
4918    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4919        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4920            return false;
4921        }
4922        final long token = Binder.clearCallingIdentity();
4923        try {
4924            final int callingUserId = UserHandle.getUserId(callingUid);
4925            if (ActivityManager.getCurrentUser() != callingUserId) {
4926                return false;
4927            }
4928            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4929        } finally {
4930            Binder.restoreCallingIdentity(token);
4931        }
4932    }
4933
4934    @Override
4935    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4936            String resolvedType) {
4937        synchronized (mPackages) {
4938            if (component.equals(mResolveComponentName)) {
4939                // The resolver supports EVERYTHING!
4940                return true;
4941            }
4942            final int callingUid = Binder.getCallingUid();
4943            final int callingUserId = UserHandle.getUserId(callingUid);
4944            PackageParser.Activity a = mActivities.mActivities.get(component);
4945            if (a == null) {
4946                return false;
4947            }
4948            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4949            if (ps == null) {
4950                return false;
4951            }
4952            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4953                return false;
4954            }
4955            for (int i=0; i<a.intents.size(); i++) {
4956                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4957                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4958                    return true;
4959                }
4960            }
4961            return false;
4962        }
4963    }
4964
4965    @Override
4966    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4967        if (!sUserManager.exists(userId)) return null;
4968        final int callingUid = Binder.getCallingUid();
4969        flags = updateFlagsForComponent(flags, userId, component);
4970        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4971                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4972        synchronized (mPackages) {
4973            PackageParser.Activity a = mReceivers.mActivities.get(component);
4974            if (DEBUG_PACKAGE_INFO) Log.v(
4975                TAG, "getReceiverInfo " + component + ": " + a);
4976            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4977                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4978                if (ps == null) return null;
4979                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4980                    return null;
4981                }
4982                return PackageParser.generateActivityInfo(
4983                        a, flags, ps.readUserState(userId), userId);
4984            }
4985        }
4986        return null;
4987    }
4988
4989    @Override
4990    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4991            int flags, int userId) {
4992        if (!sUserManager.exists(userId)) return null;
4993        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4994        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4995            return null;
4996        }
4997
4998        flags = updateFlagsForPackage(flags, userId, null);
4999
5000        final boolean canSeeStaticLibraries =
5001                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
5002                        == PERMISSION_GRANTED
5003                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
5004                        == PERMISSION_GRANTED
5005                || canRequestPackageInstallsInternal(packageName,
5006                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
5007                        false  /* throwIfPermNotDeclared*/)
5008                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
5009                        == PERMISSION_GRANTED;
5010
5011        synchronized (mPackages) {
5012            List<SharedLibraryInfo> result = null;
5013
5014            final int libCount = mSharedLibraries.size();
5015            for (int i = 0; i < libCount; i++) {
5016                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5017                if (versionedLib == null) {
5018                    continue;
5019                }
5020
5021                final int versionCount = versionedLib.size();
5022                for (int j = 0; j < versionCount; j++) {
5023                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5024                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5025                        break;
5026                    }
5027                    final long identity = Binder.clearCallingIdentity();
5028                    try {
5029                        PackageInfo packageInfo = getPackageInfoVersioned(
5030                                libInfo.getDeclaringPackage(), flags
5031                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5032                        if (packageInfo == null) {
5033                            continue;
5034                        }
5035                    } finally {
5036                        Binder.restoreCallingIdentity(identity);
5037                    }
5038
5039                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5040                            libInfo.getLongVersion(), libInfo.getType(),
5041                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5042                            flags, userId));
5043
5044                    if (result == null) {
5045                        result = new ArrayList<>();
5046                    }
5047                    result.add(resLibInfo);
5048                }
5049            }
5050
5051            return result != null ? new ParceledListSlice<>(result) : null;
5052        }
5053    }
5054
5055    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5056            SharedLibraryInfo libInfo, int flags, int userId) {
5057        List<VersionedPackage> versionedPackages = null;
5058        final int packageCount = mSettings.mPackages.size();
5059        for (int i = 0; i < packageCount; i++) {
5060            PackageSetting ps = mSettings.mPackages.valueAt(i);
5061
5062            if (ps == null) {
5063                continue;
5064            }
5065
5066            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5067                continue;
5068            }
5069
5070            final String libName = libInfo.getName();
5071            if (libInfo.isStatic()) {
5072                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5073                if (libIdx < 0) {
5074                    continue;
5075                }
5076                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
5077                    continue;
5078                }
5079                if (versionedPackages == null) {
5080                    versionedPackages = new ArrayList<>();
5081                }
5082                // If the dependent is a static shared lib, use the public package name
5083                String dependentPackageName = ps.name;
5084                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5085                    dependentPackageName = ps.pkg.manifestPackageName;
5086                }
5087                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5088            } else if (ps.pkg != null) {
5089                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5090                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5091                    if (versionedPackages == null) {
5092                        versionedPackages = new ArrayList<>();
5093                    }
5094                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5095                }
5096            }
5097        }
5098
5099        return versionedPackages;
5100    }
5101
5102    @Override
5103    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5104        if (!sUserManager.exists(userId)) return null;
5105        final int callingUid = Binder.getCallingUid();
5106        flags = updateFlagsForComponent(flags, userId, component);
5107        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5108                false /* requireFullPermission */, false /* checkShell */, "get service info");
5109        synchronized (mPackages) {
5110            PackageParser.Service s = mServices.mServices.get(component);
5111            if (DEBUG_PACKAGE_INFO) Log.v(
5112                TAG, "getServiceInfo " + component + ": " + s);
5113            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5114                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5115                if (ps == null) return null;
5116                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5117                    return null;
5118                }
5119                return PackageParser.generateServiceInfo(
5120                        s, flags, ps.readUserState(userId), userId);
5121            }
5122        }
5123        return null;
5124    }
5125
5126    @Override
5127    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5128        if (!sUserManager.exists(userId)) return null;
5129        final int callingUid = Binder.getCallingUid();
5130        flags = updateFlagsForComponent(flags, userId, component);
5131        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5132                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5133        synchronized (mPackages) {
5134            PackageParser.Provider p = mProviders.mProviders.get(component);
5135            if (DEBUG_PACKAGE_INFO) Log.v(
5136                TAG, "getProviderInfo " + component + ": " + p);
5137            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5138                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5139                if (ps == null) return null;
5140                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5141                    return null;
5142                }
5143                return PackageParser.generateProviderInfo(
5144                        p, flags, ps.readUserState(userId), userId);
5145            }
5146        }
5147        return null;
5148    }
5149
5150    @Override
5151    public String[] getSystemSharedLibraryNames() {
5152        // allow instant applications
5153        synchronized (mPackages) {
5154            Set<String> libs = null;
5155            final int libCount = mSharedLibraries.size();
5156            for (int i = 0; i < libCount; i++) {
5157                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5158                if (versionedLib == null) {
5159                    continue;
5160                }
5161                final int versionCount = versionedLib.size();
5162                for (int j = 0; j < versionCount; j++) {
5163                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5164                    if (!libEntry.info.isStatic()) {
5165                        if (libs == null) {
5166                            libs = new ArraySet<>();
5167                        }
5168                        libs.add(libEntry.info.getName());
5169                        break;
5170                    }
5171                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5172                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5173                            UserHandle.getUserId(Binder.getCallingUid()),
5174                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5175                        if (libs == null) {
5176                            libs = new ArraySet<>();
5177                        }
5178                        libs.add(libEntry.info.getName());
5179                        break;
5180                    }
5181                }
5182            }
5183
5184            if (libs != null) {
5185                String[] libsArray = new String[libs.size()];
5186                libs.toArray(libsArray);
5187                return libsArray;
5188            }
5189
5190            return null;
5191        }
5192    }
5193
5194    @Override
5195    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5196        // allow instant applications
5197        synchronized (mPackages) {
5198            return mServicesSystemSharedLibraryPackageName;
5199        }
5200    }
5201
5202    @Override
5203    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5204        // allow instant applications
5205        synchronized (mPackages) {
5206            return mSharedSystemSharedLibraryPackageName;
5207        }
5208    }
5209
5210    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5211        for (int i = userList.length - 1; i >= 0; --i) {
5212            final int userId = userList[i];
5213            // don't add instant app to the list of updates
5214            if (pkgSetting.getInstantApp(userId)) {
5215                continue;
5216            }
5217            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5218            if (changedPackages == null) {
5219                changedPackages = new SparseArray<>();
5220                mChangedPackages.put(userId, changedPackages);
5221            }
5222            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5223            if (sequenceNumbers == null) {
5224                sequenceNumbers = new HashMap<>();
5225                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5226            }
5227            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5228            if (sequenceNumber != null) {
5229                changedPackages.remove(sequenceNumber);
5230            }
5231            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5232            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5233        }
5234        mChangedPackagesSequenceNumber++;
5235    }
5236
5237    @Override
5238    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5239        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5240            return null;
5241        }
5242        synchronized (mPackages) {
5243            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5244                return null;
5245            }
5246            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5247            if (changedPackages == null) {
5248                return null;
5249            }
5250            final List<String> packageNames =
5251                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5252            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5253                final String packageName = changedPackages.get(i);
5254                if (packageName != null) {
5255                    packageNames.add(packageName);
5256                }
5257            }
5258            return packageNames.isEmpty()
5259                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5260        }
5261    }
5262
5263    @Override
5264    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5265        // allow instant applications
5266        ArrayList<FeatureInfo> res;
5267        synchronized (mAvailableFeatures) {
5268            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5269            res.addAll(mAvailableFeatures.values());
5270        }
5271        final FeatureInfo fi = new FeatureInfo();
5272        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5273                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5274        res.add(fi);
5275
5276        return new ParceledListSlice<>(res);
5277    }
5278
5279    @Override
5280    public boolean hasSystemFeature(String name, int version) {
5281        // allow instant applications
5282        synchronized (mAvailableFeatures) {
5283            final FeatureInfo feat = mAvailableFeatures.get(name);
5284            if (feat == null) {
5285                return false;
5286            } else {
5287                return feat.version >= version;
5288            }
5289        }
5290    }
5291
5292    @Override
5293    public int checkPermission(String permName, String pkgName, int userId) {
5294        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5295    }
5296
5297    @Override
5298    public int checkUidPermission(String permName, int uid) {
5299        synchronized (mPackages) {
5300            final String[] packageNames = getPackagesForUid(uid);
5301            final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0)
5302                    ? mPackages.get(packageNames[0])
5303                    : null;
5304            return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid());
5305        }
5306    }
5307
5308    @Override
5309    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5310        if (UserHandle.getCallingUserId() != userId) {
5311            mContext.enforceCallingPermission(
5312                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5313                    "isPermissionRevokedByPolicy for user " + userId);
5314        }
5315
5316        if (checkPermission(permission, packageName, userId)
5317                == PackageManager.PERMISSION_GRANTED) {
5318            return false;
5319        }
5320
5321        final int callingUid = Binder.getCallingUid();
5322        if (getInstantAppPackageName(callingUid) != null) {
5323            if (!isCallerSameApp(packageName, callingUid)) {
5324                return false;
5325            }
5326        } else {
5327            if (isInstantApp(packageName, userId)) {
5328                return false;
5329            }
5330        }
5331
5332        final long identity = Binder.clearCallingIdentity();
5333        try {
5334            final int flags = getPermissionFlags(permission, packageName, userId);
5335            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5336        } finally {
5337            Binder.restoreCallingIdentity(identity);
5338        }
5339    }
5340
5341    @Override
5342    public String getPermissionControllerPackageName() {
5343        synchronized (mPackages) {
5344            return mRequiredInstallerPackage;
5345        }
5346    }
5347
5348    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5349        return mPermissionManager.addDynamicPermission(
5350                info, async, getCallingUid(), new PermissionCallback() {
5351                    @Override
5352                    public void onPermissionChanged() {
5353                        if (!async) {
5354                            mSettings.writeLPr();
5355                        } else {
5356                            scheduleWriteSettingsLocked();
5357                        }
5358                    }
5359                });
5360    }
5361
5362    @Override
5363    public boolean addPermission(PermissionInfo info) {
5364        synchronized (mPackages) {
5365            return addDynamicPermission(info, false);
5366        }
5367    }
5368
5369    @Override
5370    public boolean addPermissionAsync(PermissionInfo info) {
5371        synchronized (mPackages) {
5372            return addDynamicPermission(info, true);
5373        }
5374    }
5375
5376    @Override
5377    public void removePermission(String permName) {
5378        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5379    }
5380
5381    @Override
5382    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5383        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5384                getCallingUid(), userId, mPermissionCallback);
5385    }
5386
5387    @Override
5388    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5389        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5390                getCallingUid(), userId, mPermissionCallback);
5391    }
5392
5393    @Override
5394    public void resetRuntimePermissions() {
5395        mContext.enforceCallingOrSelfPermission(
5396                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5397                "revokeRuntimePermission");
5398
5399        int callingUid = Binder.getCallingUid();
5400        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5401            mContext.enforceCallingOrSelfPermission(
5402                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5403                    "resetRuntimePermissions");
5404        }
5405
5406        synchronized (mPackages) {
5407            mPermissionManager.updateAllPermissions(
5408                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5409                    mPermissionCallback);
5410            for (int userId : UserManagerService.getInstance().getUserIds()) {
5411                final int packageCount = mPackages.size();
5412                for (int i = 0; i < packageCount; i++) {
5413                    PackageParser.Package pkg = mPackages.valueAt(i);
5414                    if (!(pkg.mExtras instanceof PackageSetting)) {
5415                        continue;
5416                    }
5417                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5418                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5419                }
5420            }
5421        }
5422    }
5423
5424    @Override
5425    public int getPermissionFlags(String permName, String packageName, int userId) {
5426        return mPermissionManager.getPermissionFlags(
5427                permName, packageName, getCallingUid(), userId);
5428    }
5429
5430    @Override
5431    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5432            int flagValues, int userId) {
5433        mPermissionManager.updatePermissionFlags(
5434                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5435                mPermissionCallback);
5436    }
5437
5438    /**
5439     * Update the permission flags for all packages and runtime permissions of a user in order
5440     * to allow device or profile owner to remove POLICY_FIXED.
5441     */
5442    @Override
5443    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5444        synchronized (mPackages) {
5445            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5446                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5447                    mPermissionCallback);
5448            if (changed) {
5449                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5450            }
5451        }
5452    }
5453
5454    @Override
5455    public boolean shouldShowRequestPermissionRationale(String permissionName,
5456            String packageName, int userId) {
5457        if (UserHandle.getCallingUserId() != userId) {
5458            mContext.enforceCallingPermission(
5459                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5460                    "canShowRequestPermissionRationale for user " + userId);
5461        }
5462
5463        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5464        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5465            return false;
5466        }
5467
5468        if (checkPermission(permissionName, packageName, userId)
5469                == PackageManager.PERMISSION_GRANTED) {
5470            return false;
5471        }
5472
5473        final int flags;
5474
5475        final long identity = Binder.clearCallingIdentity();
5476        try {
5477            flags = getPermissionFlags(permissionName,
5478                    packageName, userId);
5479        } finally {
5480            Binder.restoreCallingIdentity(identity);
5481        }
5482
5483        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5484                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5485                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5486
5487        if ((flags & fixedFlags) != 0) {
5488            return false;
5489        }
5490
5491        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5492    }
5493
5494    @Override
5495    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5496        mContext.enforceCallingOrSelfPermission(
5497                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5498                "addOnPermissionsChangeListener");
5499
5500        synchronized (mPackages) {
5501            mOnPermissionChangeListeners.addListenerLocked(listener);
5502        }
5503    }
5504
5505    @Override
5506    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5507        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5508            throw new SecurityException("Instant applications don't have access to this method");
5509        }
5510        synchronized (mPackages) {
5511            mOnPermissionChangeListeners.removeListenerLocked(listener);
5512        }
5513    }
5514
5515    @Override
5516    public boolean isProtectedBroadcast(String actionName) {
5517        // allow instant applications
5518        synchronized (mProtectedBroadcasts) {
5519            if (mProtectedBroadcasts.contains(actionName)) {
5520                return true;
5521            } else if (actionName != null) {
5522                // TODO: remove these terrible hacks
5523                if (actionName.startsWith("android.net.netmon.lingerExpired")
5524                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5525                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5526                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5527                    return true;
5528                }
5529            }
5530        }
5531        return false;
5532    }
5533
5534    @Override
5535    public int checkSignatures(String pkg1, String pkg2) {
5536        synchronized (mPackages) {
5537            final PackageParser.Package p1 = mPackages.get(pkg1);
5538            final PackageParser.Package p2 = mPackages.get(pkg2);
5539            if (p1 == null || p1.mExtras == null
5540                    || p2 == null || p2.mExtras == null) {
5541                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5542            }
5543            final int callingUid = Binder.getCallingUid();
5544            final int callingUserId = UserHandle.getUserId(callingUid);
5545            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5546            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5547            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5548                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5549                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5550            }
5551            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5552        }
5553    }
5554
5555    @Override
5556    public int checkUidSignatures(int uid1, int uid2) {
5557        final int callingUid = Binder.getCallingUid();
5558        final int callingUserId = UserHandle.getUserId(callingUid);
5559        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5560        // Map to base uids.
5561        uid1 = UserHandle.getAppId(uid1);
5562        uid2 = UserHandle.getAppId(uid2);
5563        // reader
5564        synchronized (mPackages) {
5565            Signature[] s1;
5566            Signature[] s2;
5567            Object obj = mSettings.getUserIdLPr(uid1);
5568            if (obj != null) {
5569                if (obj instanceof SharedUserSetting) {
5570                    if (isCallerInstantApp) {
5571                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5572                    }
5573                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5574                } else if (obj instanceof PackageSetting) {
5575                    final PackageSetting ps = (PackageSetting) obj;
5576                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5577                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5578                    }
5579                    s1 = ps.signatures.mSigningDetails.signatures;
5580                } else {
5581                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5582                }
5583            } else {
5584                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5585            }
5586            obj = mSettings.getUserIdLPr(uid2);
5587            if (obj != null) {
5588                if (obj instanceof SharedUserSetting) {
5589                    if (isCallerInstantApp) {
5590                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5591                    }
5592                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5593                } else if (obj instanceof PackageSetting) {
5594                    final PackageSetting ps = (PackageSetting) obj;
5595                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5596                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5597                    }
5598                    s2 = ps.signatures.mSigningDetails.signatures;
5599                } else {
5600                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5601                }
5602            } else {
5603                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5604            }
5605            return compareSignatures(s1, s2);
5606        }
5607    }
5608
5609    @Override
5610    public boolean hasSigningCertificate(
5611            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5612
5613        synchronized (mPackages) {
5614            final PackageParser.Package p = mPackages.get(packageName);
5615            if (p == null || p.mExtras == null) {
5616                return false;
5617            }
5618            final int callingUid = Binder.getCallingUid();
5619            final int callingUserId = UserHandle.getUserId(callingUid);
5620            final PackageSetting ps = (PackageSetting) p.mExtras;
5621            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5622                return false;
5623            }
5624            switch (type) {
5625                case CERT_INPUT_RAW_X509:
5626                    return p.mSigningDetails.hasCertificate(certificate);
5627                case CERT_INPUT_SHA256:
5628                    return p.mSigningDetails.hasSha256Certificate(certificate);
5629                default:
5630                    return false;
5631            }
5632        }
5633    }
5634
5635    @Override
5636    public boolean hasUidSigningCertificate(
5637            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5638        final int callingUid = Binder.getCallingUid();
5639        final int callingUserId = UserHandle.getUserId(callingUid);
5640        // Map to base uids.
5641        uid = UserHandle.getAppId(uid);
5642        // reader
5643        synchronized (mPackages) {
5644            final PackageParser.SigningDetails signingDetails;
5645            final Object obj = mSettings.getUserIdLPr(uid);
5646            if (obj != null) {
5647                if (obj instanceof SharedUserSetting) {
5648                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5649                    if (isCallerInstantApp) {
5650                        return false;
5651                    }
5652                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5653                } else if (obj instanceof PackageSetting) {
5654                    final PackageSetting ps = (PackageSetting) obj;
5655                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5656                        return false;
5657                    }
5658                    signingDetails = ps.signatures.mSigningDetails;
5659                } else {
5660                    return false;
5661                }
5662            } else {
5663                return false;
5664            }
5665            switch (type) {
5666                case CERT_INPUT_RAW_X509:
5667                    return signingDetails.hasCertificate(certificate);
5668                case CERT_INPUT_SHA256:
5669                    return signingDetails.hasSha256Certificate(certificate);
5670                default:
5671                    return false;
5672            }
5673        }
5674    }
5675
5676    /**
5677     * This method should typically only be used when granting or revoking
5678     * permissions, since the app may immediately restart after this call.
5679     * <p>
5680     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5681     * guard your work against the app being relaunched.
5682     */
5683    private void killUid(int appId, int userId, String reason) {
5684        final long identity = Binder.clearCallingIdentity();
5685        try {
5686            IActivityManager am = ActivityManager.getService();
5687            if (am != null) {
5688                try {
5689                    am.killUid(appId, userId, reason);
5690                } catch (RemoteException e) {
5691                    /* ignore - same process */
5692                }
5693            }
5694        } finally {
5695            Binder.restoreCallingIdentity(identity);
5696        }
5697    }
5698
5699    /**
5700     * If the database version for this type of package (internal storage or
5701     * external storage) is less than the version where package signatures
5702     * were updated, return true.
5703     */
5704    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5705        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5706        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5707    }
5708
5709    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5710        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5711        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5712    }
5713
5714    @Override
5715    public List<String> getAllPackages() {
5716        final int callingUid = Binder.getCallingUid();
5717        final int callingUserId = UserHandle.getUserId(callingUid);
5718        synchronized (mPackages) {
5719            if (canViewInstantApps(callingUid, callingUserId)) {
5720                return new ArrayList<String>(mPackages.keySet());
5721            }
5722            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5723            final List<String> result = new ArrayList<>();
5724            if (instantAppPkgName != null) {
5725                // caller is an instant application; filter unexposed applications
5726                for (PackageParser.Package pkg : mPackages.values()) {
5727                    if (!pkg.visibleToInstantApps) {
5728                        continue;
5729                    }
5730                    result.add(pkg.packageName);
5731                }
5732            } else {
5733                // caller is a normal application; filter instant applications
5734                for (PackageParser.Package pkg : mPackages.values()) {
5735                    final PackageSetting ps =
5736                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5737                    if (ps != null
5738                            && ps.getInstantApp(callingUserId)
5739                            && !mInstantAppRegistry.isInstantAccessGranted(
5740                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5741                        continue;
5742                    }
5743                    result.add(pkg.packageName);
5744                }
5745            }
5746            return result;
5747        }
5748    }
5749
5750    @Override
5751    public String[] getPackagesForUid(int uid) {
5752        final int callingUid = Binder.getCallingUid();
5753        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5754        final int userId = UserHandle.getUserId(uid);
5755        uid = UserHandle.getAppId(uid);
5756        // reader
5757        synchronized (mPackages) {
5758            Object obj = mSettings.getUserIdLPr(uid);
5759            if (obj instanceof SharedUserSetting) {
5760                if (isCallerInstantApp) {
5761                    return null;
5762                }
5763                final SharedUserSetting sus = (SharedUserSetting) obj;
5764                final int N = sus.packages.size();
5765                String[] res = new String[N];
5766                final Iterator<PackageSetting> it = sus.packages.iterator();
5767                int i = 0;
5768                while (it.hasNext()) {
5769                    PackageSetting ps = it.next();
5770                    if (ps.getInstalled(userId)) {
5771                        res[i++] = ps.name;
5772                    } else {
5773                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5774                    }
5775                }
5776                return res;
5777            } else if (obj instanceof PackageSetting) {
5778                final PackageSetting ps = (PackageSetting) obj;
5779                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5780                    return new String[]{ps.name};
5781                }
5782            }
5783        }
5784        return null;
5785    }
5786
5787    @Override
5788    public String getNameForUid(int uid) {
5789        final int callingUid = Binder.getCallingUid();
5790        if (getInstantAppPackageName(callingUid) != null) {
5791            return null;
5792        }
5793        synchronized (mPackages) {
5794            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5795            if (obj instanceof SharedUserSetting) {
5796                final SharedUserSetting sus = (SharedUserSetting) obj;
5797                return sus.name + ":" + sus.userId;
5798            } else if (obj instanceof PackageSetting) {
5799                final PackageSetting ps = (PackageSetting) obj;
5800                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5801                    return null;
5802                }
5803                return ps.name;
5804            }
5805            return null;
5806        }
5807    }
5808
5809    @Override
5810    public String[] getNamesForUids(int[] uids) {
5811        if (uids == null || uids.length == 0) {
5812            return null;
5813        }
5814        final int callingUid = Binder.getCallingUid();
5815        if (getInstantAppPackageName(callingUid) != null) {
5816            return null;
5817        }
5818        final String[] names = new String[uids.length];
5819        synchronized (mPackages) {
5820            for (int i = uids.length - 1; i >= 0; i--) {
5821                final int uid = uids[i];
5822                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5823                if (obj instanceof SharedUserSetting) {
5824                    final SharedUserSetting sus = (SharedUserSetting) obj;
5825                    names[i] = "shared:" + sus.name;
5826                } else if (obj instanceof PackageSetting) {
5827                    final PackageSetting ps = (PackageSetting) obj;
5828                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5829                        names[i] = null;
5830                    } else {
5831                        names[i] = ps.name;
5832                    }
5833                } else {
5834                    names[i] = null;
5835                }
5836            }
5837        }
5838        return names;
5839    }
5840
5841    @Override
5842    public int getUidForSharedUser(String sharedUserName) {
5843        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5844            return -1;
5845        }
5846        if (sharedUserName == null) {
5847            return -1;
5848        }
5849        // reader
5850        synchronized (mPackages) {
5851            SharedUserSetting suid;
5852            try {
5853                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5854                if (suid != null) {
5855                    return suid.userId;
5856                }
5857            } catch (PackageManagerException ignore) {
5858                // can't happen, but, still need to catch it
5859            }
5860            return -1;
5861        }
5862    }
5863
5864    @Override
5865    public int getFlagsForUid(int uid) {
5866        final int callingUid = Binder.getCallingUid();
5867        if (getInstantAppPackageName(callingUid) != null) {
5868            return 0;
5869        }
5870        synchronized (mPackages) {
5871            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5872            if (obj instanceof SharedUserSetting) {
5873                final SharedUserSetting sus = (SharedUserSetting) obj;
5874                return sus.pkgFlags;
5875            } else if (obj instanceof PackageSetting) {
5876                final PackageSetting ps = (PackageSetting) obj;
5877                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5878                    return 0;
5879                }
5880                return ps.pkgFlags;
5881            }
5882        }
5883        return 0;
5884    }
5885
5886    @Override
5887    public int getPrivateFlagsForUid(int uid) {
5888        final int callingUid = Binder.getCallingUid();
5889        if (getInstantAppPackageName(callingUid) != null) {
5890            return 0;
5891        }
5892        synchronized (mPackages) {
5893            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5894            if (obj instanceof SharedUserSetting) {
5895                final SharedUserSetting sus = (SharedUserSetting) obj;
5896                return sus.pkgPrivateFlags;
5897            } else if (obj instanceof PackageSetting) {
5898                final PackageSetting ps = (PackageSetting) obj;
5899                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5900                    return 0;
5901                }
5902                return ps.pkgPrivateFlags;
5903            }
5904        }
5905        return 0;
5906    }
5907
5908    @Override
5909    public boolean isUidPrivileged(int uid) {
5910        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5911            return false;
5912        }
5913        uid = UserHandle.getAppId(uid);
5914        // reader
5915        synchronized (mPackages) {
5916            Object obj = mSettings.getUserIdLPr(uid);
5917            if (obj instanceof SharedUserSetting) {
5918                final SharedUserSetting sus = (SharedUserSetting) obj;
5919                final Iterator<PackageSetting> it = sus.packages.iterator();
5920                while (it.hasNext()) {
5921                    if (it.next().isPrivileged()) {
5922                        return true;
5923                    }
5924                }
5925            } else if (obj instanceof PackageSetting) {
5926                final PackageSetting ps = (PackageSetting) obj;
5927                return ps.isPrivileged();
5928            }
5929        }
5930        return false;
5931    }
5932
5933    @Override
5934    public String[] getAppOpPermissionPackages(String permName) {
5935        return mPermissionManager.getAppOpPermissionPackages(permName);
5936    }
5937
5938    @Override
5939    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5940            int flags, int userId) {
5941        return resolveIntentInternal(
5942                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5943    }
5944
5945    /**
5946     * Normally instant apps can only be resolved when they're visible to the caller.
5947     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5948     * since we need to allow the system to start any installed application.
5949     */
5950    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5951            int flags, int userId, boolean resolveForStart) {
5952        try {
5953            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5954
5955            if (!sUserManager.exists(userId)) return null;
5956            final int callingUid = Binder.getCallingUid();
5957            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5958            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5959                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5960
5961            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5962            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5963                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5964            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5965
5966            final ResolveInfo bestChoice =
5967                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5968            return bestChoice;
5969        } finally {
5970            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5971        }
5972    }
5973
5974    @Override
5975    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5976        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5977            throw new SecurityException(
5978                    "findPersistentPreferredActivity can only be run by the system");
5979        }
5980        if (!sUserManager.exists(userId)) {
5981            return null;
5982        }
5983        final int callingUid = Binder.getCallingUid();
5984        intent = updateIntentForResolve(intent);
5985        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5986        final int flags = updateFlagsForResolve(
5987                0, userId, intent, callingUid, false /*includeInstantApps*/);
5988        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5989                userId);
5990        synchronized (mPackages) {
5991            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5992                    userId);
5993        }
5994    }
5995
5996    @Override
5997    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5998            IntentFilter filter, int match, ComponentName activity) {
5999        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6000            return;
6001        }
6002        final int userId = UserHandle.getCallingUserId();
6003        if (DEBUG_PREFERRED) {
6004            Log.v(TAG, "setLastChosenActivity intent=" + intent
6005                + " resolvedType=" + resolvedType
6006                + " flags=" + flags
6007                + " filter=" + filter
6008                + " match=" + match
6009                + " activity=" + activity);
6010            filter.dump(new PrintStreamPrinter(System.out), "    ");
6011        }
6012        intent.setComponent(null);
6013        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6014                userId);
6015        // Find any earlier preferred or last chosen entries and nuke them
6016        findPreferredActivity(intent, resolvedType,
6017                flags, query, 0, false, true, false, userId);
6018        // Add the new activity as the last chosen for this filter
6019        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6020                "Setting last chosen");
6021    }
6022
6023    @Override
6024    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6025        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6026            return null;
6027        }
6028        final int userId = UserHandle.getCallingUserId();
6029        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6030        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6031                userId);
6032        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6033                false, false, false, userId);
6034    }
6035
6036    /**
6037     * Returns whether or not instant apps have been disabled remotely.
6038     */
6039    private boolean areWebInstantAppsDisabled() {
6040        return mWebInstantAppsDisabled;
6041    }
6042
6043    private boolean isInstantAppResolutionAllowed(
6044            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6045            boolean skipPackageCheck) {
6046        if (mInstantAppResolverConnection == null) {
6047            return false;
6048        }
6049        if (mInstantAppInstallerActivity == null) {
6050            return false;
6051        }
6052        if (intent.getComponent() != null) {
6053            return false;
6054        }
6055        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6056            return false;
6057        }
6058        if (!skipPackageCheck && intent.getPackage() != null) {
6059            return false;
6060        }
6061        if (!intent.isWebIntent()) {
6062            // for non web intents, we should not resolve externally if an app already exists to
6063            // handle it or if the caller didn't explicitly request it.
6064            if ((resolvedActivities != null && resolvedActivities.size() != 0)
6065                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
6066                return false;
6067            }
6068        } else {
6069            if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
6070                return false;
6071            } else if (areWebInstantAppsDisabled()) {
6072                return false;
6073            }
6074        }
6075        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6076        // Or if there's already an ephemeral app installed that handles the action
6077        synchronized (mPackages) {
6078            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6079            for (int n = 0; n < count; n++) {
6080                final ResolveInfo info = resolvedActivities.get(n);
6081                final String packageName = info.activityInfo.packageName;
6082                final PackageSetting ps = mSettings.mPackages.get(packageName);
6083                if (ps != null) {
6084                    // only check domain verification status if the app is not a browser
6085                    if (!info.handleAllWebDataURI) {
6086                        // Try to get the status from User settings first
6087                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6088                        final int status = (int) (packedStatus >> 32);
6089                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6090                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6091                            if (DEBUG_INSTANT) {
6092                                Slog.v(TAG, "DENY instant app;"
6093                                    + " pkg: " + packageName + ", status: " + status);
6094                            }
6095                            return false;
6096                        }
6097                    }
6098                    if (ps.getInstantApp(userId)) {
6099                        if (DEBUG_INSTANT) {
6100                            Slog.v(TAG, "DENY instant app installed;"
6101                                    + " pkg: " + packageName);
6102                        }
6103                        return false;
6104                    }
6105                }
6106            }
6107        }
6108        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6109        return true;
6110    }
6111
6112    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6113            Intent origIntent, String resolvedType, String callingPackage,
6114            Bundle verificationBundle, int userId) {
6115        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6116                new InstantAppRequest(responseObj, origIntent, resolvedType,
6117                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6118        mHandler.sendMessage(msg);
6119    }
6120
6121    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6122            int flags, List<ResolveInfo> query, int userId) {
6123        if (query != null) {
6124            final int N = query.size();
6125            if (N == 1) {
6126                return query.get(0);
6127            } else if (N > 1) {
6128                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6129                // If there is more than one activity with the same priority,
6130                // then let the user decide between them.
6131                ResolveInfo r0 = query.get(0);
6132                ResolveInfo r1 = query.get(1);
6133                if (DEBUG_INTENT_MATCHING || debug) {
6134                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6135                            + r1.activityInfo.name + "=" + r1.priority);
6136                }
6137                // If the first activity has a higher priority, or a different
6138                // default, then it is always desirable to pick it.
6139                if (r0.priority != r1.priority
6140                        || r0.preferredOrder != r1.preferredOrder
6141                        || r0.isDefault != r1.isDefault) {
6142                    return query.get(0);
6143                }
6144                // If we have saved a preference for a preferred activity for
6145                // this Intent, use that.
6146                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6147                        flags, query, r0.priority, true, false, debug, userId);
6148                if (ri != null) {
6149                    return ri;
6150                }
6151                // If we have an ephemeral app, use it
6152                for (int i = 0; i < N; i++) {
6153                    ri = query.get(i);
6154                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6155                        final String packageName = ri.activityInfo.packageName;
6156                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6157                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6158                        final int status = (int)(packedStatus >> 32);
6159                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6160                            return ri;
6161                        }
6162                    }
6163                }
6164                ri = new ResolveInfo(mResolveInfo);
6165                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6166                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6167                // If all of the options come from the same package, show the application's
6168                // label and icon instead of the generic resolver's.
6169                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6170                // and then throw away the ResolveInfo itself, meaning that the caller loses
6171                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6172                // a fallback for this case; we only set the target package's resources on
6173                // the ResolveInfo, not the ActivityInfo.
6174                final String intentPackage = intent.getPackage();
6175                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6176                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6177                    ri.resolvePackageName = intentPackage;
6178                    if (userNeedsBadging(userId)) {
6179                        ri.noResourceId = true;
6180                    } else {
6181                        ri.icon = appi.icon;
6182                    }
6183                    ri.iconResourceId = appi.icon;
6184                    ri.labelRes = appi.labelRes;
6185                }
6186                ri.activityInfo.applicationInfo = new ApplicationInfo(
6187                        ri.activityInfo.applicationInfo);
6188                if (userId != 0) {
6189                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6190                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6191                }
6192                // Make sure that the resolver is displayable in car mode
6193                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6194                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6195                return ri;
6196            }
6197        }
6198        return null;
6199    }
6200
6201    /**
6202     * Return true if the given list is not empty and all of its contents have
6203     * an activityInfo with the given package name.
6204     */
6205    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6206        if (ArrayUtils.isEmpty(list)) {
6207            return false;
6208        }
6209        for (int i = 0, N = list.size(); i < N; i++) {
6210            final ResolveInfo ri = list.get(i);
6211            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6212            if (ai == null || !packageName.equals(ai.packageName)) {
6213                return false;
6214            }
6215        }
6216        return true;
6217    }
6218
6219    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6220            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6221        final int N = query.size();
6222        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6223                .get(userId);
6224        // Get the list of persistent preferred activities that handle the intent
6225        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6226        List<PersistentPreferredActivity> pprefs = ppir != null
6227                ? ppir.queryIntent(intent, resolvedType,
6228                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6229                        userId)
6230                : null;
6231        if (pprefs != null && pprefs.size() > 0) {
6232            final int M = pprefs.size();
6233            for (int i=0; i<M; i++) {
6234                final PersistentPreferredActivity ppa = pprefs.get(i);
6235                if (DEBUG_PREFERRED || debug) {
6236                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6237                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6238                            + "\n  component=" + ppa.mComponent);
6239                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6240                }
6241                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6242                        flags | MATCH_DISABLED_COMPONENTS, userId);
6243                if (DEBUG_PREFERRED || debug) {
6244                    Slog.v(TAG, "Found persistent preferred activity:");
6245                    if (ai != null) {
6246                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6247                    } else {
6248                        Slog.v(TAG, "  null");
6249                    }
6250                }
6251                if (ai == null) {
6252                    // This previously registered persistent preferred activity
6253                    // component is no longer known. Ignore it and do NOT remove it.
6254                    continue;
6255                }
6256                for (int j=0; j<N; j++) {
6257                    final ResolveInfo ri = query.get(j);
6258                    if (!ri.activityInfo.applicationInfo.packageName
6259                            .equals(ai.applicationInfo.packageName)) {
6260                        continue;
6261                    }
6262                    if (!ri.activityInfo.name.equals(ai.name)) {
6263                        continue;
6264                    }
6265                    //  Found a persistent preference that can handle the intent.
6266                    if (DEBUG_PREFERRED || debug) {
6267                        Slog.v(TAG, "Returning persistent preferred activity: " +
6268                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6269                    }
6270                    return ri;
6271                }
6272            }
6273        }
6274        return null;
6275    }
6276
6277    // TODO: handle preferred activities missing while user has amnesia
6278    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6279            List<ResolveInfo> query, int priority, boolean always,
6280            boolean removeMatches, boolean debug, int userId) {
6281        if (!sUserManager.exists(userId)) return null;
6282        final int callingUid = Binder.getCallingUid();
6283        flags = updateFlagsForResolve(
6284                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6285        intent = updateIntentForResolve(intent);
6286        // writer
6287        synchronized (mPackages) {
6288            // Try to find a matching persistent preferred activity.
6289            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6290                    debug, userId);
6291
6292            // If a persistent preferred activity matched, use it.
6293            if (pri != null) {
6294                return pri;
6295            }
6296
6297            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6298            // Get the list of preferred activities that handle the intent
6299            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6300            List<PreferredActivity> prefs = pir != null
6301                    ? pir.queryIntent(intent, resolvedType,
6302                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6303                            userId)
6304                    : null;
6305            if (prefs != null && prefs.size() > 0) {
6306                boolean changed = false;
6307                try {
6308                    // First figure out how good the original match set is.
6309                    // We will only allow preferred activities that came
6310                    // from the same match quality.
6311                    int match = 0;
6312
6313                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6314
6315                    final int N = query.size();
6316                    for (int j=0; j<N; j++) {
6317                        final ResolveInfo ri = query.get(j);
6318                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6319                                + ": 0x" + Integer.toHexString(match));
6320                        if (ri.match > match) {
6321                            match = ri.match;
6322                        }
6323                    }
6324
6325                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6326                            + Integer.toHexString(match));
6327
6328                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6329                    final int M = prefs.size();
6330                    for (int i=0; i<M; i++) {
6331                        final PreferredActivity pa = prefs.get(i);
6332                        if (DEBUG_PREFERRED || debug) {
6333                            Slog.v(TAG, "Checking PreferredActivity ds="
6334                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6335                                    + "\n  component=" + pa.mPref.mComponent);
6336                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6337                        }
6338                        if (pa.mPref.mMatch != match) {
6339                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6340                                    + Integer.toHexString(pa.mPref.mMatch));
6341                            continue;
6342                        }
6343                        // If it's not an "always" type preferred activity and that's what we're
6344                        // looking for, skip it.
6345                        if (always && !pa.mPref.mAlways) {
6346                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6347                            continue;
6348                        }
6349                        final ActivityInfo ai = getActivityInfo(
6350                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6351                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6352                                userId);
6353                        if (DEBUG_PREFERRED || debug) {
6354                            Slog.v(TAG, "Found preferred activity:");
6355                            if (ai != null) {
6356                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6357                            } else {
6358                                Slog.v(TAG, "  null");
6359                            }
6360                        }
6361                        if (ai == null) {
6362                            // This previously registered preferred activity
6363                            // component is no longer known.  Most likely an update
6364                            // to the app was installed and in the new version this
6365                            // component no longer exists.  Clean it up by removing
6366                            // it from the preferred activities list, and skip it.
6367                            Slog.w(TAG, "Removing dangling preferred activity: "
6368                                    + pa.mPref.mComponent);
6369                            pir.removeFilter(pa);
6370                            changed = true;
6371                            continue;
6372                        }
6373                        for (int j=0; j<N; j++) {
6374                            final ResolveInfo ri = query.get(j);
6375                            if (!ri.activityInfo.applicationInfo.packageName
6376                                    .equals(ai.applicationInfo.packageName)) {
6377                                continue;
6378                            }
6379                            if (!ri.activityInfo.name.equals(ai.name)) {
6380                                continue;
6381                            }
6382
6383                            if (removeMatches) {
6384                                pir.removeFilter(pa);
6385                                changed = true;
6386                                if (DEBUG_PREFERRED) {
6387                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6388                                }
6389                                break;
6390                            }
6391
6392                            // Okay we found a previously set preferred or last chosen app.
6393                            // If the result set is different from when this
6394                            // was created, and is not a subset of the preferred set, we need to
6395                            // clear it and re-ask the user their preference, if we're looking for
6396                            // an "always" type entry.
6397                            if (always && !pa.mPref.sameSet(query)) {
6398                                if (pa.mPref.isSuperset(query)) {
6399                                    // some components of the set are no longer present in
6400                                    // the query, but the preferred activity can still be reused
6401                                    if (DEBUG_PREFERRED) {
6402                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6403                                                + " still valid as only non-preferred components"
6404                                                + " were removed for " + intent + " type "
6405                                                + resolvedType);
6406                                    }
6407                                    // remove obsolete components and re-add the up-to-date filter
6408                                    PreferredActivity freshPa = new PreferredActivity(pa,
6409                                            pa.mPref.mMatch,
6410                                            pa.mPref.discardObsoleteComponents(query),
6411                                            pa.mPref.mComponent,
6412                                            pa.mPref.mAlways);
6413                                    pir.removeFilter(pa);
6414                                    pir.addFilter(freshPa);
6415                                    changed = true;
6416                                } else {
6417                                    Slog.i(TAG,
6418                                            "Result set changed, dropping preferred activity for "
6419                                                    + intent + " type " + resolvedType);
6420                                    if (DEBUG_PREFERRED) {
6421                                        Slog.v(TAG, "Removing preferred activity since set changed "
6422                                                + pa.mPref.mComponent);
6423                                    }
6424                                    pir.removeFilter(pa);
6425                                    // Re-add the filter as a "last chosen" entry (!always)
6426                                    PreferredActivity lastChosen = new PreferredActivity(
6427                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6428                                    pir.addFilter(lastChosen);
6429                                    changed = true;
6430                                    return null;
6431                                }
6432                            }
6433
6434                            // Yay! Either the set matched or we're looking for the last chosen
6435                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6436                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6437                            return ri;
6438                        }
6439                    }
6440                } finally {
6441                    if (changed) {
6442                        if (DEBUG_PREFERRED) {
6443                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6444                        }
6445                        scheduleWritePackageRestrictionsLocked(userId);
6446                    }
6447                }
6448            }
6449        }
6450        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6451        return null;
6452    }
6453
6454    /*
6455     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6456     */
6457    @Override
6458    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6459            int targetUserId) {
6460        mContext.enforceCallingOrSelfPermission(
6461                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6462        List<CrossProfileIntentFilter> matches =
6463                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6464        if (matches != null) {
6465            int size = matches.size();
6466            for (int i = 0; i < size; i++) {
6467                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6468            }
6469        }
6470        if (intent.hasWebURI()) {
6471            // cross-profile app linking works only towards the parent.
6472            final int callingUid = Binder.getCallingUid();
6473            final UserInfo parent = getProfileParent(sourceUserId);
6474            synchronized(mPackages) {
6475                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6476                        false /*includeInstantApps*/);
6477                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6478                        intent, resolvedType, flags, sourceUserId, parent.id);
6479                return xpDomainInfo != null;
6480            }
6481        }
6482        return false;
6483    }
6484
6485    private UserInfo getProfileParent(int userId) {
6486        final long identity = Binder.clearCallingIdentity();
6487        try {
6488            return sUserManager.getProfileParent(userId);
6489        } finally {
6490            Binder.restoreCallingIdentity(identity);
6491        }
6492    }
6493
6494    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6495            String resolvedType, int userId) {
6496        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6497        if (resolver != null) {
6498            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6499        }
6500        return null;
6501    }
6502
6503    @Override
6504    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6505            String resolvedType, int flags, int userId) {
6506        try {
6507            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6508
6509            return new ParceledListSlice<>(
6510                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6511        } finally {
6512            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6513        }
6514    }
6515
6516    /**
6517     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6518     * instant, returns {@code null}.
6519     */
6520    private String getInstantAppPackageName(int callingUid) {
6521        synchronized (mPackages) {
6522            // If the caller is an isolated app use the owner's uid for the lookup.
6523            if (Process.isIsolated(callingUid)) {
6524                callingUid = mIsolatedOwners.get(callingUid);
6525            }
6526            final int appId = UserHandle.getAppId(callingUid);
6527            final Object obj = mSettings.getUserIdLPr(appId);
6528            if (obj instanceof PackageSetting) {
6529                final PackageSetting ps = (PackageSetting) obj;
6530                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6531                return isInstantApp ? ps.pkg.packageName : null;
6532            }
6533        }
6534        return null;
6535    }
6536
6537    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6538            String resolvedType, int flags, int userId) {
6539        return queryIntentActivitiesInternal(
6540                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6541                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6542    }
6543
6544    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6545            String resolvedType, int flags, int filterCallingUid, int userId,
6546            boolean resolveForStart, boolean allowDynamicSplits) {
6547        if (!sUserManager.exists(userId)) return Collections.emptyList();
6548        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6549        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6550                false /* requireFullPermission */, false /* checkShell */,
6551                "query intent activities");
6552        final String pkgName = intent.getPackage();
6553        ComponentName comp = intent.getComponent();
6554        if (comp == null) {
6555            if (intent.getSelector() != null) {
6556                intent = intent.getSelector();
6557                comp = intent.getComponent();
6558            }
6559        }
6560
6561        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6562                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6563        if (comp != null) {
6564            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6565            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6566            if (ai != null) {
6567                // When specifying an explicit component, we prevent the activity from being
6568                // used when either 1) the calling package is normal and the activity is within
6569                // an ephemeral application or 2) the calling package is ephemeral and the
6570                // activity is not visible to ephemeral applications.
6571                final boolean matchInstantApp =
6572                        (flags & PackageManager.MATCH_INSTANT) != 0;
6573                final boolean matchVisibleToInstantAppOnly =
6574                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6575                final boolean matchExplicitlyVisibleOnly =
6576                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6577                final boolean isCallerInstantApp =
6578                        instantAppPkgName != null;
6579                final boolean isTargetSameInstantApp =
6580                        comp.getPackageName().equals(instantAppPkgName);
6581                final boolean isTargetInstantApp =
6582                        (ai.applicationInfo.privateFlags
6583                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6584                final boolean isTargetVisibleToInstantApp =
6585                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6586                final boolean isTargetExplicitlyVisibleToInstantApp =
6587                        isTargetVisibleToInstantApp
6588                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6589                final boolean isTargetHiddenFromInstantApp =
6590                        !isTargetVisibleToInstantApp
6591                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6592                final boolean blockResolution =
6593                        !isTargetSameInstantApp
6594                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6595                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6596                                        && isTargetHiddenFromInstantApp));
6597                if (!blockResolution) {
6598                    final ResolveInfo ri = new ResolveInfo();
6599                    ri.activityInfo = ai;
6600                    list.add(ri);
6601                }
6602            }
6603            return applyPostResolutionFilter(
6604                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6605        }
6606
6607        // reader
6608        boolean sortResult = false;
6609        boolean addInstant = false;
6610        List<ResolveInfo> result;
6611        synchronized (mPackages) {
6612            if (pkgName == null) {
6613                List<CrossProfileIntentFilter> matchingFilters =
6614                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6615                // Check for results that need to skip the current profile.
6616                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6617                        resolvedType, flags, userId);
6618                if (xpResolveInfo != null) {
6619                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6620                    xpResult.add(xpResolveInfo);
6621                    return applyPostResolutionFilter(
6622                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6623                            allowDynamicSplits, filterCallingUid, userId, intent);
6624                }
6625
6626                // Check for results in the current profile.
6627                result = filterIfNotSystemUser(mActivities.queryIntent(
6628                        intent, resolvedType, flags, userId), userId);
6629                addInstant = isInstantAppResolutionAllowed(intent, result, userId,
6630                        false /*skipPackageCheck*/);
6631                // Check for cross profile results.
6632                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6633                xpResolveInfo = queryCrossProfileIntents(
6634                        matchingFilters, intent, resolvedType, flags, userId,
6635                        hasNonNegativePriorityResult);
6636                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6637                    boolean isVisibleToUser = filterIfNotSystemUser(
6638                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6639                    if (isVisibleToUser) {
6640                        result.add(xpResolveInfo);
6641                        sortResult = true;
6642                    }
6643                }
6644                if (intent.hasWebURI()) {
6645                    CrossProfileDomainInfo xpDomainInfo = null;
6646                    final UserInfo parent = getProfileParent(userId);
6647                    if (parent != null) {
6648                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6649                                flags, userId, parent.id);
6650                    }
6651                    if (xpDomainInfo != null) {
6652                        if (xpResolveInfo != null) {
6653                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6654                            // in the result.
6655                            result.remove(xpResolveInfo);
6656                        }
6657                        if (result.size() == 0 && !addInstant) {
6658                            // No result in current profile, but found candidate in parent user.
6659                            // And we are not going to add emphemeral app, so we can return the
6660                            // result straight away.
6661                            result.add(xpDomainInfo.resolveInfo);
6662                            return applyPostResolutionFilter(result, instantAppPkgName,
6663                                    allowDynamicSplits, filterCallingUid, userId, intent);
6664                        }
6665                    } else if (result.size() <= 1 && !addInstant) {
6666                        // No result in parent user and <= 1 result in current profile, and we
6667                        // are not going to add emphemeral app, so we can return the result without
6668                        // further processing.
6669                        return applyPostResolutionFilter(result, instantAppPkgName,
6670                                allowDynamicSplits, filterCallingUid, userId, intent);
6671                    }
6672                    // We have more than one candidate (combining results from current and parent
6673                    // profile), so we need filtering and sorting.
6674                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6675                            intent, flags, result, xpDomainInfo, userId);
6676                    sortResult = true;
6677                }
6678            } else {
6679                final PackageParser.Package pkg = mPackages.get(pkgName);
6680                result = null;
6681                if (pkg != null) {
6682                    result = filterIfNotSystemUser(
6683                            mActivities.queryIntentForPackage(
6684                                    intent, resolvedType, flags, pkg.activities, userId),
6685                            userId);
6686                }
6687                if (result == null || result.size() == 0) {
6688                    // the caller wants to resolve for a particular package; however, there
6689                    // were no installed results, so, try to find an ephemeral result
6690                    addInstant = isInstantAppResolutionAllowed(
6691                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6692                    if (result == null) {
6693                        result = new ArrayList<>();
6694                    }
6695                }
6696            }
6697        }
6698        if (addInstant) {
6699            result = maybeAddInstantAppInstaller(
6700                    result, intent, resolvedType, flags, userId, resolveForStart);
6701        }
6702        if (sortResult) {
6703            Collections.sort(result, mResolvePrioritySorter);
6704        }
6705        return applyPostResolutionFilter(
6706                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6707    }
6708
6709    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6710            String resolvedType, int flags, int userId, boolean resolveForStart) {
6711        // first, check to see if we've got an instant app already installed
6712        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6713        ResolveInfo localInstantApp = null;
6714        boolean blockResolution = false;
6715        if (!alreadyResolvedLocally) {
6716            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6717                    flags
6718                        | PackageManager.GET_RESOLVED_FILTER
6719                        | PackageManager.MATCH_INSTANT
6720                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6721                    userId);
6722            for (int i = instantApps.size() - 1; i >= 0; --i) {
6723                final ResolveInfo info = instantApps.get(i);
6724                final String packageName = info.activityInfo.packageName;
6725                final PackageSetting ps = mSettings.mPackages.get(packageName);
6726                if (ps.getInstantApp(userId)) {
6727                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6728                    final int status = (int)(packedStatus >> 32);
6729                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6730                        // there's a local instant application installed, but, the user has
6731                        // chosen to never use it; skip resolution and don't acknowledge
6732                        // an instant application is even available
6733                        if (DEBUG_INSTANT) {
6734                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6735                        }
6736                        blockResolution = true;
6737                        break;
6738                    } else {
6739                        // we have a locally installed instant application; skip resolution
6740                        // but acknowledge there's an instant application available
6741                        if (DEBUG_INSTANT) {
6742                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6743                        }
6744                        localInstantApp = info;
6745                        break;
6746                    }
6747                }
6748            }
6749        }
6750        // no app installed, let's see if one's available
6751        AuxiliaryResolveInfo auxiliaryResponse = null;
6752        if (!blockResolution) {
6753            if (localInstantApp == null) {
6754                // we don't have an instant app locally, resolve externally
6755                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6756                final InstantAppRequest requestObject = new InstantAppRequest(
6757                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6758                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6759                        resolveForStart);
6760                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6761                        mInstantAppResolverConnection, requestObject);
6762                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6763            } else {
6764                // we have an instant application locally, but, we can't admit that since
6765                // callers shouldn't be able to determine prior browsing. create a dummy
6766                // auxiliary response so the downstream code behaves as if there's an
6767                // instant application available externally. when it comes time to start
6768                // the instant application, we'll do the right thing.
6769                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6770                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6771                                        ai.packageName, ai.versionCode, null /* splitName */);
6772            }
6773        }
6774        if (intent.isWebIntent() && auxiliaryResponse == null) {
6775            return result;
6776        }
6777        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6778        if (ps == null
6779                || ps.getUserState().get(userId) == null
6780                || !ps.getUserState().get(userId).isEnabled(mInstantAppInstallerActivity, 0)) {
6781            return result;
6782        }
6783        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6784        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6785                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6786        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6787                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6788        // add a non-generic filter
6789        ephemeralInstaller.filter = new IntentFilter();
6790        if (intent.getAction() != null) {
6791            ephemeralInstaller.filter.addAction(intent.getAction());
6792        }
6793        if (intent.getData() != null && intent.getData().getPath() != null) {
6794            ephemeralInstaller.filter.addDataPath(
6795                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6796        }
6797        ephemeralInstaller.isInstantAppAvailable = true;
6798        // make sure this resolver is the default
6799        ephemeralInstaller.isDefault = true;
6800        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6801        if (DEBUG_INSTANT) {
6802            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6803        }
6804
6805        result.add(ephemeralInstaller);
6806        return result;
6807    }
6808
6809    private static class CrossProfileDomainInfo {
6810        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6811        ResolveInfo resolveInfo;
6812        /* Best domain verification status of the activities found in the other profile */
6813        int bestDomainVerificationStatus;
6814    }
6815
6816    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6817            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6818        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6819                sourceUserId)) {
6820            return null;
6821        }
6822        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6823                resolvedType, flags, parentUserId);
6824
6825        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6826            return null;
6827        }
6828        CrossProfileDomainInfo result = null;
6829        int size = resultTargetUser.size();
6830        for (int i = 0; i < size; i++) {
6831            ResolveInfo riTargetUser = resultTargetUser.get(i);
6832            // Intent filter verification is only for filters that specify a host. So don't return
6833            // those that handle all web uris.
6834            if (riTargetUser.handleAllWebDataURI) {
6835                continue;
6836            }
6837            String packageName = riTargetUser.activityInfo.packageName;
6838            PackageSetting ps = mSettings.mPackages.get(packageName);
6839            if (ps == null) {
6840                continue;
6841            }
6842            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6843            int status = (int)(verificationState >> 32);
6844            if (result == null) {
6845                result = new CrossProfileDomainInfo();
6846                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6847                        sourceUserId, parentUserId);
6848                result.bestDomainVerificationStatus = status;
6849            } else {
6850                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6851                        result.bestDomainVerificationStatus);
6852            }
6853        }
6854        // Don't consider matches with status NEVER across profiles.
6855        if (result != null && result.bestDomainVerificationStatus
6856                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6857            return null;
6858        }
6859        return result;
6860    }
6861
6862    /**
6863     * Verification statuses are ordered from the worse to the best, except for
6864     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6865     */
6866    private int bestDomainVerificationStatus(int status1, int status2) {
6867        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6868            return status2;
6869        }
6870        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6871            return status1;
6872        }
6873        return (int) MathUtils.max(status1, status2);
6874    }
6875
6876    private boolean isUserEnabled(int userId) {
6877        long callingId = Binder.clearCallingIdentity();
6878        try {
6879            UserInfo userInfo = sUserManager.getUserInfo(userId);
6880            return userInfo != null && userInfo.isEnabled();
6881        } finally {
6882            Binder.restoreCallingIdentity(callingId);
6883        }
6884    }
6885
6886    /**
6887     * Filter out activities with systemUserOnly flag set, when current user is not System.
6888     *
6889     * @return filtered list
6890     */
6891    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6892        if (userId == UserHandle.USER_SYSTEM) {
6893            return resolveInfos;
6894        }
6895        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6896            ResolveInfo info = resolveInfos.get(i);
6897            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6898                resolveInfos.remove(i);
6899            }
6900        }
6901        return resolveInfos;
6902    }
6903
6904    /**
6905     * Filters out ephemeral activities.
6906     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6907     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6908     *
6909     * @param resolveInfos The pre-filtered list of resolved activities
6910     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6911     *          is performed.
6912     * @param intent
6913     * @return A filtered list of resolved activities.
6914     */
6915    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6916            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId,
6917            Intent intent) {
6918        final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled();
6919        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6920            final ResolveInfo info = resolveInfos.get(i);
6921            // remove locally resolved instant app web results when disabled
6922            if (info.isInstantAppAvailable && blockInstant) {
6923                resolveInfos.remove(i);
6924                continue;
6925            }
6926            // allow activities that are defined in the provided package
6927            if (allowDynamicSplits
6928                    && info.activityInfo != null
6929                    && info.activityInfo.splitName != null
6930                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6931                            info.activityInfo.splitName)) {
6932                if (mInstantAppInstallerActivity == null) {
6933                    if (DEBUG_INSTALL) {
6934                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6935                    }
6936                    resolveInfos.remove(i);
6937                    continue;
6938                }
6939                if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) {
6940                    resolveInfos.remove(i);
6941                    continue;
6942                }
6943                // requested activity is defined in a split that hasn't been installed yet.
6944                // add the installer to the resolve list
6945                if (DEBUG_INSTALL) {
6946                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6947                }
6948                final ResolveInfo installerInfo = new ResolveInfo(
6949                        mInstantAppInstallerInfo);
6950                final ComponentName installFailureActivity = findInstallFailureActivity(
6951                        info.activityInfo.packageName,  filterCallingUid, userId);
6952                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6953                        installFailureActivity,
6954                        info.activityInfo.packageName,
6955                        info.activityInfo.applicationInfo.versionCode,
6956                        info.activityInfo.splitName);
6957                // add a non-generic filter
6958                installerInfo.filter = new IntentFilter();
6959
6960                // This resolve info may appear in the chooser UI, so let us make it
6961                // look as the one it replaces as far as the user is concerned which
6962                // requires loading the correct label and icon for the resolve info.
6963                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6964                installerInfo.labelRes = info.resolveLabelResId();
6965                installerInfo.icon = info.resolveIconResId();
6966                installerInfo.isInstantAppAvailable = true;
6967                resolveInfos.set(i, installerInfo);
6968                continue;
6969            }
6970            // caller is a full app, don't need to apply any other filtering
6971            if (ephemeralPkgName == null) {
6972                continue;
6973            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6974                // caller is same app; don't need to apply any other filtering
6975                continue;
6976            }
6977            // allow activities that have been explicitly exposed to ephemeral apps
6978            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6979            if (!isEphemeralApp
6980                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6981                continue;
6982            }
6983            resolveInfos.remove(i);
6984        }
6985        return resolveInfos;
6986    }
6987
6988    /**
6989     * Returns the activity component that can handle install failures.
6990     * <p>By default, the instant application installer handles failures. However, an
6991     * application may want to handle failures on its own. Applications do this by
6992     * creating an activity with an intent filter that handles the action
6993     * {@link Intent#ACTION_INSTALL_FAILURE}.
6994     */
6995    private @Nullable ComponentName findInstallFailureActivity(
6996            String packageName, int filterCallingUid, int userId) {
6997        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6998        failureActivityIntent.setPackage(packageName);
6999        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7000        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7001                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7002                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7003        final int NR = result.size();
7004        if (NR > 0) {
7005            for (int i = 0; i < NR; i++) {
7006                final ResolveInfo info = result.get(i);
7007                if (info.activityInfo.splitName != null) {
7008                    continue;
7009                }
7010                return new ComponentName(packageName, info.activityInfo.name);
7011            }
7012        }
7013        return null;
7014    }
7015
7016    /**
7017     * @param resolveInfos list of resolve infos in descending priority order
7018     * @return if the list contains a resolve info with non-negative priority
7019     */
7020    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7021        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7022    }
7023
7024    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7025            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7026            int userId) {
7027        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7028
7029        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7030            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7031                    candidates.size());
7032        }
7033
7034        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7035        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7036        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7037        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7038        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7039        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7040
7041        synchronized (mPackages) {
7042            final int count = candidates.size();
7043            // First, try to use linked apps. Partition the candidates into four lists:
7044            // one for the final results, one for the "do not use ever", one for "undefined status"
7045            // and finally one for "browser app type".
7046            for (int n=0; n<count; n++) {
7047                ResolveInfo info = candidates.get(n);
7048                String packageName = info.activityInfo.packageName;
7049                PackageSetting ps = mSettings.mPackages.get(packageName);
7050                if (ps != null) {
7051                    // Add to the special match all list (Browser use case)
7052                    if (info.handleAllWebDataURI) {
7053                        matchAllList.add(info);
7054                        continue;
7055                    }
7056                    // Try to get the status from User settings first
7057                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7058                    int status = (int)(packedStatus >> 32);
7059                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7060                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7061                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7062                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7063                                    + " : linkgen=" + linkGeneration);
7064                        }
7065                        // Use link-enabled generation as preferredOrder, i.e.
7066                        // prefer newly-enabled over earlier-enabled.
7067                        info.preferredOrder = linkGeneration;
7068                        alwaysList.add(info);
7069                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7070                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7071                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7072                        }
7073                        neverList.add(info);
7074                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7075                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7076                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7077                        }
7078                        alwaysAskList.add(info);
7079                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7080                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7081                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7082                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7083                        }
7084                        undefinedList.add(info);
7085                    }
7086                }
7087            }
7088
7089            // We'll want to include browser possibilities in a few cases
7090            boolean includeBrowser = false;
7091
7092            // First try to add the "always" resolution(s) for the current user, if any
7093            if (alwaysList.size() > 0) {
7094                result.addAll(alwaysList);
7095            } else {
7096                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7097                result.addAll(undefinedList);
7098                // Maybe add one for the other profile.
7099                if (xpDomainInfo != null && (
7100                        xpDomainInfo.bestDomainVerificationStatus
7101                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7102                    result.add(xpDomainInfo.resolveInfo);
7103                }
7104                includeBrowser = true;
7105            }
7106
7107            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7108            // If there were 'always' entries their preferred order has been set, so we also
7109            // back that off to make the alternatives equivalent
7110            if (alwaysAskList.size() > 0) {
7111                for (ResolveInfo i : result) {
7112                    i.preferredOrder = 0;
7113                }
7114                result.addAll(alwaysAskList);
7115                includeBrowser = true;
7116            }
7117
7118            if (includeBrowser) {
7119                // Also add browsers (all of them or only the default one)
7120                if (DEBUG_DOMAIN_VERIFICATION) {
7121                    Slog.v(TAG, "   ...including browsers in candidate set");
7122                }
7123                if ((matchFlags & MATCH_ALL) != 0) {
7124                    result.addAll(matchAllList);
7125                } else {
7126                    // Browser/generic handling case.  If there's a default browser, go straight
7127                    // to that (but only if there is no other higher-priority match).
7128                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7129                    int maxMatchPrio = 0;
7130                    ResolveInfo defaultBrowserMatch = null;
7131                    final int numCandidates = matchAllList.size();
7132                    for (int n = 0; n < numCandidates; n++) {
7133                        ResolveInfo info = matchAllList.get(n);
7134                        // track the highest overall match priority...
7135                        if (info.priority > maxMatchPrio) {
7136                            maxMatchPrio = info.priority;
7137                        }
7138                        // ...and the highest-priority default browser match
7139                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7140                            if (defaultBrowserMatch == null
7141                                    || (defaultBrowserMatch.priority < info.priority)) {
7142                                if (debug) {
7143                                    Slog.v(TAG, "Considering default browser match " + info);
7144                                }
7145                                defaultBrowserMatch = info;
7146                            }
7147                        }
7148                    }
7149                    if (defaultBrowserMatch != null
7150                            && defaultBrowserMatch.priority >= maxMatchPrio
7151                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7152                    {
7153                        if (debug) {
7154                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7155                        }
7156                        result.add(defaultBrowserMatch);
7157                    } else {
7158                        result.addAll(matchAllList);
7159                    }
7160                }
7161
7162                // If there is nothing selected, add all candidates and remove the ones that the user
7163                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7164                if (result.size() == 0) {
7165                    result.addAll(candidates);
7166                    result.removeAll(neverList);
7167                }
7168            }
7169        }
7170        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7171            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7172                    result.size());
7173            for (ResolveInfo info : result) {
7174                Slog.v(TAG, "  + " + info.activityInfo);
7175            }
7176        }
7177        return result;
7178    }
7179
7180    // Returns a packed value as a long:
7181    //
7182    // high 'int'-sized word: link status: undefined/ask/never/always.
7183    // low 'int'-sized word: relative priority among 'always' results.
7184    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7185        long result = ps.getDomainVerificationStatusForUser(userId);
7186        // if none available, get the master status
7187        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7188            if (ps.getIntentFilterVerificationInfo() != null) {
7189                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7190            }
7191        }
7192        return result;
7193    }
7194
7195    private ResolveInfo querySkipCurrentProfileIntents(
7196            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7197            int flags, int sourceUserId) {
7198        if (matchingFilters != null) {
7199            int size = matchingFilters.size();
7200            for (int i = 0; i < size; i ++) {
7201                CrossProfileIntentFilter filter = matchingFilters.get(i);
7202                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7203                    // Checking if there are activities in the target user that can handle the
7204                    // intent.
7205                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7206                            resolvedType, flags, sourceUserId);
7207                    if (resolveInfo != null) {
7208                        return resolveInfo;
7209                    }
7210                }
7211            }
7212        }
7213        return null;
7214    }
7215
7216    // Return matching ResolveInfo in target user if any.
7217    private ResolveInfo queryCrossProfileIntents(
7218            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7219            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7220        if (matchingFilters != null) {
7221            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7222            // match the same intent. For performance reasons, it is better not to
7223            // run queryIntent twice for the same userId
7224            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7225            int size = matchingFilters.size();
7226            for (int i = 0; i < size; i++) {
7227                CrossProfileIntentFilter filter = matchingFilters.get(i);
7228                int targetUserId = filter.getTargetUserId();
7229                boolean skipCurrentProfile =
7230                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7231                boolean skipCurrentProfileIfNoMatchFound =
7232                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7233                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7234                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7235                    // Checking if there are activities in the target user that can handle the
7236                    // intent.
7237                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7238                            resolvedType, flags, sourceUserId);
7239                    if (resolveInfo != null) return resolveInfo;
7240                    alreadyTriedUserIds.put(targetUserId, true);
7241                }
7242            }
7243        }
7244        return null;
7245    }
7246
7247    /**
7248     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7249     * will forward the intent to the filter's target user.
7250     * Otherwise, returns null.
7251     */
7252    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7253            String resolvedType, int flags, int sourceUserId) {
7254        int targetUserId = filter.getTargetUserId();
7255        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7256                resolvedType, flags, targetUserId);
7257        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7258            // If all the matches in the target profile are suspended, return null.
7259            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7260                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7261                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7262                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7263                            targetUserId);
7264                }
7265            }
7266        }
7267        return null;
7268    }
7269
7270    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7271            int sourceUserId, int targetUserId) {
7272        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7273        long ident = Binder.clearCallingIdentity();
7274        boolean targetIsProfile;
7275        try {
7276            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7277        } finally {
7278            Binder.restoreCallingIdentity(ident);
7279        }
7280        String className;
7281        if (targetIsProfile) {
7282            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7283        } else {
7284            className = FORWARD_INTENT_TO_PARENT;
7285        }
7286        ComponentName forwardingActivityComponentName = new ComponentName(
7287                mAndroidApplication.packageName, className);
7288        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7289                sourceUserId);
7290        if (!targetIsProfile) {
7291            forwardingActivityInfo.showUserIcon = targetUserId;
7292            forwardingResolveInfo.noResourceId = true;
7293        }
7294        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7295        forwardingResolveInfo.priority = 0;
7296        forwardingResolveInfo.preferredOrder = 0;
7297        forwardingResolveInfo.match = 0;
7298        forwardingResolveInfo.isDefault = true;
7299        forwardingResolveInfo.filter = filter;
7300        forwardingResolveInfo.targetUserId = targetUserId;
7301        return forwardingResolveInfo;
7302    }
7303
7304    @Override
7305    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7306            Intent[] specifics, String[] specificTypes, Intent intent,
7307            String resolvedType, int flags, int userId) {
7308        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7309                specificTypes, intent, resolvedType, flags, userId));
7310    }
7311
7312    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7313            Intent[] specifics, String[] specificTypes, Intent intent,
7314            String resolvedType, int flags, int userId) {
7315        if (!sUserManager.exists(userId)) return Collections.emptyList();
7316        final int callingUid = Binder.getCallingUid();
7317        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7318                false /*includeInstantApps*/);
7319        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7320                false /*requireFullPermission*/, false /*checkShell*/,
7321                "query intent activity options");
7322        final String resultsAction = intent.getAction();
7323
7324        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7325                | PackageManager.GET_RESOLVED_FILTER, userId);
7326
7327        if (DEBUG_INTENT_MATCHING) {
7328            Log.v(TAG, "Query " + intent + ": " + results);
7329        }
7330
7331        int specificsPos = 0;
7332        int N;
7333
7334        // todo: note that the algorithm used here is O(N^2).  This
7335        // isn't a problem in our current environment, but if we start running
7336        // into situations where we have more than 5 or 10 matches then this
7337        // should probably be changed to something smarter...
7338
7339        // First we go through and resolve each of the specific items
7340        // that were supplied, taking care of removing any corresponding
7341        // duplicate items in the generic resolve list.
7342        if (specifics != null) {
7343            for (int i=0; i<specifics.length; i++) {
7344                final Intent sintent = specifics[i];
7345                if (sintent == null) {
7346                    continue;
7347                }
7348
7349                if (DEBUG_INTENT_MATCHING) {
7350                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7351                }
7352
7353                String action = sintent.getAction();
7354                if (resultsAction != null && resultsAction.equals(action)) {
7355                    // If this action was explicitly requested, then don't
7356                    // remove things that have it.
7357                    action = null;
7358                }
7359
7360                ResolveInfo ri = null;
7361                ActivityInfo ai = null;
7362
7363                ComponentName comp = sintent.getComponent();
7364                if (comp == null) {
7365                    ri = resolveIntent(
7366                        sintent,
7367                        specificTypes != null ? specificTypes[i] : null,
7368                            flags, userId);
7369                    if (ri == null) {
7370                        continue;
7371                    }
7372                    if (ri == mResolveInfo) {
7373                        // ACK!  Must do something better with this.
7374                    }
7375                    ai = ri.activityInfo;
7376                    comp = new ComponentName(ai.applicationInfo.packageName,
7377                            ai.name);
7378                } else {
7379                    ai = getActivityInfo(comp, flags, userId);
7380                    if (ai == null) {
7381                        continue;
7382                    }
7383                }
7384
7385                // Look for any generic query activities that are duplicates
7386                // of this specific one, and remove them from the results.
7387                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7388                N = results.size();
7389                int j;
7390                for (j=specificsPos; j<N; j++) {
7391                    ResolveInfo sri = results.get(j);
7392                    if ((sri.activityInfo.name.equals(comp.getClassName())
7393                            && sri.activityInfo.applicationInfo.packageName.equals(
7394                                    comp.getPackageName()))
7395                        || (action != null && sri.filter.matchAction(action))) {
7396                        results.remove(j);
7397                        if (DEBUG_INTENT_MATCHING) Log.v(
7398                            TAG, "Removing duplicate item from " + j
7399                            + " due to specific " + specificsPos);
7400                        if (ri == null) {
7401                            ri = sri;
7402                        }
7403                        j--;
7404                        N--;
7405                    }
7406                }
7407
7408                // Add this specific item to its proper place.
7409                if (ri == null) {
7410                    ri = new ResolveInfo();
7411                    ri.activityInfo = ai;
7412                }
7413                results.add(specificsPos, ri);
7414                ri.specificIndex = i;
7415                specificsPos++;
7416            }
7417        }
7418
7419        // Now we go through the remaining generic results and remove any
7420        // duplicate actions that are found here.
7421        N = results.size();
7422        for (int i=specificsPos; i<N-1; i++) {
7423            final ResolveInfo rii = results.get(i);
7424            if (rii.filter == null) {
7425                continue;
7426            }
7427
7428            // Iterate over all of the actions of this result's intent
7429            // filter...  typically this should be just one.
7430            final Iterator<String> it = rii.filter.actionsIterator();
7431            if (it == null) {
7432                continue;
7433            }
7434            while (it.hasNext()) {
7435                final String action = it.next();
7436                if (resultsAction != null && resultsAction.equals(action)) {
7437                    // If this action was explicitly requested, then don't
7438                    // remove things that have it.
7439                    continue;
7440                }
7441                for (int j=i+1; j<N; j++) {
7442                    final ResolveInfo rij = results.get(j);
7443                    if (rij.filter != null && rij.filter.hasAction(action)) {
7444                        results.remove(j);
7445                        if (DEBUG_INTENT_MATCHING) Log.v(
7446                            TAG, "Removing duplicate item from " + j
7447                            + " due to action " + action + " at " + i);
7448                        j--;
7449                        N--;
7450                    }
7451                }
7452            }
7453
7454            // If the caller didn't request filter information, drop it now
7455            // so we don't have to marshall/unmarshall it.
7456            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7457                rii.filter = null;
7458            }
7459        }
7460
7461        // Filter out the caller activity if so requested.
7462        if (caller != null) {
7463            N = results.size();
7464            for (int i=0; i<N; i++) {
7465                ActivityInfo ainfo = results.get(i).activityInfo;
7466                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7467                        && caller.getClassName().equals(ainfo.name)) {
7468                    results.remove(i);
7469                    break;
7470                }
7471            }
7472        }
7473
7474        // If the caller didn't request filter information,
7475        // drop them now so we don't have to
7476        // marshall/unmarshall it.
7477        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7478            N = results.size();
7479            for (int i=0; i<N; i++) {
7480                results.get(i).filter = null;
7481            }
7482        }
7483
7484        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7485        return results;
7486    }
7487
7488    @Override
7489    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7490            String resolvedType, int flags, int userId) {
7491        return new ParceledListSlice<>(
7492                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7493                        false /*allowDynamicSplits*/));
7494    }
7495
7496    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7497            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7498        if (!sUserManager.exists(userId)) return Collections.emptyList();
7499        final int callingUid = Binder.getCallingUid();
7500        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7501                false /*requireFullPermission*/, false /*checkShell*/,
7502                "query intent receivers");
7503        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7504        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7505                false /*includeInstantApps*/);
7506        ComponentName comp = intent.getComponent();
7507        if (comp == null) {
7508            if (intent.getSelector() != null) {
7509                intent = intent.getSelector();
7510                comp = intent.getComponent();
7511            }
7512        }
7513        if (comp != null) {
7514            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7515            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7516            if (ai != null) {
7517                // When specifying an explicit component, we prevent the activity from being
7518                // used when either 1) the calling package is normal and the activity is within
7519                // an instant application or 2) the calling package is ephemeral and the
7520                // activity is not visible to instant applications.
7521                final boolean matchInstantApp =
7522                        (flags & PackageManager.MATCH_INSTANT) != 0;
7523                final boolean matchVisibleToInstantAppOnly =
7524                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7525                final boolean matchExplicitlyVisibleOnly =
7526                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7527                final boolean isCallerInstantApp =
7528                        instantAppPkgName != null;
7529                final boolean isTargetSameInstantApp =
7530                        comp.getPackageName().equals(instantAppPkgName);
7531                final boolean isTargetInstantApp =
7532                        (ai.applicationInfo.privateFlags
7533                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7534                final boolean isTargetVisibleToInstantApp =
7535                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7536                final boolean isTargetExplicitlyVisibleToInstantApp =
7537                        isTargetVisibleToInstantApp
7538                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7539                final boolean isTargetHiddenFromInstantApp =
7540                        !isTargetVisibleToInstantApp
7541                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7542                final boolean blockResolution =
7543                        !isTargetSameInstantApp
7544                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7545                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7546                                        && isTargetHiddenFromInstantApp));
7547                if (!blockResolution) {
7548                    ResolveInfo ri = new ResolveInfo();
7549                    ri.activityInfo = ai;
7550                    list.add(ri);
7551                }
7552            }
7553            return applyPostResolutionFilter(
7554                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7555        }
7556
7557        // reader
7558        synchronized (mPackages) {
7559            String pkgName = intent.getPackage();
7560            if (pkgName == null) {
7561                final List<ResolveInfo> result =
7562                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7563                return applyPostResolutionFilter(
7564                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7565            }
7566            final PackageParser.Package pkg = mPackages.get(pkgName);
7567            if (pkg != null) {
7568                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7569                        intent, resolvedType, flags, pkg.receivers, userId);
7570                return applyPostResolutionFilter(
7571                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7572            }
7573            return Collections.emptyList();
7574        }
7575    }
7576
7577    @Override
7578    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7579        final int callingUid = Binder.getCallingUid();
7580        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7581    }
7582
7583    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7584            int userId, int callingUid) {
7585        if (!sUserManager.exists(userId)) return null;
7586        flags = updateFlagsForResolve(
7587                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7588        List<ResolveInfo> query = queryIntentServicesInternal(
7589                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7590        if (query != null) {
7591            if (query.size() >= 1) {
7592                // If there is more than one service with the same priority,
7593                // just arbitrarily pick the first one.
7594                return query.get(0);
7595            }
7596        }
7597        return null;
7598    }
7599
7600    @Override
7601    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7602            String resolvedType, int flags, int userId) {
7603        final int callingUid = Binder.getCallingUid();
7604        return new ParceledListSlice<>(queryIntentServicesInternal(
7605                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7606    }
7607
7608    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7609            String resolvedType, int flags, int userId, int callingUid,
7610            boolean includeInstantApps) {
7611        if (!sUserManager.exists(userId)) return Collections.emptyList();
7612        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7613                false /*requireFullPermission*/, false /*checkShell*/,
7614                "query intent receivers");
7615        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7616        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7617        ComponentName comp = intent.getComponent();
7618        if (comp == null) {
7619            if (intent.getSelector() != null) {
7620                intent = intent.getSelector();
7621                comp = intent.getComponent();
7622            }
7623        }
7624        if (comp != null) {
7625            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7626            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7627            if (si != null) {
7628                // When specifying an explicit component, we prevent the service from being
7629                // used when either 1) the service is in an instant application and the
7630                // caller is not the same instant application or 2) the calling package is
7631                // ephemeral and the activity is not visible to ephemeral applications.
7632                final boolean matchInstantApp =
7633                        (flags & PackageManager.MATCH_INSTANT) != 0;
7634                final boolean matchVisibleToInstantAppOnly =
7635                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7636                final boolean isCallerInstantApp =
7637                        instantAppPkgName != null;
7638                final boolean isTargetSameInstantApp =
7639                        comp.getPackageName().equals(instantAppPkgName);
7640                final boolean isTargetInstantApp =
7641                        (si.applicationInfo.privateFlags
7642                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7643                final boolean isTargetHiddenFromInstantApp =
7644                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7645                final boolean blockResolution =
7646                        !isTargetSameInstantApp
7647                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7648                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7649                                        && isTargetHiddenFromInstantApp));
7650                if (!blockResolution) {
7651                    final ResolveInfo ri = new ResolveInfo();
7652                    ri.serviceInfo = si;
7653                    list.add(ri);
7654                }
7655            }
7656            return list;
7657        }
7658
7659        // reader
7660        synchronized (mPackages) {
7661            String pkgName = intent.getPackage();
7662            if (pkgName == null) {
7663                return applyPostServiceResolutionFilter(
7664                        mServices.queryIntent(intent, resolvedType, flags, userId),
7665                        instantAppPkgName);
7666            }
7667            final PackageParser.Package pkg = mPackages.get(pkgName);
7668            if (pkg != null) {
7669                return applyPostServiceResolutionFilter(
7670                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7671                                userId),
7672                        instantAppPkgName);
7673            }
7674            return Collections.emptyList();
7675        }
7676    }
7677
7678    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7679            String instantAppPkgName) {
7680        if (instantAppPkgName == null) {
7681            return resolveInfos;
7682        }
7683        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7684            final ResolveInfo info = resolveInfos.get(i);
7685            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7686            // allow services that are defined in the provided package
7687            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7688                if (info.serviceInfo.splitName != null
7689                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7690                                info.serviceInfo.splitName)) {
7691                    // requested service is defined in a split that hasn't been installed yet.
7692                    // add the installer to the resolve list
7693                    if (DEBUG_INSTANT) {
7694                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7695                    }
7696                    final ResolveInfo installerInfo = new ResolveInfo(
7697                            mInstantAppInstallerInfo);
7698                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7699                            null /* installFailureActivity */,
7700                            info.serviceInfo.packageName,
7701                            info.serviceInfo.applicationInfo.versionCode,
7702                            info.serviceInfo.splitName);
7703                    // add a non-generic filter
7704                    installerInfo.filter = new IntentFilter();
7705                    // load resources from the correct package
7706                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7707                    resolveInfos.set(i, installerInfo);
7708                }
7709                continue;
7710            }
7711            // allow services that have been explicitly exposed to ephemeral apps
7712            if (!isEphemeralApp
7713                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7714                continue;
7715            }
7716            resolveInfos.remove(i);
7717        }
7718        return resolveInfos;
7719    }
7720
7721    @Override
7722    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7723            String resolvedType, int flags, int userId) {
7724        return new ParceledListSlice<>(
7725                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7726    }
7727
7728    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7729            Intent intent, String resolvedType, int flags, int userId) {
7730        if (!sUserManager.exists(userId)) return Collections.emptyList();
7731        final int callingUid = Binder.getCallingUid();
7732        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7733        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7734                false /*includeInstantApps*/);
7735        ComponentName comp = intent.getComponent();
7736        if (comp == null) {
7737            if (intent.getSelector() != null) {
7738                intent = intent.getSelector();
7739                comp = intent.getComponent();
7740            }
7741        }
7742        if (comp != null) {
7743            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7744            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7745            if (pi != null) {
7746                // When specifying an explicit component, we prevent the provider from being
7747                // used when either 1) the provider is in an instant application and the
7748                // caller is not the same instant application or 2) the calling package is an
7749                // instant application and the provider is not visible to instant applications.
7750                final boolean matchInstantApp =
7751                        (flags & PackageManager.MATCH_INSTANT) != 0;
7752                final boolean matchVisibleToInstantAppOnly =
7753                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7754                final boolean isCallerInstantApp =
7755                        instantAppPkgName != null;
7756                final boolean isTargetSameInstantApp =
7757                        comp.getPackageName().equals(instantAppPkgName);
7758                final boolean isTargetInstantApp =
7759                        (pi.applicationInfo.privateFlags
7760                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7761                final boolean isTargetHiddenFromInstantApp =
7762                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7763                final boolean blockResolution =
7764                        !isTargetSameInstantApp
7765                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7766                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7767                                        && isTargetHiddenFromInstantApp));
7768                if (!blockResolution) {
7769                    final ResolveInfo ri = new ResolveInfo();
7770                    ri.providerInfo = pi;
7771                    list.add(ri);
7772                }
7773            }
7774            return list;
7775        }
7776
7777        // reader
7778        synchronized (mPackages) {
7779            String pkgName = intent.getPackage();
7780            if (pkgName == null) {
7781                return applyPostContentProviderResolutionFilter(
7782                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7783                        instantAppPkgName);
7784            }
7785            final PackageParser.Package pkg = mPackages.get(pkgName);
7786            if (pkg != null) {
7787                return applyPostContentProviderResolutionFilter(
7788                        mProviders.queryIntentForPackage(
7789                        intent, resolvedType, flags, pkg.providers, userId),
7790                        instantAppPkgName);
7791            }
7792            return Collections.emptyList();
7793        }
7794    }
7795
7796    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7797            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7798        if (instantAppPkgName == null) {
7799            return resolveInfos;
7800        }
7801        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7802            final ResolveInfo info = resolveInfos.get(i);
7803            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7804            // allow providers that are defined in the provided package
7805            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7806                if (info.providerInfo.splitName != null
7807                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7808                                info.providerInfo.splitName)) {
7809                    // requested provider is defined in a split that hasn't been installed yet.
7810                    // add the installer to the resolve list
7811                    if (DEBUG_INSTANT) {
7812                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7813                    }
7814                    final ResolveInfo installerInfo = new ResolveInfo(
7815                            mInstantAppInstallerInfo);
7816                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7817                            null /*failureActivity*/,
7818                            info.providerInfo.packageName,
7819                            info.providerInfo.applicationInfo.versionCode,
7820                            info.providerInfo.splitName);
7821                    // add a non-generic filter
7822                    installerInfo.filter = new IntentFilter();
7823                    // load resources from the correct package
7824                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7825                    resolveInfos.set(i, installerInfo);
7826                }
7827                continue;
7828            }
7829            // allow providers that have been explicitly exposed to instant applications
7830            if (!isEphemeralApp
7831                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7832                continue;
7833            }
7834            resolveInfos.remove(i);
7835        }
7836        return resolveInfos;
7837    }
7838
7839    @Override
7840    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7841        final int callingUid = Binder.getCallingUid();
7842        if (getInstantAppPackageName(callingUid) != null) {
7843            return ParceledListSlice.emptyList();
7844        }
7845        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7846        flags = updateFlagsForPackage(flags, userId, null);
7847        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7848        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7849                true /* requireFullPermission */, false /* checkShell */,
7850                "get installed packages");
7851
7852        // writer
7853        synchronized (mPackages) {
7854            ArrayList<PackageInfo> list;
7855            if (listUninstalled) {
7856                list = new ArrayList<>(mSettings.mPackages.size());
7857                for (PackageSetting ps : mSettings.mPackages.values()) {
7858                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7859                        continue;
7860                    }
7861                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7862                        continue;
7863                    }
7864                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7865                    if (pi != null) {
7866                        list.add(pi);
7867                    }
7868                }
7869            } else {
7870                list = new ArrayList<>(mPackages.size());
7871                for (PackageParser.Package p : mPackages.values()) {
7872                    final PackageSetting ps = (PackageSetting) p.mExtras;
7873                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7874                        continue;
7875                    }
7876                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7877                        continue;
7878                    }
7879                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7880                            p.mExtras, flags, userId);
7881                    if (pi != null) {
7882                        list.add(pi);
7883                    }
7884                }
7885            }
7886
7887            return new ParceledListSlice<>(list);
7888        }
7889    }
7890
7891    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7892            String[] permissions, boolean[] tmp, int flags, int userId) {
7893        int numMatch = 0;
7894        final PermissionsState permissionsState = ps.getPermissionsState();
7895        for (int i=0; i<permissions.length; i++) {
7896            final String permission = permissions[i];
7897            if (permissionsState.hasPermission(permission, userId)) {
7898                tmp[i] = true;
7899                numMatch++;
7900            } else {
7901                tmp[i] = false;
7902            }
7903        }
7904        if (numMatch == 0) {
7905            return;
7906        }
7907        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7908
7909        // The above might return null in cases of uninstalled apps or install-state
7910        // skew across users/profiles.
7911        if (pi != null) {
7912            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7913                if (numMatch == permissions.length) {
7914                    pi.requestedPermissions = permissions;
7915                } else {
7916                    pi.requestedPermissions = new String[numMatch];
7917                    numMatch = 0;
7918                    for (int i=0; i<permissions.length; i++) {
7919                        if (tmp[i]) {
7920                            pi.requestedPermissions[numMatch] = permissions[i];
7921                            numMatch++;
7922                        }
7923                    }
7924                }
7925            }
7926            list.add(pi);
7927        }
7928    }
7929
7930    @Override
7931    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7932            String[] permissions, int flags, int userId) {
7933        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7934        flags = updateFlagsForPackage(flags, userId, permissions);
7935        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7936                true /* requireFullPermission */, false /* checkShell */,
7937                "get packages holding permissions");
7938        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7939
7940        // writer
7941        synchronized (mPackages) {
7942            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7943            boolean[] tmpBools = new boolean[permissions.length];
7944            if (listUninstalled) {
7945                for (PackageSetting ps : mSettings.mPackages.values()) {
7946                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7947                            userId);
7948                }
7949            } else {
7950                for (PackageParser.Package pkg : mPackages.values()) {
7951                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7952                    if (ps != null) {
7953                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7954                                userId);
7955                    }
7956                }
7957            }
7958
7959            return new ParceledListSlice<PackageInfo>(list);
7960        }
7961    }
7962
7963    @Override
7964    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7965        final int callingUid = Binder.getCallingUid();
7966        if (getInstantAppPackageName(callingUid) != null) {
7967            return ParceledListSlice.emptyList();
7968        }
7969        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7970        flags = updateFlagsForApplication(flags, userId, null);
7971        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7972
7973        // writer
7974        synchronized (mPackages) {
7975            ArrayList<ApplicationInfo> list;
7976            if (listUninstalled) {
7977                list = new ArrayList<>(mSettings.mPackages.size());
7978                for (PackageSetting ps : mSettings.mPackages.values()) {
7979                    ApplicationInfo ai;
7980                    int effectiveFlags = flags;
7981                    if (ps.isSystem()) {
7982                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7983                    }
7984                    if (ps.pkg != null) {
7985                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7986                            continue;
7987                        }
7988                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7989                            continue;
7990                        }
7991                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7992                                ps.readUserState(userId), userId);
7993                        if (ai != null) {
7994                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7995                        }
7996                    } else {
7997                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7998                        // and already converts to externally visible package name
7999                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8000                                callingUid, effectiveFlags, userId);
8001                    }
8002                    if (ai != null) {
8003                        list.add(ai);
8004                    }
8005                }
8006            } else {
8007                list = new ArrayList<>(mPackages.size());
8008                for (PackageParser.Package p : mPackages.values()) {
8009                    if (p.mExtras != null) {
8010                        PackageSetting ps = (PackageSetting) p.mExtras;
8011                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8012                            continue;
8013                        }
8014                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8015                            continue;
8016                        }
8017                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8018                                ps.readUserState(userId), userId);
8019                        if (ai != null) {
8020                            ai.packageName = resolveExternalPackageNameLPr(p);
8021                            list.add(ai);
8022                        }
8023                    }
8024                }
8025            }
8026
8027            return new ParceledListSlice<>(list);
8028        }
8029    }
8030
8031    @Override
8032    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8033        if (HIDE_EPHEMERAL_APIS) {
8034            return null;
8035        }
8036        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8037            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8038                    "getEphemeralApplications");
8039        }
8040        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8041                true /* requireFullPermission */, false /* checkShell */,
8042                "getEphemeralApplications");
8043        synchronized (mPackages) {
8044            List<InstantAppInfo> instantApps = mInstantAppRegistry
8045                    .getInstantAppsLPr(userId);
8046            if (instantApps != null) {
8047                return new ParceledListSlice<>(instantApps);
8048            }
8049        }
8050        return null;
8051    }
8052
8053    @Override
8054    public boolean isInstantApp(String packageName, int userId) {
8055        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8056                true /* requireFullPermission */, false /* checkShell */,
8057                "isInstantApp");
8058        if (HIDE_EPHEMERAL_APIS) {
8059            return false;
8060        }
8061
8062        synchronized (mPackages) {
8063            int callingUid = Binder.getCallingUid();
8064            if (Process.isIsolated(callingUid)) {
8065                callingUid = mIsolatedOwners.get(callingUid);
8066            }
8067            final PackageSetting ps = mSettings.mPackages.get(packageName);
8068            PackageParser.Package pkg = mPackages.get(packageName);
8069            final boolean returnAllowed =
8070                    ps != null
8071                    && (isCallerSameApp(packageName, callingUid)
8072                            || canViewInstantApps(callingUid, userId)
8073                            || mInstantAppRegistry.isInstantAccessGranted(
8074                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8075            if (returnAllowed) {
8076                return ps.getInstantApp(userId);
8077            }
8078        }
8079        return false;
8080    }
8081
8082    @Override
8083    public byte[] getInstantAppCookie(String packageName, int userId) {
8084        if (HIDE_EPHEMERAL_APIS) {
8085            return null;
8086        }
8087
8088        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8089                true /* requireFullPermission */, false /* checkShell */,
8090                "getInstantAppCookie");
8091        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8092            return null;
8093        }
8094        synchronized (mPackages) {
8095            return mInstantAppRegistry.getInstantAppCookieLPw(
8096                    packageName, userId);
8097        }
8098    }
8099
8100    @Override
8101    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8102        if (HIDE_EPHEMERAL_APIS) {
8103            return true;
8104        }
8105
8106        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8107                true /* requireFullPermission */, true /* checkShell */,
8108                "setInstantAppCookie");
8109        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8110            return false;
8111        }
8112        synchronized (mPackages) {
8113            return mInstantAppRegistry.setInstantAppCookieLPw(
8114                    packageName, cookie, userId);
8115        }
8116    }
8117
8118    @Override
8119    public Bitmap getInstantAppIcon(String packageName, int userId) {
8120        if (HIDE_EPHEMERAL_APIS) {
8121            return null;
8122        }
8123
8124        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8125            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8126                    "getInstantAppIcon");
8127        }
8128        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8129                true /* requireFullPermission */, false /* checkShell */,
8130                "getInstantAppIcon");
8131
8132        synchronized (mPackages) {
8133            return mInstantAppRegistry.getInstantAppIconLPw(
8134                    packageName, userId);
8135        }
8136    }
8137
8138    private boolean isCallerSameApp(String packageName, int uid) {
8139        PackageParser.Package pkg = mPackages.get(packageName);
8140        return pkg != null
8141                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8142    }
8143
8144    @Override
8145    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8146        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8147            return ParceledListSlice.emptyList();
8148        }
8149        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8150    }
8151
8152    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8153        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8154
8155        // reader
8156        synchronized (mPackages) {
8157            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8158            final int userId = UserHandle.getCallingUserId();
8159            while (i.hasNext()) {
8160                final PackageParser.Package p = i.next();
8161                if (p.applicationInfo == null) continue;
8162
8163                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8164                        && !p.applicationInfo.isDirectBootAware();
8165                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8166                        && p.applicationInfo.isDirectBootAware();
8167
8168                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8169                        && (!mSafeMode || isSystemApp(p))
8170                        && (matchesUnaware || matchesAware)) {
8171                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8172                    if (ps != null) {
8173                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8174                                ps.readUserState(userId), userId);
8175                        if (ai != null) {
8176                            finalList.add(ai);
8177                        }
8178                    }
8179                }
8180            }
8181        }
8182
8183        return finalList;
8184    }
8185
8186    @Override
8187    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8188        return resolveContentProviderInternal(name, flags, userId);
8189    }
8190
8191    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8192        if (!sUserManager.exists(userId)) return null;
8193        flags = updateFlagsForComponent(flags, userId, name);
8194        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8195        // reader
8196        synchronized (mPackages) {
8197            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8198            PackageSetting ps = provider != null
8199                    ? mSettings.mPackages.get(provider.owner.packageName)
8200                    : null;
8201            if (ps != null) {
8202                final boolean isInstantApp = ps.getInstantApp(userId);
8203                // normal application; filter out instant application provider
8204                if (instantAppPkgName == null && isInstantApp) {
8205                    return null;
8206                }
8207                // instant application; filter out other instant applications
8208                if (instantAppPkgName != null
8209                        && isInstantApp
8210                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8211                    return null;
8212                }
8213                // instant application; filter out non-exposed provider
8214                if (instantAppPkgName != null
8215                        && !isInstantApp
8216                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8217                    return null;
8218                }
8219                // provider not enabled
8220                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8221                    return null;
8222                }
8223                return PackageParser.generateProviderInfo(
8224                        provider, flags, ps.readUserState(userId), userId);
8225            }
8226            return null;
8227        }
8228    }
8229
8230    /**
8231     * @deprecated
8232     */
8233    @Deprecated
8234    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8235        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8236            return;
8237        }
8238        // reader
8239        synchronized (mPackages) {
8240            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8241                    .entrySet().iterator();
8242            final int userId = UserHandle.getCallingUserId();
8243            while (i.hasNext()) {
8244                Map.Entry<String, PackageParser.Provider> entry = i.next();
8245                PackageParser.Provider p = entry.getValue();
8246                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8247
8248                if (ps != null && p.syncable
8249                        && (!mSafeMode || (p.info.applicationInfo.flags
8250                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8251                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8252                            ps.readUserState(userId), userId);
8253                    if (info != null) {
8254                        outNames.add(entry.getKey());
8255                        outInfo.add(info);
8256                    }
8257                }
8258            }
8259        }
8260    }
8261
8262    @Override
8263    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8264            int uid, int flags, String metaDataKey) {
8265        final int callingUid = Binder.getCallingUid();
8266        final int userId = processName != null ? UserHandle.getUserId(uid)
8267                : UserHandle.getCallingUserId();
8268        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8269        flags = updateFlagsForComponent(flags, userId, processName);
8270        ArrayList<ProviderInfo> finalList = null;
8271        // reader
8272        synchronized (mPackages) {
8273            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8274            while (i.hasNext()) {
8275                final PackageParser.Provider p = i.next();
8276                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8277                if (ps != null && p.info.authority != null
8278                        && (processName == null
8279                                || (p.info.processName.equals(processName)
8280                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8281                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8282
8283                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8284                    // parameter.
8285                    if (metaDataKey != null
8286                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8287                        continue;
8288                    }
8289                    final ComponentName component =
8290                            new ComponentName(p.info.packageName, p.info.name);
8291                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8292                        continue;
8293                    }
8294                    if (finalList == null) {
8295                        finalList = new ArrayList<ProviderInfo>(3);
8296                    }
8297                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8298                            ps.readUserState(userId), userId);
8299                    if (info != null) {
8300                        finalList.add(info);
8301                    }
8302                }
8303            }
8304        }
8305
8306        if (finalList != null) {
8307            Collections.sort(finalList, mProviderInitOrderSorter);
8308            return new ParceledListSlice<ProviderInfo>(finalList);
8309        }
8310
8311        return ParceledListSlice.emptyList();
8312    }
8313
8314    @Override
8315    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8316        // reader
8317        synchronized (mPackages) {
8318            final int callingUid = Binder.getCallingUid();
8319            final int callingUserId = UserHandle.getUserId(callingUid);
8320            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8321            if (ps == null) return null;
8322            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8323                return null;
8324            }
8325            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8326            return PackageParser.generateInstrumentationInfo(i, flags);
8327        }
8328    }
8329
8330    @Override
8331    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8332            String targetPackage, int flags) {
8333        final int callingUid = Binder.getCallingUid();
8334        final int callingUserId = UserHandle.getUserId(callingUid);
8335        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8336        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8337            return ParceledListSlice.emptyList();
8338        }
8339        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8340    }
8341
8342    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8343            int flags) {
8344        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8345
8346        // reader
8347        synchronized (mPackages) {
8348            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8349            while (i.hasNext()) {
8350                final PackageParser.Instrumentation p = i.next();
8351                if (targetPackage == null
8352                        || targetPackage.equals(p.info.targetPackage)) {
8353                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8354                            flags);
8355                    if (ii != null) {
8356                        finalList.add(ii);
8357                    }
8358                }
8359            }
8360        }
8361
8362        return finalList;
8363    }
8364
8365    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8366        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8367        try {
8368            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8369        } finally {
8370            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8371        }
8372    }
8373
8374    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8375        final File[] files = scanDir.listFiles();
8376        if (ArrayUtils.isEmpty(files)) {
8377            Log.d(TAG, "No files in app dir " + scanDir);
8378            return;
8379        }
8380
8381        if (DEBUG_PACKAGE_SCANNING) {
8382            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8383                    + " flags=0x" + Integer.toHexString(parseFlags));
8384        }
8385        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8386                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8387                mParallelPackageParserCallback)) {
8388            // Submit files for parsing in parallel
8389            int fileCount = 0;
8390            for (File file : files) {
8391                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8392                        && !PackageInstallerService.isStageName(file.getName());
8393                if (!isPackage) {
8394                    // Ignore entries which are not packages
8395                    continue;
8396                }
8397                parallelPackageParser.submit(file, parseFlags);
8398                fileCount++;
8399            }
8400
8401            // Process results one by one
8402            for (; fileCount > 0; fileCount--) {
8403                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8404                Throwable throwable = parseResult.throwable;
8405                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8406
8407                if (throwable == null) {
8408                    // TODO(toddke): move lower in the scan chain
8409                    // Static shared libraries have synthetic package names
8410                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8411                        renameStaticSharedLibraryPackage(parseResult.pkg);
8412                    }
8413                    try {
8414                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8415                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8416                                    currentTime, null);
8417                        }
8418                    } catch (PackageManagerException e) {
8419                        errorCode = e.error;
8420                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8421                    }
8422                } else if (throwable instanceof PackageParser.PackageParserException) {
8423                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8424                            throwable;
8425                    errorCode = e.error;
8426                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8427                } else {
8428                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8429                            + parseResult.scanFile, throwable);
8430                }
8431
8432                // Delete invalid userdata apps
8433                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8434                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8435                    logCriticalInfo(Log.WARN,
8436                            "Deleting invalid package at " + parseResult.scanFile);
8437                    removeCodePathLI(parseResult.scanFile);
8438                }
8439            }
8440        }
8441    }
8442
8443    public static void reportSettingsProblem(int priority, String msg) {
8444        logCriticalInfo(priority, msg);
8445    }
8446
8447    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8448            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8449        // When upgrading from pre-N MR1, verify the package time stamp using the package
8450        // directory and not the APK file.
8451        final long lastModifiedTime = mIsPreNMR1Upgrade
8452                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8453        if (ps != null && !forceCollect
8454                && ps.codePathString.equals(pkg.codePath)
8455                && ps.timeStamp == lastModifiedTime
8456                && !isCompatSignatureUpdateNeeded(pkg)
8457                && !isRecoverSignatureUpdateNeeded(pkg)) {
8458            if (ps.signatures.mSigningDetails.signatures != null
8459                    && ps.signatures.mSigningDetails.signatures.length != 0
8460                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8461                            != SignatureSchemeVersion.UNKNOWN) {
8462                // Optimization: reuse the existing cached signing data
8463                // if the package appears to be unchanged.
8464                pkg.mSigningDetails =
8465                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8466                return;
8467            }
8468
8469            Slog.w(TAG, "PackageSetting for " + ps.name
8470                    + " is missing signatures.  Collecting certs again to recover them.");
8471        } else {
8472            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8473                    (forceCollect ? " (forced)" : ""));
8474        }
8475
8476        try {
8477            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8478            PackageParser.collectCertificates(pkg, skipVerify);
8479        } catch (PackageParserException e) {
8480            throw PackageManagerException.from(e);
8481        } finally {
8482            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8483        }
8484    }
8485
8486    /**
8487     *  Traces a package scan.
8488     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8489     */
8490    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8491            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8492        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8493        try {
8494            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8495        } finally {
8496            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8497        }
8498    }
8499
8500    /**
8501     *  Scans a package and returns the newly parsed package.
8502     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8503     */
8504    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8505            long currentTime, UserHandle user) throws PackageManagerException {
8506        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8507        PackageParser pp = new PackageParser();
8508        pp.setSeparateProcesses(mSeparateProcesses);
8509        pp.setOnlyCoreApps(mOnlyCore);
8510        pp.setDisplayMetrics(mMetrics);
8511        pp.setCallback(mPackageParserCallback);
8512
8513        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8514        final PackageParser.Package pkg;
8515        try {
8516            pkg = pp.parsePackage(scanFile, parseFlags);
8517        } catch (PackageParserException e) {
8518            throw PackageManagerException.from(e);
8519        } finally {
8520            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8521        }
8522
8523        // Static shared libraries have synthetic package names
8524        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8525            renameStaticSharedLibraryPackage(pkg);
8526        }
8527
8528        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8529    }
8530
8531    /**
8532     *  Scans a package and returns the newly parsed package.
8533     *  @throws PackageManagerException on a parse error.
8534     */
8535    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8536            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8537            @Nullable UserHandle user)
8538                    throws PackageManagerException {
8539        // If the package has children and this is the first dive in the function
8540        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8541        // packages (parent and children) would be successfully scanned before the
8542        // actual scan since scanning mutates internal state and we want to atomically
8543        // install the package and its children.
8544        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8545            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8546                scanFlags |= SCAN_CHECK_ONLY;
8547            }
8548        } else {
8549            scanFlags &= ~SCAN_CHECK_ONLY;
8550        }
8551
8552        // Scan the parent
8553        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8554                scanFlags, currentTime, user);
8555
8556        // Scan the children
8557        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8558        for (int i = 0; i < childCount; i++) {
8559            PackageParser.Package childPackage = pkg.childPackages.get(i);
8560            addForInitLI(childPackage, parseFlags, scanFlags,
8561                    currentTime, user);
8562        }
8563
8564
8565        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8566            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8567        }
8568
8569        return scannedPkg;
8570    }
8571
8572    /**
8573     * Returns if full apk verification can be skipped for the whole package, including the splits.
8574     */
8575    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8576        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8577            return false;
8578        }
8579        // TODO: Allow base and splits to be verified individually.
8580        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8581            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8582                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8583                    return false;
8584                }
8585            }
8586        }
8587        return true;
8588    }
8589
8590    /**
8591     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8592     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8593     * match one in a trusted source, and should be done separately.
8594     */
8595    private boolean canSkipFullApkVerification(String apkPath) {
8596        byte[] rootHashObserved = null;
8597        try {
8598            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8599            if (rootHashObserved == null) {
8600                return false;  // APK does not contain Merkle tree root hash.
8601            }
8602            synchronized (mInstallLock) {
8603                // Returns whether the observed root hash matches what kernel has.
8604                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8605                return true;
8606            }
8607        } catch (InstallerException | IOException | DigestException |
8608                NoSuchAlgorithmException e) {
8609            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8610        }
8611        return false;
8612    }
8613
8614    /**
8615     * Adds a new package to the internal data structures during platform initialization.
8616     * <p>After adding, the package is known to the system and available for querying.
8617     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8618     * etc...], additional checks are performed. Basic verification [such as ensuring
8619     * matching signatures, checking version codes, etc...] occurs if the package is
8620     * identical to a previously known package. If the package fails a signature check,
8621     * the version installed on /data will be removed. If the version of the new package
8622     * is less than or equal than the version on /data, it will be ignored.
8623     * <p>Regardless of the package location, the results are applied to the internal
8624     * structures and the package is made available to the rest of the system.
8625     * <p>NOTE: The return value should be removed. It's the passed in package object.
8626     */
8627    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8628            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8629            @Nullable UserHandle user)
8630                    throws PackageManagerException {
8631        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8632        final String renamedPkgName;
8633        final PackageSetting disabledPkgSetting;
8634        final boolean isSystemPkgUpdated;
8635        final boolean pkgAlreadyExists;
8636        PackageSetting pkgSetting;
8637
8638        // NOTE: installPackageLI() has the same code to setup the package's
8639        // application info. This probably should be done lower in the call
8640        // stack [such as scanPackageOnly()]. However, we verify the application
8641        // info prior to that [in scanPackageNew()] and thus have to setup
8642        // the application info early.
8643        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8644        pkg.setApplicationInfoCodePath(pkg.codePath);
8645        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8646        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8647        pkg.setApplicationInfoResourcePath(pkg.codePath);
8648        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8649        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8650
8651        synchronized (mPackages) {
8652            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8653            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8654            if (realPkgName != null) {
8655                ensurePackageRenamed(pkg, renamedPkgName);
8656            }
8657            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8658            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8659            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8660            pkgAlreadyExists = pkgSetting != null;
8661            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8662            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8663            isSystemPkgUpdated = disabledPkgSetting != null;
8664
8665            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8666                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8667            }
8668
8669            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8670                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8671                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8672                    : null;
8673            if (DEBUG_PACKAGE_SCANNING
8674                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8675                    && sharedUserSetting != null) {
8676                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8677                        + " (uid=" + sharedUserSetting.userId + "):"
8678                        + " packages=" + sharedUserSetting.packages);
8679            }
8680
8681            if (scanSystemPartition) {
8682                // Potentially prune child packages. If the application on the /system
8683                // partition has been updated via OTA, but, is still disabled by a
8684                // version on /data, cycle through all of its children packages and
8685                // remove children that are no longer defined.
8686                if (isSystemPkgUpdated) {
8687                    final int scannedChildCount = (pkg.childPackages != null)
8688                            ? pkg.childPackages.size() : 0;
8689                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8690                            ? disabledPkgSetting.childPackageNames.size() : 0;
8691                    for (int i = 0; i < disabledChildCount; i++) {
8692                        String disabledChildPackageName =
8693                                disabledPkgSetting.childPackageNames.get(i);
8694                        boolean disabledPackageAvailable = false;
8695                        for (int j = 0; j < scannedChildCount; j++) {
8696                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8697                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8698                                disabledPackageAvailable = true;
8699                                break;
8700                            }
8701                        }
8702                        if (!disabledPackageAvailable) {
8703                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8704                        }
8705                    }
8706                    // we're updating the disabled package, so, scan it as the package setting
8707                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
8708                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8709                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8710                            (pkg == mPlatformPackage), user);
8711                    applyPolicy(pkg, parseFlags, scanFlags);
8712                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8713                }
8714            }
8715        }
8716
8717        final boolean newPkgChangedPaths =
8718                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8719        final boolean newPkgVersionGreater =
8720                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8721        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8722                && newPkgChangedPaths && newPkgVersionGreater;
8723        if (isSystemPkgBetter) {
8724            // The version of the application on /system is greater than the version on
8725            // /data. Switch back to the application on /system.
8726            // It's safe to assume the application on /system will correctly scan. If not,
8727            // there won't be a working copy of the application.
8728            synchronized (mPackages) {
8729                // just remove the loaded entries from package lists
8730                mPackages.remove(pkgSetting.name);
8731            }
8732
8733            logCriticalInfo(Log.WARN,
8734                    "System package updated;"
8735                    + " name: " + pkgSetting.name
8736                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8737                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8738
8739            final InstallArgs args = createInstallArgsForExisting(
8740                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8741                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8742            args.cleanUpResourcesLI();
8743            synchronized (mPackages) {
8744                mSettings.enableSystemPackageLPw(pkgSetting.name);
8745            }
8746        }
8747
8748        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8749            // The version of the application on the /system partition is less than or
8750            // equal to the version on the /data partition. Throw an exception and use
8751            // the application already installed on the /data partition.
8752            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8753                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8754                    + " better than this " + pkg.getLongVersionCode());
8755        }
8756
8757        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8758        // force re-collecting certificate.
8759        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8760                disabledPkgSetting);
8761        // Full APK verification can be skipped during certificate collection, only if the file is
8762        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8763        // cases, only data in Signing Block is verified instead of the whole file.
8764        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8765                (forceCollect && canSkipFullPackageVerification(pkg));
8766        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8767
8768        boolean shouldHideSystemApp = false;
8769        // A new application appeared on /system, but, we already have a copy of
8770        // the application installed on /data.
8771        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8772                && !pkgSetting.isSystem()) {
8773
8774            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8775                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
8776                logCriticalInfo(Log.WARN,
8777                        "System package signature mismatch;"
8778                        + " name: " + pkgSetting.name);
8779                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8780                        "scanPackageInternalLI")) {
8781                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8782                }
8783                pkgSetting = null;
8784            } else if (newPkgVersionGreater) {
8785                // The application on /system is newer than the application on /data.
8786                // Simply remove the application on /data [keeping application data]
8787                // and replace it with the version on /system.
8788                logCriticalInfo(Log.WARN,
8789                        "System package enabled;"
8790                        + " name: " + pkgSetting.name
8791                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8792                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8793                InstallArgs args = createInstallArgsForExisting(
8794                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8795                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8796                synchronized (mInstallLock) {
8797                    args.cleanUpResourcesLI();
8798                }
8799            } else {
8800                // The application on /system is older than the application on /data. Hide
8801                // the application on /system and the version on /data will be scanned later
8802                // and re-added like an update.
8803                shouldHideSystemApp = true;
8804                logCriticalInfo(Log.INFO,
8805                        "System package disabled;"
8806                        + " name: " + pkgSetting.name
8807                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8808                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8809            }
8810        }
8811
8812        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8813                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8814
8815        if (shouldHideSystemApp) {
8816            synchronized (mPackages) {
8817                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8818            }
8819        }
8820        return scannedPkg;
8821    }
8822
8823    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8824        // Derive the new package synthetic package name
8825        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8826                + pkg.staticSharedLibVersion);
8827    }
8828
8829    private static String fixProcessName(String defProcessName,
8830            String processName) {
8831        if (processName == null) {
8832            return defProcessName;
8833        }
8834        return processName;
8835    }
8836
8837    /**
8838     * Enforces that only the system UID or root's UID can call a method exposed
8839     * via Binder.
8840     *
8841     * @param message used as message if SecurityException is thrown
8842     * @throws SecurityException if the caller is not system or root
8843     */
8844    private static final void enforceSystemOrRoot(String message) {
8845        final int uid = Binder.getCallingUid();
8846        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8847            throw new SecurityException(message);
8848        }
8849    }
8850
8851    @Override
8852    public void performFstrimIfNeeded() {
8853        enforceSystemOrRoot("Only the system can request fstrim");
8854
8855        // Before everything else, see whether we need to fstrim.
8856        try {
8857            IStorageManager sm = PackageHelper.getStorageManager();
8858            if (sm != null) {
8859                boolean doTrim = false;
8860                final long interval = android.provider.Settings.Global.getLong(
8861                        mContext.getContentResolver(),
8862                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8863                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8864                if (interval > 0) {
8865                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8866                    if (timeSinceLast > interval) {
8867                        doTrim = true;
8868                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8869                                + "; running immediately");
8870                    }
8871                }
8872                if (doTrim) {
8873                    final boolean dexOptDialogShown;
8874                    synchronized (mPackages) {
8875                        dexOptDialogShown = mDexOptDialogShown;
8876                    }
8877                    if (!isFirstBoot() && dexOptDialogShown) {
8878                        try {
8879                            ActivityManager.getService().showBootMessage(
8880                                    mContext.getResources().getString(
8881                                            R.string.android_upgrading_fstrim), true);
8882                        } catch (RemoteException e) {
8883                        }
8884                    }
8885                    sm.runMaintenance();
8886                }
8887            } else {
8888                Slog.e(TAG, "storageManager service unavailable!");
8889            }
8890        } catch (RemoteException e) {
8891            // Can't happen; StorageManagerService is local
8892        }
8893    }
8894
8895    @Override
8896    public void updatePackagesIfNeeded() {
8897        enforceSystemOrRoot("Only the system can request package update");
8898
8899        // We need to re-extract after an OTA.
8900        boolean causeUpgrade = isUpgrade();
8901
8902        // First boot or factory reset.
8903        // Note: we also handle devices that are upgrading to N right now as if it is their
8904        //       first boot, as they do not have profile data.
8905        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8906
8907        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8908        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8909
8910        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8911            return;
8912        }
8913
8914        List<PackageParser.Package> pkgs;
8915        synchronized (mPackages) {
8916            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8917        }
8918
8919        final long startTime = System.nanoTime();
8920        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8921                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
8922                    false /* bootComplete */);
8923
8924        final int elapsedTimeSeconds =
8925                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8926
8927        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8928        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8929        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8930        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8931        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8932    }
8933
8934    /*
8935     * Return the prebuilt profile path given a package base code path.
8936     */
8937    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8938        return pkg.baseCodePath + ".prof";
8939    }
8940
8941    /**
8942     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8943     * containing statistics about the invocation. The array consists of three elements,
8944     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8945     * and {@code numberOfPackagesFailed}.
8946     */
8947    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8948            final int compilationReason, boolean bootComplete) {
8949
8950        int numberOfPackagesVisited = 0;
8951        int numberOfPackagesOptimized = 0;
8952        int numberOfPackagesSkipped = 0;
8953        int numberOfPackagesFailed = 0;
8954        final int numberOfPackagesToDexopt = pkgs.size();
8955
8956        for (PackageParser.Package pkg : pkgs) {
8957            numberOfPackagesVisited++;
8958
8959            boolean useProfileForDexopt = false;
8960
8961            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8962                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8963                // that are already compiled.
8964                File profileFile = new File(getPrebuildProfilePath(pkg));
8965                // Copy profile if it exists.
8966                if (profileFile.exists()) {
8967                    try {
8968                        // We could also do this lazily before calling dexopt in
8969                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8970                        // is that we don't have a good way to say "do this only once".
8971                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8972                                pkg.applicationInfo.uid, pkg.packageName,
8973                                ArtManager.getProfileName(null))) {
8974                            Log.e(TAG, "Installer failed to copy system profile!");
8975                        } else {
8976                            // Disabled as this causes speed-profile compilation during first boot
8977                            // even if things are already compiled.
8978                            // useProfileForDexopt = true;
8979                        }
8980                    } catch (Exception e) {
8981                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8982                                e);
8983                    }
8984                } else {
8985                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8986                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8987                    // minimize the number off apps being speed-profile compiled during first boot.
8988                    // The other paths will not change the filter.
8989                    if (disabledPs != null && disabledPs.pkg.isStub) {
8990                        // The package is the stub one, remove the stub suffix to get the normal
8991                        // package and APK names.
8992                        String systemProfilePath =
8993                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8994                        profileFile = new File(systemProfilePath);
8995                        // If we have a profile for a compressed APK, copy it to the reference
8996                        // location.
8997                        // Note that copying the profile here will cause it to override the
8998                        // reference profile every OTA even though the existing reference profile
8999                        // may have more data. We can't copy during decompression since the
9000                        // directories are not set up at that point.
9001                        if (profileFile.exists()) {
9002                            try {
9003                                // We could also do this lazily before calling dexopt in
9004                                // PackageDexOptimizer to prevent this happening on first boot. The
9005                                // issue is that we don't have a good way to say "do this only
9006                                // once".
9007                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9008                                        pkg.applicationInfo.uid, pkg.packageName,
9009                                        ArtManager.getProfileName(null))) {
9010                                    Log.e(TAG, "Failed to copy system profile for stub package!");
9011                                } else {
9012                                    useProfileForDexopt = true;
9013                                }
9014                            } catch (Exception e) {
9015                                Log.e(TAG, "Failed to copy profile " +
9016                                        profileFile.getAbsolutePath() + " ", e);
9017                            }
9018                        }
9019                    }
9020                }
9021            }
9022
9023            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9024                if (DEBUG_DEXOPT) {
9025                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9026                }
9027                numberOfPackagesSkipped++;
9028                continue;
9029            }
9030
9031            if (DEBUG_DEXOPT) {
9032                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9033                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9034            }
9035
9036            if (showDialog) {
9037                try {
9038                    ActivityManager.getService().showBootMessage(
9039                            mContext.getResources().getString(R.string.android_upgrading_apk,
9040                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9041                } catch (RemoteException e) {
9042                }
9043                synchronized (mPackages) {
9044                    mDexOptDialogShown = true;
9045                }
9046            }
9047
9048            int pkgCompilationReason = compilationReason;
9049            if (useProfileForDexopt) {
9050                // Use background dexopt mode to try and use the profile. Note that this does not
9051                // guarantee usage of the profile.
9052                pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT;
9053            }
9054
9055            // checkProfiles is false to avoid merging profiles during boot which
9056            // might interfere with background compilation (b/28612421).
9057            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9058            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9059            // trade-off worth doing to save boot time work.
9060            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9061            if (compilationReason == REASON_FIRST_BOOT) {
9062                // TODO: This doesn't cover the upgrade case, we should check for this too.
9063                dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE;
9064            }
9065            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9066                    pkg.packageName,
9067                    pkgCompilationReason,
9068                    dexoptFlags));
9069
9070            switch (primaryDexOptStaus) {
9071                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9072                    numberOfPackagesOptimized++;
9073                    break;
9074                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9075                    numberOfPackagesSkipped++;
9076                    break;
9077                case PackageDexOptimizer.DEX_OPT_FAILED:
9078                    numberOfPackagesFailed++;
9079                    break;
9080                default:
9081                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9082                    break;
9083            }
9084        }
9085
9086        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9087                numberOfPackagesFailed };
9088    }
9089
9090    @Override
9091    public void notifyPackageUse(String packageName, int reason) {
9092        synchronized (mPackages) {
9093            final int callingUid = Binder.getCallingUid();
9094            final int callingUserId = UserHandle.getUserId(callingUid);
9095            if (getInstantAppPackageName(callingUid) != null) {
9096                if (!isCallerSameApp(packageName, callingUid)) {
9097                    return;
9098                }
9099            } else {
9100                if (isInstantApp(packageName, callingUserId)) {
9101                    return;
9102                }
9103            }
9104            notifyPackageUseLocked(packageName, reason);
9105        }
9106    }
9107
9108    @GuardedBy("mPackages")
9109    private void notifyPackageUseLocked(String packageName, int reason) {
9110        final PackageParser.Package p = mPackages.get(packageName);
9111        if (p == null) {
9112            return;
9113        }
9114        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9115    }
9116
9117    @Override
9118    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9119            List<String> classPaths, String loaderIsa) {
9120        int userId = UserHandle.getCallingUserId();
9121        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9122        if (ai == null) {
9123            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9124                + loadingPackageName + ", user=" + userId);
9125            return;
9126        }
9127        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9128    }
9129
9130    @Override
9131    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9132            IDexModuleRegisterCallback callback) {
9133        int userId = UserHandle.getCallingUserId();
9134        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9135        DexManager.RegisterDexModuleResult result;
9136        if (ai == null) {
9137            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9138                     " calling user. package=" + packageName + ", user=" + userId);
9139            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9140        } else {
9141            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9142        }
9143
9144        if (callback != null) {
9145            mHandler.post(() -> {
9146                try {
9147                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9148                } catch (RemoteException e) {
9149                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9150                }
9151            });
9152        }
9153    }
9154
9155    /**
9156     * Ask the package manager to perform a dex-opt with the given compiler filter.
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 performDexOptMode(String packageName,
9163            boolean checkProfiles, String targetCompilerFilter, boolean force,
9164            boolean bootComplete, String splitName) {
9165        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9166                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9167                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9168        return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN,
9169                targetCompilerFilter, splitName, flags));
9170    }
9171
9172    /**
9173     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9174     * secondary dex files belonging to the given package.
9175     *
9176     * Note: exposed only for the shell command to allow moving packages explicitly to a
9177     *       definite state.
9178     */
9179    @Override
9180    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9181            boolean force) {
9182        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9183                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9184                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9185                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9186        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9187    }
9188
9189    /*package*/ boolean performDexOpt(DexoptOptions options) {
9190        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9191            return false;
9192        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9193            return false;
9194        }
9195
9196        if (options.isDexoptOnlySecondaryDex()) {
9197            return mDexManager.dexoptSecondaryDex(options);
9198        } else {
9199            int dexoptStatus = performDexOptWithStatus(options);
9200            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9201        }
9202    }
9203
9204    /**
9205     * Perform dexopt on the given package and return one of following result:
9206     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9207     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9208     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9209     */
9210    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9211        return performDexOptTraced(options);
9212    }
9213
9214    private int performDexOptTraced(DexoptOptions options) {
9215        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9216        try {
9217            return performDexOptInternal(options);
9218        } finally {
9219            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9220        }
9221    }
9222
9223    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9224    // if the package can now be considered up to date for the given filter.
9225    private int performDexOptInternal(DexoptOptions options) {
9226        PackageParser.Package p;
9227        synchronized (mPackages) {
9228            p = mPackages.get(options.getPackageName());
9229            if (p == null) {
9230                // Package could not be found. Report failure.
9231                return PackageDexOptimizer.DEX_OPT_FAILED;
9232            }
9233            mPackageUsage.maybeWriteAsync(mPackages);
9234            mCompilerStats.maybeWriteAsync();
9235        }
9236        long callingId = Binder.clearCallingIdentity();
9237        try {
9238            synchronized (mInstallLock) {
9239                return performDexOptInternalWithDependenciesLI(p, options);
9240            }
9241        } finally {
9242            Binder.restoreCallingIdentity(callingId);
9243        }
9244    }
9245
9246    public ArraySet<String> getOptimizablePackages() {
9247        ArraySet<String> pkgs = new ArraySet<String>();
9248        synchronized (mPackages) {
9249            for (PackageParser.Package p : mPackages.values()) {
9250                if (PackageDexOptimizer.canOptimizePackage(p)) {
9251                    pkgs.add(p.packageName);
9252                }
9253            }
9254        }
9255        return pkgs;
9256    }
9257
9258    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9259            DexoptOptions options) {
9260        // Select the dex optimizer based on the force parameter.
9261        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9262        //       allocate an object here.
9263        PackageDexOptimizer pdo = options.isForce()
9264                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9265                : mPackageDexOptimizer;
9266
9267        // Dexopt all dependencies first. Note: we ignore the return value and march on
9268        // on errors.
9269        // Note that we are going to call performDexOpt on those libraries as many times as
9270        // they are referenced in packages. When we do a batch of performDexOpt (for example
9271        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9272        // and the first package that uses the library will dexopt it. The
9273        // others will see that the compiled code for the library is up to date.
9274        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9275        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9276        if (!deps.isEmpty()) {
9277            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9278                    options.getCompilationReason(), options.getCompilerFilter(),
9279                    options.getSplitName(),
9280                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9281            for (PackageParser.Package depPackage : deps) {
9282                // TODO: Analyze and investigate if we (should) profile libraries.
9283                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9284                        getOrCreateCompilerPackageStats(depPackage),
9285                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9286            }
9287        }
9288        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9289                getOrCreateCompilerPackageStats(p),
9290                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9291    }
9292
9293    /**
9294     * Reconcile the information we have about the secondary dex files belonging to
9295     * {@code packagName} and the actual dex files. For all dex files that were
9296     * deleted, update the internal records and delete the generated oat files.
9297     */
9298    @Override
9299    public void reconcileSecondaryDexFiles(String packageName) {
9300        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9301            return;
9302        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9303            return;
9304        }
9305        mDexManager.reconcileSecondaryDexFiles(packageName);
9306    }
9307
9308    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9309    // a reference there.
9310    /*package*/ DexManager getDexManager() {
9311        return mDexManager;
9312    }
9313
9314    /**
9315     * Execute the background dexopt job immediately.
9316     */
9317    @Override
9318    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9319        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9320            return false;
9321        }
9322        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9323    }
9324
9325    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9326        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9327                || p.usesStaticLibraries != null) {
9328            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9329            Set<String> collectedNames = new HashSet<>();
9330            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9331
9332            retValue.remove(p);
9333
9334            return retValue;
9335        } else {
9336            return Collections.emptyList();
9337        }
9338    }
9339
9340    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9341            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9342        if (!collectedNames.contains(p.packageName)) {
9343            collectedNames.add(p.packageName);
9344            collected.add(p);
9345
9346            if (p.usesLibraries != null) {
9347                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9348                        null, collected, collectedNames);
9349            }
9350            if (p.usesOptionalLibraries != null) {
9351                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9352                        null, collected, collectedNames);
9353            }
9354            if (p.usesStaticLibraries != null) {
9355                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9356                        p.usesStaticLibrariesVersions, collected, collectedNames);
9357            }
9358        }
9359    }
9360
9361    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9362            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9363        final int libNameCount = libs.size();
9364        for (int i = 0; i < libNameCount; i++) {
9365            String libName = libs.get(i);
9366            long version = (versions != null && versions.length == libNameCount)
9367                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9368            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9369            if (libPkg != null) {
9370                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9371            }
9372        }
9373    }
9374
9375    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9376        synchronized (mPackages) {
9377            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9378            if (libEntry != null) {
9379                return mPackages.get(libEntry.apk);
9380            }
9381            return null;
9382        }
9383    }
9384
9385    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9386        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9387        if (versionedLib == null) {
9388            return null;
9389        }
9390        return versionedLib.get(version);
9391    }
9392
9393    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9394        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9395                pkg.staticSharedLibName);
9396        if (versionedLib == null) {
9397            return null;
9398        }
9399        long previousLibVersion = -1;
9400        final int versionCount = versionedLib.size();
9401        for (int i = 0; i < versionCount; i++) {
9402            final long libVersion = versionedLib.keyAt(i);
9403            if (libVersion < pkg.staticSharedLibVersion) {
9404                previousLibVersion = Math.max(previousLibVersion, libVersion);
9405            }
9406        }
9407        if (previousLibVersion >= 0) {
9408            return versionedLib.get(previousLibVersion);
9409        }
9410        return null;
9411    }
9412
9413    public void shutdown() {
9414        mPackageUsage.writeNow(mPackages);
9415        mCompilerStats.writeNow();
9416        mDexManager.writePackageDexUsageNow();
9417    }
9418
9419    @Override
9420    public void dumpProfiles(String packageName) {
9421        PackageParser.Package pkg;
9422        synchronized (mPackages) {
9423            pkg = mPackages.get(packageName);
9424            if (pkg == null) {
9425                throw new IllegalArgumentException("Unknown package: " + packageName);
9426            }
9427        }
9428        /* Only the shell, root, or the app user should be able to dump profiles. */
9429        int callingUid = Binder.getCallingUid();
9430        if (callingUid != Process.SHELL_UID &&
9431            callingUid != Process.ROOT_UID &&
9432            callingUid != pkg.applicationInfo.uid) {
9433            throw new SecurityException("dumpProfiles");
9434        }
9435
9436        synchronized (mInstallLock) {
9437            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9438            mArtManagerService.dumpProfiles(pkg);
9439            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9440        }
9441    }
9442
9443    @Override
9444    public void forceDexOpt(String packageName) {
9445        enforceSystemOrRoot("forceDexOpt");
9446
9447        PackageParser.Package pkg;
9448        synchronized (mPackages) {
9449            pkg = mPackages.get(packageName);
9450            if (pkg == null) {
9451                throw new IllegalArgumentException("Unknown package: " + packageName);
9452            }
9453        }
9454
9455        synchronized (mInstallLock) {
9456            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9457
9458            // Whoever is calling forceDexOpt wants a compiled package.
9459            // Don't use profiles since that may cause compilation to be skipped.
9460            final int res = performDexOptInternalWithDependenciesLI(
9461                    pkg,
9462                    new DexoptOptions(packageName,
9463                            getDefaultCompilerFilter(),
9464                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9465
9466            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9467            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9468                throw new IllegalStateException("Failed to dexopt: " + res);
9469            }
9470        }
9471    }
9472
9473    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9474        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9475            Slog.w(TAG, "Unable to update from " + oldPkg.name
9476                    + " to " + newPkg.packageName
9477                    + ": old package not in system partition");
9478            return false;
9479        } else if (mPackages.get(oldPkg.name) != null) {
9480            Slog.w(TAG, "Unable to update from " + oldPkg.name
9481                    + " to " + newPkg.packageName
9482                    + ": old package still exists");
9483            return false;
9484        }
9485        return true;
9486    }
9487
9488    void removeCodePathLI(File codePath) {
9489        if (codePath.isDirectory()) {
9490            try {
9491                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9492            } catch (InstallerException e) {
9493                Slog.w(TAG, "Failed to remove code path", e);
9494            }
9495        } else {
9496            codePath.delete();
9497        }
9498    }
9499
9500    private int[] resolveUserIds(int userId) {
9501        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9502    }
9503
9504    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9505        if (pkg == null) {
9506            Slog.wtf(TAG, "Package was null!", new Throwable());
9507            return;
9508        }
9509        clearAppDataLeafLIF(pkg, userId, flags);
9510        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9511        for (int i = 0; i < childCount; i++) {
9512            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9513        }
9514
9515        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9516    }
9517
9518    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9519        final PackageSetting ps;
9520        synchronized (mPackages) {
9521            ps = mSettings.mPackages.get(pkg.packageName);
9522        }
9523        for (int realUserId : resolveUserIds(userId)) {
9524            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9525            try {
9526                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9527                        ceDataInode);
9528            } catch (InstallerException e) {
9529                Slog.w(TAG, String.valueOf(e));
9530            }
9531        }
9532    }
9533
9534    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9535        if (pkg == null) {
9536            Slog.wtf(TAG, "Package was null!", new Throwable());
9537            return;
9538        }
9539        destroyAppDataLeafLIF(pkg, userId, flags);
9540        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9541        for (int i = 0; i < childCount; i++) {
9542            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9543        }
9544    }
9545
9546    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9547        final PackageSetting ps;
9548        synchronized (mPackages) {
9549            ps = mSettings.mPackages.get(pkg.packageName);
9550        }
9551        for (int realUserId : resolveUserIds(userId)) {
9552            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9553            try {
9554                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9555                        ceDataInode);
9556            } catch (InstallerException e) {
9557                Slog.w(TAG, String.valueOf(e));
9558            }
9559            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9560        }
9561    }
9562
9563    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9564        if (pkg == null) {
9565            Slog.wtf(TAG, "Package was null!", new Throwable());
9566            return;
9567        }
9568        destroyAppProfilesLeafLIF(pkg);
9569        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9570        for (int i = 0; i < childCount; i++) {
9571            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9572        }
9573    }
9574
9575    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9576        try {
9577            mInstaller.destroyAppProfiles(pkg.packageName);
9578        } catch (InstallerException e) {
9579            Slog.w(TAG, String.valueOf(e));
9580        }
9581    }
9582
9583    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9584        if (pkg == null) {
9585            Slog.wtf(TAG, "Package was null!", new Throwable());
9586            return;
9587        }
9588        mArtManagerService.clearAppProfiles(pkg);
9589        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9590        for (int i = 0; i < childCount; i++) {
9591            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9592        }
9593    }
9594
9595    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9596            long lastUpdateTime) {
9597        // Set parent install/update time
9598        PackageSetting ps = (PackageSetting) pkg.mExtras;
9599        if (ps != null) {
9600            ps.firstInstallTime = firstInstallTime;
9601            ps.lastUpdateTime = lastUpdateTime;
9602        }
9603        // Set children install/update time
9604        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9605        for (int i = 0; i < childCount; i++) {
9606            PackageParser.Package childPkg = pkg.childPackages.get(i);
9607            ps = (PackageSetting) childPkg.mExtras;
9608            if (ps != null) {
9609                ps.firstInstallTime = firstInstallTime;
9610                ps.lastUpdateTime = lastUpdateTime;
9611            }
9612        }
9613    }
9614
9615    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9616            SharedLibraryEntry file,
9617            PackageParser.Package changingLib) {
9618        if (file.path != null) {
9619            usesLibraryFiles.add(file.path);
9620            return;
9621        }
9622        PackageParser.Package p = mPackages.get(file.apk);
9623        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9624            // If we are doing this while in the middle of updating a library apk,
9625            // then we need to make sure to use that new apk for determining the
9626            // dependencies here.  (We haven't yet finished committing the new apk
9627            // to the package manager state.)
9628            if (p == null || p.packageName.equals(changingLib.packageName)) {
9629                p = changingLib;
9630            }
9631        }
9632        if (p != null) {
9633            usesLibraryFiles.addAll(p.getAllCodePaths());
9634            if (p.usesLibraryFiles != null) {
9635                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9636            }
9637        }
9638    }
9639
9640    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9641            PackageParser.Package changingLib) throws PackageManagerException {
9642        if (pkg == null) {
9643            return;
9644        }
9645        // The collection used here must maintain the order of addition (so
9646        // that libraries are searched in the correct order) and must have no
9647        // duplicates.
9648        Set<String> usesLibraryFiles = null;
9649        if (pkg.usesLibraries != null) {
9650            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9651                    null, null, pkg.packageName, changingLib, true,
9652                    pkg.applicationInfo.targetSdkVersion, null);
9653        }
9654        if (pkg.usesStaticLibraries != null) {
9655            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9656                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9657                    pkg.packageName, changingLib, true,
9658                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9659        }
9660        if (pkg.usesOptionalLibraries != null) {
9661            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9662                    null, null, pkg.packageName, changingLib, false,
9663                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9664        }
9665        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9666            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9667        } else {
9668            pkg.usesLibraryFiles = null;
9669        }
9670    }
9671
9672    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9673            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9674            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9675            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9676            throws PackageManagerException {
9677        final int libCount = requestedLibraries.size();
9678        for (int i = 0; i < libCount; i++) {
9679            final String libName = requestedLibraries.get(i);
9680            final long libVersion = requiredVersions != null ? requiredVersions[i]
9681                    : SharedLibraryInfo.VERSION_UNDEFINED;
9682            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9683            if (libEntry == null) {
9684                if (required) {
9685                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9686                            "Package " + packageName + " requires unavailable shared library "
9687                                    + libName + "; failing!");
9688                } else if (DEBUG_SHARED_LIBRARIES) {
9689                    Slog.i(TAG, "Package " + packageName
9690                            + " desires unavailable shared library "
9691                            + libName + "; ignoring!");
9692                }
9693            } else {
9694                if (requiredVersions != null && requiredCertDigests != null) {
9695                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9696                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9697                            "Package " + packageName + " requires unavailable static shared"
9698                                    + " library " + libName + " version "
9699                                    + libEntry.info.getLongVersion() + "; failing!");
9700                    }
9701
9702                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9703                    if (libPkg == null) {
9704                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9705                                "Package " + packageName + " requires unavailable static shared"
9706                                        + " library; failing!");
9707                    }
9708
9709                    final String[] expectedCertDigests = requiredCertDigests[i];
9710
9711
9712                    if (expectedCertDigests.length > 1) {
9713
9714                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9715                        final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9716                                ? PackageUtils.computeSignaturesSha256Digests(
9717                                libPkg.mSigningDetails.signatures)
9718                                : PackageUtils.computeSignaturesSha256Digests(
9719                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9720
9721                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9722                        // target O we don't parse the "additional-certificate" tags similarly
9723                        // how we only consider all certs only for apps targeting O (see above).
9724                        // Therefore, the size check is safe to make.
9725                        if (expectedCertDigests.length != libCertDigests.length) {
9726                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9727                                    "Package " + packageName + " requires differently signed" +
9728                                            " static shared library; failing!");
9729                        }
9730
9731                        // Use a predictable order as signature order may vary
9732                        Arrays.sort(libCertDigests);
9733                        Arrays.sort(expectedCertDigests);
9734
9735                        final int certCount = libCertDigests.length;
9736                        for (int j = 0; j < certCount; j++) {
9737                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9738                                throw new PackageManagerException(
9739                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9740                                        "Package " + packageName + " requires differently signed" +
9741                                                " static shared library; failing!");
9742                            }
9743                        }
9744                    } else {
9745
9746                        // lib signing cert could have rotated beyond the one expected, check to see
9747                        // if the new one has been blessed by the old
9748                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9749                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9750                            throw new PackageManagerException(
9751                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9752                                    "Package " + packageName + " requires differently signed" +
9753                                            " static shared library; failing!");
9754                        }
9755                    }
9756                }
9757
9758                if (outUsedLibraries == null) {
9759                    // Use LinkedHashSet to preserve the order of files added to
9760                    // usesLibraryFiles while eliminating duplicates.
9761                    outUsedLibraries = new LinkedHashSet<>();
9762                }
9763                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9764            }
9765        }
9766        return outUsedLibraries;
9767    }
9768
9769    private static boolean hasString(List<String> list, List<String> which) {
9770        if (list == null) {
9771            return false;
9772        }
9773        for (int i=list.size()-1; i>=0; i--) {
9774            for (int j=which.size()-1; j>=0; j--) {
9775                if (which.get(j).equals(list.get(i))) {
9776                    return true;
9777                }
9778            }
9779        }
9780        return false;
9781    }
9782
9783    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9784            PackageParser.Package changingPkg) {
9785        ArrayList<PackageParser.Package> res = null;
9786        for (PackageParser.Package pkg : mPackages.values()) {
9787            if (changingPkg != null
9788                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9789                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9790                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9791                            changingPkg.staticSharedLibName)) {
9792                return null;
9793            }
9794            if (res == null) {
9795                res = new ArrayList<>();
9796            }
9797            res.add(pkg);
9798            try {
9799                updateSharedLibrariesLPr(pkg, changingPkg);
9800            } catch (PackageManagerException e) {
9801                // If a system app update or an app and a required lib missing we
9802                // delete the package and for updated system apps keep the data as
9803                // it is better for the user to reinstall than to be in an limbo
9804                // state. Also libs disappearing under an app should never happen
9805                // - just in case.
9806                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9807                    final int flags = pkg.isUpdatedSystemApp()
9808                            ? PackageManager.DELETE_KEEP_DATA : 0;
9809                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9810                            flags , null, true, null);
9811                }
9812                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9813            }
9814        }
9815        return res;
9816    }
9817
9818    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9819            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9820            @Nullable UserHandle user) throws PackageManagerException {
9821        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9822        // If the package has children and this is the first dive in the function
9823        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9824        // whether all packages (parent and children) would be successfully scanned
9825        // before the actual scan since scanning mutates internal state and we want
9826        // to atomically install the package and its children.
9827        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9828            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9829                scanFlags |= SCAN_CHECK_ONLY;
9830            }
9831        } else {
9832            scanFlags &= ~SCAN_CHECK_ONLY;
9833        }
9834
9835        final PackageParser.Package scannedPkg;
9836        try {
9837            // Scan the parent
9838            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9839            // Scan the children
9840            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9841            for (int i = 0; i < childCount; i++) {
9842                PackageParser.Package childPkg = pkg.childPackages.get(i);
9843                scanPackageNewLI(childPkg, parseFlags,
9844                        scanFlags, currentTime, user);
9845            }
9846        } finally {
9847            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9848        }
9849
9850        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9851            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9852        }
9853
9854        return scannedPkg;
9855    }
9856
9857    /** The result of a package scan. */
9858    private static class ScanResult {
9859        /** Whether or not the package scan was successful */
9860        public final boolean success;
9861        /**
9862         * The final package settings. This may be the same object passed in
9863         * the {@link ScanRequest}, but, with modified values.
9864         */
9865        @Nullable public final PackageSetting pkgSetting;
9866        /** ABI code paths that have changed in the package scan */
9867        @Nullable public final List<String> changedAbiCodePath;
9868        public ScanResult(
9869                boolean success,
9870                @Nullable PackageSetting pkgSetting,
9871                @Nullable List<String> changedAbiCodePath) {
9872            this.success = success;
9873            this.pkgSetting = pkgSetting;
9874            this.changedAbiCodePath = changedAbiCodePath;
9875        }
9876    }
9877
9878    /** A package to be scanned */
9879    private static class ScanRequest {
9880        /** The parsed package */
9881        @NonNull public final PackageParser.Package pkg;
9882        /** Shared user settings, if the package has a shared user */
9883        @Nullable public final SharedUserSetting sharedUserSetting;
9884        /**
9885         * Package settings of the currently installed version.
9886         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9887         * during scan.
9888         */
9889        @Nullable public final PackageSetting pkgSetting;
9890        /** A copy of the settings for the currently installed version */
9891        @Nullable public final PackageSetting oldPkgSetting;
9892        /** Package settings for the disabled version on the /system partition */
9893        @Nullable public final PackageSetting disabledPkgSetting;
9894        /** Package settings for the installed version under its original package name */
9895        @Nullable public final PackageSetting originalPkgSetting;
9896        /** The real package name of a renamed application */
9897        @Nullable public final String realPkgName;
9898        public final @ParseFlags int parseFlags;
9899        public final @ScanFlags int scanFlags;
9900        /** The user for which the package is being scanned */
9901        @Nullable public final UserHandle user;
9902        /** Whether or not the platform package is being scanned */
9903        public final boolean isPlatformPackage;
9904        public ScanRequest(
9905                @NonNull PackageParser.Package pkg,
9906                @Nullable SharedUserSetting sharedUserSetting,
9907                @Nullable PackageSetting pkgSetting,
9908                @Nullable PackageSetting disabledPkgSetting,
9909                @Nullable PackageSetting originalPkgSetting,
9910                @Nullable String realPkgName,
9911                @ParseFlags int parseFlags,
9912                @ScanFlags int scanFlags,
9913                boolean isPlatformPackage,
9914                @Nullable UserHandle user) {
9915            this.pkg = pkg;
9916            this.pkgSetting = pkgSetting;
9917            this.sharedUserSetting = sharedUserSetting;
9918            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9919            this.disabledPkgSetting = disabledPkgSetting;
9920            this.originalPkgSetting = originalPkgSetting;
9921            this.realPkgName = realPkgName;
9922            this.parseFlags = parseFlags;
9923            this.scanFlags = scanFlags;
9924            this.isPlatformPackage = isPlatformPackage;
9925            this.user = user;
9926        }
9927    }
9928
9929    /**
9930     * Returns the actual scan flags depending upon the state of the other settings.
9931     * <p>Updated system applications will not have the following flags set
9932     * by default and need to be adjusted after the fact:
9933     * <ul>
9934     * <li>{@link #SCAN_AS_SYSTEM}</li>
9935     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9936     * <li>{@link #SCAN_AS_OEM}</li>
9937     * <li>{@link #SCAN_AS_VENDOR}</li>
9938     * <li>{@link #SCAN_AS_PRODUCT}</li>
9939     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9940     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9941     * </ul>
9942     */
9943    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9944            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9945            PackageParser.Package pkg) {
9946        if (disabledPkgSetting != null) {
9947            // updated system application, must at least have SCAN_AS_SYSTEM
9948            scanFlags |= SCAN_AS_SYSTEM;
9949            if ((disabledPkgSetting.pkgPrivateFlags
9950                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9951                scanFlags |= SCAN_AS_PRIVILEGED;
9952            }
9953            if ((disabledPkgSetting.pkgPrivateFlags
9954                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9955                scanFlags |= SCAN_AS_OEM;
9956            }
9957            if ((disabledPkgSetting.pkgPrivateFlags
9958                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9959                scanFlags |= SCAN_AS_VENDOR;
9960            }
9961            if ((disabledPkgSetting.pkgPrivateFlags
9962                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9963                scanFlags |= SCAN_AS_PRODUCT;
9964            }
9965        }
9966        if (pkgSetting != null) {
9967            final int userId = ((user == null) ? 0 : user.getIdentifier());
9968            if (pkgSetting.getInstantApp(userId)) {
9969                scanFlags |= SCAN_AS_INSTANT_APP;
9970            }
9971            if (pkgSetting.getVirtulalPreload(userId)) {
9972                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9973            }
9974        }
9975
9976        // Scan as privileged apps that share a user with a priv-app.
9977        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9978                && (pkg.mSharedUserId != null)) {
9979            SharedUserSetting sharedUserSetting = null;
9980            try {
9981                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9982            } catch (PackageManagerException ignore) {}
9983            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9984                // Exempt SharedUsers signed with the platform key.
9985                // TODO(b/72378145) Fix this exemption. Force signature apps
9986                // to whitelist their privileged permissions just like other
9987                // priv-apps.
9988                synchronized (mPackages) {
9989                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9990                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
9991                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
9992                        scanFlags |= SCAN_AS_PRIVILEGED;
9993                    }
9994                }
9995            }
9996        }
9997
9998        return scanFlags;
9999    }
10000
10001    // TODO: scanPackageNewLI() and scanPackageOnly() should be merged. But, first, commiting
10002    // the results / removing app data needs to be moved up a level to the callers of this
10003    // method. Also, we need to solve the problem of potentially creating a new shared user
10004    // setting. That can probably be done later and patch things up after the fact.
10005    @GuardedBy("mInstallLock")
10006    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
10007            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
10008            @Nullable UserHandle user) throws PackageManagerException {
10009
10010        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10011        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
10012        if (realPkgName != null) {
10013            ensurePackageRenamed(pkg, renamedPkgName);
10014        }
10015        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
10016        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10017        final PackageSetting disabledPkgSetting =
10018                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10019
10020        if (mTransferedPackages.contains(pkg.packageName)) {
10021            Slog.w(TAG, "Package " + pkg.packageName
10022                    + " was transferred to another, but its .apk remains");
10023        }
10024
10025        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
10026        synchronized (mPackages) {
10027            applyPolicy(pkg, parseFlags, scanFlags);
10028            assertPackageIsValid(pkg, parseFlags, scanFlags);
10029
10030            SharedUserSetting sharedUserSetting = null;
10031            if (pkg.mSharedUserId != null) {
10032                // SIDE EFFECTS; may potentially allocate a new shared user
10033                sharedUserSetting = mSettings.getSharedUserLPw(
10034                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10035                if (DEBUG_PACKAGE_SCANNING) {
10036                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10037                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
10038                                + " (uid=" + sharedUserSetting.userId + "):"
10039                                + " packages=" + sharedUserSetting.packages);
10040                }
10041            }
10042
10043            boolean scanSucceeded = false;
10044            try {
10045                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
10046                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
10047                        (pkg == mPlatformPackage), user);
10048                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
10049                if (result.success) {
10050                    commitScanResultsLocked(request, result);
10051                }
10052                scanSucceeded = true;
10053            } finally {
10054                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10055                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
10056                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10057                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10058                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10059                  }
10060            }
10061        }
10062        return pkg;
10063    }
10064
10065    /**
10066     * Commits the package scan and modifies system state.
10067     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
10068     * of committing the package, leaving the system in an inconsistent state.
10069     * This needs to be fixed so, once we get to this point, no errors are
10070     * possible and the system is not left in an inconsistent state.
10071     */
10072    @GuardedBy("mPackages")
10073    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
10074            throws PackageManagerException {
10075        final PackageParser.Package pkg = request.pkg;
10076        final @ParseFlags int parseFlags = request.parseFlags;
10077        final @ScanFlags int scanFlags = request.scanFlags;
10078        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10079        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10080        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10081        final UserHandle user = request.user;
10082        final String realPkgName = request.realPkgName;
10083        final PackageSetting pkgSetting = result.pkgSetting;
10084        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10085        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10086
10087        if (newPkgSettingCreated) {
10088            if (originalPkgSetting != null) {
10089                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10090            }
10091            // THROWS: when we can't allocate a user id. add call to check if there's
10092            // enough space to ensure we won't throw; otherwise, don't modify state
10093            mSettings.addUserToSettingLPw(pkgSetting);
10094
10095            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10096                mTransferedPackages.add(originalPkgSetting.name);
10097            }
10098        }
10099        // TODO(toddke): Consider a method specifically for modifying the Package object
10100        // post scan; or, moving this stuff out of the Package object since it has nothing
10101        // to do with the package on disk.
10102        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10103        // for creating the application ID. If we did this earlier, we would be saving the
10104        // correct ID.
10105        pkg.applicationInfo.uid = pkgSetting.appId;
10106
10107        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10108
10109        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10110            mTransferedPackages.add(pkg.packageName);
10111        }
10112
10113        // THROWS: when requested libraries that can't be found. it only changes
10114        // the state of the passed in pkg object, so, move to the top of the method
10115        // and allow it to abort
10116        if ((scanFlags & SCAN_BOOTING) == 0
10117                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10118            // Check all shared libraries and map to their actual file path.
10119            // We only do this here for apps not on a system dir, because those
10120            // are the only ones that can fail an install due to this.  We
10121            // will take care of the system apps by updating all of their
10122            // library paths after the scan is done. Also during the initial
10123            // scan don't update any libs as we do this wholesale after all
10124            // apps are scanned to avoid dependency based scanning.
10125            updateSharedLibrariesLPr(pkg, null);
10126        }
10127
10128        // All versions of a static shared library are referenced with the same
10129        // package name. Internally, we use a synthetic package name to allow
10130        // multiple versions of the same shared library to be installed. So,
10131        // we need to generate the synthetic package name of the latest shared
10132        // library in order to compare signatures.
10133        PackageSetting signatureCheckPs = pkgSetting;
10134        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10135            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10136            if (libraryEntry != null) {
10137                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10138            }
10139        }
10140
10141        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10142        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10143            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10144                // We just determined the app is signed correctly, so bring
10145                // over the latest parsed certs.
10146                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10147            } else {
10148                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10149                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10150                            "Package " + pkg.packageName + " upgrade keys do not match the "
10151                                    + "previously installed version");
10152                } else {
10153                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10154                    String msg = "System package " + pkg.packageName
10155                            + " signature changed; retaining data.";
10156                    reportSettingsProblem(Log.WARN, msg);
10157                }
10158            }
10159        } else {
10160            try {
10161                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10162                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10163                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10164                        pkg.mSigningDetails, compareCompat, compareRecover);
10165                // The new KeySets will be re-added later in the scanning process.
10166                if (compatMatch) {
10167                    synchronized (mPackages) {
10168                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10169                    }
10170                }
10171                // We just determined the app is signed correctly, so bring
10172                // over the latest parsed certs.
10173                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10174
10175
10176                // if this is is a sharedUser, check to see if the new package is signed by a newer
10177                // signing certificate than the existing one, and if so, copy over the new details
10178                if (signatureCheckPs.sharedUser != null
10179                        && pkg.mSigningDetails.hasAncestor(
10180                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10181                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10182                }
10183            } catch (PackageManagerException e) {
10184                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10185                    throw e;
10186                }
10187                // The signature has changed, but this package is in the system
10188                // image...  let's recover!
10189                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10190                // However...  if this package is part of a shared user, but it
10191                // doesn't match the signature of the shared user, let's fail.
10192                // What this means is that you can't change the signatures
10193                // associated with an overall shared user, which doesn't seem all
10194                // that unreasonable.
10195                if (signatureCheckPs.sharedUser != null) {
10196                    if (compareSignatures(
10197                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10198                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10199                        throw new PackageManagerException(
10200                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10201                                "Signature mismatch for shared user: "
10202                                        + pkgSetting.sharedUser);
10203                    }
10204                }
10205                // File a report about this.
10206                String msg = "System package " + pkg.packageName
10207                        + " signature changed; retaining data.";
10208                reportSettingsProblem(Log.WARN, msg);
10209            } catch (IllegalArgumentException e) {
10210
10211                // should never happen: certs matched when checking, but not when comparing
10212                // old to new for sharedUser
10213                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10214                        "Signing certificates comparison made on incomparable signing details"
10215                        + " but somehow passed verifySignatures!");
10216            }
10217        }
10218
10219        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10220            // This package wants to adopt ownership of permissions from
10221            // another package.
10222            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10223                final String origName = pkg.mAdoptPermissions.get(i);
10224                final PackageSetting orig = mSettings.getPackageLPr(origName);
10225                if (orig != null) {
10226                    if (verifyPackageUpdateLPr(orig, pkg)) {
10227                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10228                                + pkg.packageName);
10229                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10230                    }
10231                }
10232            }
10233        }
10234
10235        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10236            for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
10237                final String codePathString = changedAbiCodePath.get(i);
10238                try {
10239                    mInstaller.rmdex(codePathString,
10240                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10241                } catch (InstallerException ignored) {
10242                }
10243            }
10244        }
10245
10246        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10247            if (oldPkgSetting != null) {
10248                synchronized (mPackages) {
10249                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10250                }
10251            }
10252        } else {
10253            final int userId = user == null ? 0 : user.getIdentifier();
10254            // Modify state for the given package setting
10255            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10256                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10257            if (pkgSetting.getInstantApp(userId)) {
10258                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10259            }
10260        }
10261    }
10262
10263    /**
10264     * Returns the "real" name of the package.
10265     * <p>This may differ from the package's actual name if the application has already
10266     * been installed under one of this package's original names.
10267     */
10268    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10269            @Nullable String renamedPkgName) {
10270        if (isPackageRenamed(pkg, renamedPkgName)) {
10271            return pkg.mRealPackage;
10272        }
10273        return null;
10274    }
10275
10276    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10277    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10278            @Nullable String renamedPkgName) {
10279        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10280    }
10281
10282    /**
10283     * Returns the original package setting.
10284     * <p>A package can migrate its name during an update. In this scenario, a package
10285     * designates a set of names that it considers as one of its original names.
10286     * <p>An original package must be signed identically and it must have the same
10287     * shared user [if any].
10288     */
10289    @GuardedBy("mPackages")
10290    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10291            @Nullable String renamedPkgName) {
10292        if (!isPackageRenamed(pkg, renamedPkgName)) {
10293            return null;
10294        }
10295        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10296            final PackageSetting originalPs =
10297                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10298            if (originalPs != null) {
10299                // the package is already installed under its original name...
10300                // but, should we use it?
10301                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10302                    // the new package is incompatible with the original
10303                    continue;
10304                } else if (originalPs.sharedUser != null) {
10305                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10306                        // the shared user id is incompatible with the original
10307                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10308                                + " to " + pkg.packageName + ": old uid "
10309                                + originalPs.sharedUser.name
10310                                + " differs from " + pkg.mSharedUserId);
10311                        continue;
10312                    }
10313                    // TODO: Add case when shared user id is added [b/28144775]
10314                } else {
10315                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10316                            + pkg.packageName + " to old name " + originalPs.name);
10317                }
10318                return originalPs;
10319            }
10320        }
10321        return null;
10322    }
10323
10324    /**
10325     * Renames the package if it was installed under a different name.
10326     * <p>When we've already installed the package under an original name, update
10327     * the new package so we can continue to have the old name.
10328     */
10329    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10330            @NonNull String renamedPackageName) {
10331        if (pkg.mOriginalPackages == null
10332                || !pkg.mOriginalPackages.contains(renamedPackageName)
10333                || pkg.packageName.equals(renamedPackageName)) {
10334            return;
10335        }
10336        pkg.setPackageName(renamedPackageName);
10337    }
10338
10339    /**
10340     * Just scans the package without any side effects.
10341     * <p>Not entirely true at the moment. There is still one side effect -- this
10342     * method potentially modifies a live {@link PackageSetting} object representing
10343     * the package being scanned. This will be resolved in the future.
10344     *
10345     * @param request Information about the package to be scanned
10346     * @param isUnderFactoryTest Whether or not the device is under factory test
10347     * @param currentTime The current time, in millis
10348     * @return The results of the scan
10349     */
10350    @GuardedBy("mInstallLock")
10351    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10352            boolean isUnderFactoryTest, long currentTime)
10353                    throws PackageManagerException {
10354        final PackageParser.Package pkg = request.pkg;
10355        PackageSetting pkgSetting = request.pkgSetting;
10356        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10357        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10358        final @ParseFlags int parseFlags = request.parseFlags;
10359        final @ScanFlags int scanFlags = request.scanFlags;
10360        final String realPkgName = request.realPkgName;
10361        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10362        final UserHandle user = request.user;
10363        final boolean isPlatformPackage = request.isPlatformPackage;
10364
10365        List<String> changedAbiCodePath = null;
10366
10367        if (DEBUG_PACKAGE_SCANNING) {
10368            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10369                Log.d(TAG, "Scanning package " + pkg.packageName);
10370        }
10371
10372        if (Build.IS_DEBUGGABLE &&
10373                pkg.isPrivileged() &&
10374                SystemProperties.getBoolean(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, false)) {
10375            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10376        }
10377
10378        // Initialize package source and resource directories
10379        final File scanFile = new File(pkg.codePath);
10380        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10381        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10382
10383        // We keep references to the derived CPU Abis from settings in oder to reuse
10384        // them in the case where we're not upgrading or booting for the first time.
10385        String primaryCpuAbiFromSettings = null;
10386        String secondaryCpuAbiFromSettings = null;
10387        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10388
10389        if (!needToDeriveAbi) {
10390            if (pkgSetting != null) {
10391                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10392                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10393            } else {
10394                // Re-scanning a system package after uninstalling updates; need to derive ABI
10395                needToDeriveAbi = true;
10396            }
10397        }
10398
10399        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10400            PackageManagerService.reportSettingsProblem(Log.WARN,
10401                    "Package " + pkg.packageName + " shared user changed from "
10402                            + (pkgSetting.sharedUser != null
10403                            ? pkgSetting.sharedUser.name : "<nothing>")
10404                            + " to "
10405                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10406                            + "; replacing with new");
10407            pkgSetting = null;
10408        }
10409
10410        String[] usesStaticLibraries = null;
10411        if (pkg.usesStaticLibraries != null) {
10412            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10413            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10414        }
10415        final boolean createNewPackage = (pkgSetting == null);
10416        if (createNewPackage) {
10417            final String parentPackageName = (pkg.parentPackage != null)
10418                    ? pkg.parentPackage.packageName : null;
10419            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10420            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10421            // REMOVE SharedUserSetting from method; update in a separate call
10422            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10423                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10424                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10425                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10426                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10427                    user, true /*allowInstall*/, instantApp, virtualPreload,
10428                    parentPackageName, pkg.getChildPackageNames(),
10429                    UserManagerService.getInstance(), usesStaticLibraries,
10430                    pkg.usesStaticLibrariesVersions);
10431        } else {
10432            // REMOVE SharedUserSetting from method; update in a separate call.
10433            //
10434            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10435            // secondaryCpuAbi are not known at this point so we always update them
10436            // to null here, only to reset them at a later point.
10437            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10438                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10439                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10440                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10441                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10442                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10443        }
10444        if (createNewPackage && originalPkgSetting != null) {
10445            // This is the initial transition from the original package, so,
10446            // fix up the new package's name now. We must do this after looking
10447            // up the package under its new name, so getPackageLP takes care of
10448            // fiddling things correctly.
10449            pkg.setPackageName(originalPkgSetting.name);
10450
10451            // File a report about this.
10452            String msg = "New package " + pkgSetting.realName
10453                    + " renamed to replace old package " + pkgSetting.name;
10454            reportSettingsProblem(Log.WARN, msg);
10455        }
10456
10457        if (disabledPkgSetting != null) {
10458            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10459        }
10460
10461        // Apps which share a sharedUserId must be placed in the same selinux domain. If this
10462        // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its
10463        // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be
10464        // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the
10465        // least restrictive selinux domain.
10466        // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion
10467        // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This
10468        // ensures that all packages continue to run in the same selinux domain.
10469        final int targetSdkVersion =
10470            ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ?
10471            sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion;
10472        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10473        // They currently can be if the sharedUser apps are signed with the platform key.
10474        final boolean isPrivileged = (sharedUserSetting != null) ?
10475            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10476
10477        pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged,
10478                pkg.applicationInfo.targetSandboxVersion, targetSdkVersion);
10479
10480        pkg.mExtras = pkgSetting;
10481        pkg.applicationInfo.processName = fixProcessName(
10482                pkg.applicationInfo.packageName,
10483                pkg.applicationInfo.processName);
10484
10485        if (!isPlatformPackage) {
10486            // Get all of our default paths setup
10487            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10488        }
10489
10490        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10491
10492        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10493            if (needToDeriveAbi) {
10494                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10495                final boolean extractNativeLibs = !pkg.isLibrary();
10496                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10497                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10498
10499                // Some system apps still use directory structure for native libraries
10500                // in which case we might end up not detecting abi solely based on apk
10501                // structure. Try to detect abi based on directory structure.
10502                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10503                        pkg.applicationInfo.primaryCpuAbi == null) {
10504                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10505                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10506                }
10507            } else {
10508                // This is not a first boot or an upgrade, don't bother deriving the
10509                // ABI during the scan. Instead, trust the value that was stored in the
10510                // package setting.
10511                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10512                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10513
10514                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10515
10516                if (DEBUG_ABI_SELECTION) {
10517                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10518                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10519                            pkg.applicationInfo.secondaryCpuAbi);
10520                }
10521            }
10522        } else {
10523            if ((scanFlags & SCAN_MOVE) != 0) {
10524                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10525                // but we already have this packages package info in the PackageSetting. We just
10526                // use that and derive the native library path based on the new codepath.
10527                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10528                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10529            }
10530
10531            // Set native library paths again. For moves, the path will be updated based on the
10532            // ABIs we've determined above. For non-moves, the path will be updated based on the
10533            // ABIs we determined during compilation, but the path will depend on the final
10534            // package path (after the rename away from the stage path).
10535            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10536        }
10537
10538        // This is a special case for the "system" package, where the ABI is
10539        // dictated by the zygote configuration (and init.rc). We should keep track
10540        // of this ABI so that we can deal with "normal" applications that run under
10541        // the same UID correctly.
10542        if (isPlatformPackage) {
10543            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10544                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10545        }
10546
10547        // If there's a mismatch between the abi-override in the package setting
10548        // and the abiOverride specified for the install. Warn about this because we
10549        // would've already compiled the app without taking the package setting into
10550        // account.
10551        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10552            if (cpuAbiOverride == null && pkg.packageName != null) {
10553                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10554                        " for package " + pkg.packageName);
10555            }
10556        }
10557
10558        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10559        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10560        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10561
10562        // Copy the derived override back to the parsed package, so that we can
10563        // update the package settings accordingly.
10564        pkg.cpuAbiOverride = cpuAbiOverride;
10565
10566        if (DEBUG_ABI_SELECTION) {
10567            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10568                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10569                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10570        }
10571
10572        // Push the derived path down into PackageSettings so we know what to
10573        // clean up at uninstall time.
10574        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10575
10576        if (DEBUG_ABI_SELECTION) {
10577            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10578                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10579                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10580        }
10581
10582        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10583            // We don't do this here during boot because we can do it all
10584            // at once after scanning all existing packages.
10585            //
10586            // We also do this *before* we perform dexopt on this package, so that
10587            // we can avoid redundant dexopts, and also to make sure we've got the
10588            // code and package path correct.
10589            changedAbiCodePath =
10590                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10591        }
10592
10593        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10594                android.Manifest.permission.FACTORY_TEST)) {
10595            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10596        }
10597
10598        if (isSystemApp(pkg)) {
10599            pkgSetting.isOrphaned = true;
10600        }
10601
10602        // Take care of first install / last update times.
10603        final long scanFileTime = getLastModifiedTime(pkg);
10604        if (currentTime != 0) {
10605            if (pkgSetting.firstInstallTime == 0) {
10606                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10607            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10608                pkgSetting.lastUpdateTime = currentTime;
10609            }
10610        } else if (pkgSetting.firstInstallTime == 0) {
10611            // We need *something*.  Take time time stamp of the file.
10612            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10613        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10614            if (scanFileTime != pkgSetting.timeStamp) {
10615                // A package on the system image has changed; consider this
10616                // to be an update.
10617                pkgSetting.lastUpdateTime = scanFileTime;
10618            }
10619        }
10620        pkgSetting.setTimeStamp(scanFileTime);
10621
10622        pkgSetting.pkg = pkg;
10623        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10624        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10625            pkgSetting.versionCode = pkg.getLongVersionCode();
10626        }
10627        // Update volume if needed
10628        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10629        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10630            Slog.i(PackageManagerService.TAG,
10631                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10632                    + " package " + pkg.packageName
10633                    + " volume from " + pkgSetting.volumeUuid
10634                    + " to " + volumeUuid);
10635            pkgSetting.volumeUuid = volumeUuid;
10636        }
10637
10638        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10639    }
10640
10641    /**
10642     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10643     */
10644    private static boolean apkHasCode(String fileName) {
10645        StrictJarFile jarFile = null;
10646        try {
10647            jarFile = new StrictJarFile(fileName,
10648                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10649            return jarFile.findEntry("classes.dex") != null;
10650        } catch (IOException ignore) {
10651        } finally {
10652            try {
10653                if (jarFile != null) {
10654                    jarFile.close();
10655                }
10656            } catch (IOException ignore) {}
10657        }
10658        return false;
10659    }
10660
10661    /**
10662     * Enforces code policy for the package. This ensures that if an APK has
10663     * declared hasCode="true" in its manifest that the APK actually contains
10664     * code.
10665     *
10666     * @throws PackageManagerException If bytecode could not be found when it should exist
10667     */
10668    private static void assertCodePolicy(PackageParser.Package pkg)
10669            throws PackageManagerException {
10670        final boolean shouldHaveCode =
10671                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10672        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10673            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10674                    "Package " + pkg.baseCodePath + " code is missing");
10675        }
10676
10677        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10678            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10679                final boolean splitShouldHaveCode =
10680                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10681                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10682                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10683                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10684                }
10685            }
10686        }
10687    }
10688
10689    /**
10690     * Applies policy to the parsed package based upon the given policy flags.
10691     * Ensures the package is in a good state.
10692     * <p>
10693     * Implementation detail: This method must NOT have any side effect. It would
10694     * ideally be static, but, it requires locks to read system state.
10695     */
10696    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10697            final @ScanFlags int scanFlags) {
10698        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10699            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10700            if (pkg.applicationInfo.isDirectBootAware()) {
10701                // we're direct boot aware; set for all components
10702                for (PackageParser.Service s : pkg.services) {
10703                    s.info.encryptionAware = s.info.directBootAware = true;
10704                }
10705                for (PackageParser.Provider p : pkg.providers) {
10706                    p.info.encryptionAware = p.info.directBootAware = true;
10707                }
10708                for (PackageParser.Activity a : pkg.activities) {
10709                    a.info.encryptionAware = a.info.directBootAware = true;
10710                }
10711                for (PackageParser.Activity r : pkg.receivers) {
10712                    r.info.encryptionAware = r.info.directBootAware = true;
10713                }
10714            }
10715            if (compressedFileExists(pkg.codePath)) {
10716                pkg.isStub = true;
10717            }
10718        } else {
10719            // non system apps can't be flagged as core
10720            pkg.coreApp = false;
10721            // clear flags not applicable to regular apps
10722            pkg.applicationInfo.flags &=
10723                    ~ApplicationInfo.FLAG_PERSISTENT;
10724            pkg.applicationInfo.privateFlags &=
10725                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10726            pkg.applicationInfo.privateFlags &=
10727                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10728            // cap permission priorities
10729            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10730                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10731                    pkg.permissionGroups.get(i).info.priority = 0;
10732                }
10733            }
10734        }
10735        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10736            // clear protected broadcasts
10737            pkg.protectedBroadcasts = null;
10738            // ignore export request for single user receivers
10739            if (pkg.receivers != null) {
10740                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10741                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10742                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10743                        receiver.info.exported = false;
10744                    }
10745                }
10746            }
10747            // ignore export request for single user services
10748            if (pkg.services != null) {
10749                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10750                    final PackageParser.Service service = pkg.services.get(i);
10751                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10752                        service.info.exported = false;
10753                    }
10754                }
10755            }
10756            // ignore export request for single user providers
10757            if (pkg.providers != null) {
10758                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10759                    final PackageParser.Provider provider = pkg.providers.get(i);
10760                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10761                        provider.info.exported = false;
10762                    }
10763                }
10764            }
10765        }
10766
10767        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10768            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10769        }
10770
10771        if ((scanFlags & SCAN_AS_OEM) != 0) {
10772            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10773        }
10774
10775        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10776            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10777        }
10778
10779        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10780            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10781        }
10782
10783        if (!isSystemApp(pkg)) {
10784            // Only system apps can use these features.
10785            pkg.mOriginalPackages = null;
10786            pkg.mRealPackage = null;
10787            pkg.mAdoptPermissions = null;
10788        }
10789    }
10790
10791    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10792            throws PackageManagerException {
10793        if (object == null) {
10794            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10795        }
10796        return object;
10797    }
10798
10799    /**
10800     * Asserts the parsed package is valid according to the given policy. If the
10801     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10802     * <p>
10803     * Implementation detail: This method must NOT have any side effects. It would
10804     * ideally be static, but, it requires locks to read system state.
10805     *
10806     * @throws PackageManagerException If the package fails any of the validation checks
10807     */
10808    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10809            final @ScanFlags int scanFlags)
10810                    throws PackageManagerException {
10811        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10812            assertCodePolicy(pkg);
10813        }
10814
10815        if (pkg.applicationInfo.getCodePath() == null ||
10816                pkg.applicationInfo.getResourcePath() == null) {
10817            // Bail out. The resource and code paths haven't been set.
10818            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10819                    "Code and resource paths haven't been set correctly");
10820        }
10821
10822        // Make sure we're not adding any bogus keyset info
10823        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10824        ksms.assertScannedPackageValid(pkg);
10825
10826        synchronized (mPackages) {
10827            // The special "android" package can only be defined once
10828            if (pkg.packageName.equals("android")) {
10829                if (mAndroidApplication != null) {
10830                    Slog.w(TAG, "*************************************************");
10831                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10832                    Slog.w(TAG, " codePath=" + pkg.codePath);
10833                    Slog.w(TAG, "*************************************************");
10834                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10835                            "Core android package being redefined.  Skipping.");
10836                }
10837            }
10838
10839            // A package name must be unique; don't allow duplicates
10840            if (mPackages.containsKey(pkg.packageName)) {
10841                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10842                        "Application package " + pkg.packageName
10843                        + " already installed.  Skipping duplicate.");
10844            }
10845
10846            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10847                // Static libs have a synthetic package name containing the version
10848                // but we still want the base name to be unique.
10849                if (mPackages.containsKey(pkg.manifestPackageName)) {
10850                    throw new PackageManagerException(
10851                            "Duplicate static shared lib provider package");
10852                }
10853
10854                // Static shared libraries should have at least O target SDK
10855                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10856                    throw new PackageManagerException(
10857                            "Packages declaring static-shared libs must target O SDK or higher");
10858                }
10859
10860                // Package declaring static a shared lib cannot be instant apps
10861                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10862                    throw new PackageManagerException(
10863                            "Packages declaring static-shared libs cannot be instant apps");
10864                }
10865
10866                // Package declaring static a shared lib cannot be renamed since the package
10867                // name is synthetic and apps can't code around package manager internals.
10868                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10869                    throw new PackageManagerException(
10870                            "Packages declaring static-shared libs cannot be renamed");
10871                }
10872
10873                // Package declaring static a shared lib cannot declare child packages
10874                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10875                    throw new PackageManagerException(
10876                            "Packages declaring static-shared libs cannot have child packages");
10877                }
10878
10879                // Package declaring static a shared lib cannot declare dynamic libs
10880                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10881                    throw new PackageManagerException(
10882                            "Packages declaring static-shared libs cannot declare dynamic libs");
10883                }
10884
10885                // Package declaring static a shared lib cannot declare shared users
10886                if (pkg.mSharedUserId != null) {
10887                    throw new PackageManagerException(
10888                            "Packages declaring static-shared libs cannot declare shared users");
10889                }
10890
10891                // Static shared libs cannot declare activities
10892                if (!pkg.activities.isEmpty()) {
10893                    throw new PackageManagerException(
10894                            "Static shared libs cannot declare activities");
10895                }
10896
10897                // Static shared libs cannot declare services
10898                if (!pkg.services.isEmpty()) {
10899                    throw new PackageManagerException(
10900                            "Static shared libs cannot declare services");
10901                }
10902
10903                // Static shared libs cannot declare providers
10904                if (!pkg.providers.isEmpty()) {
10905                    throw new PackageManagerException(
10906                            "Static shared libs cannot declare content providers");
10907                }
10908
10909                // Static shared libs cannot declare receivers
10910                if (!pkg.receivers.isEmpty()) {
10911                    throw new PackageManagerException(
10912                            "Static shared libs cannot declare broadcast receivers");
10913                }
10914
10915                // Static shared libs cannot declare permission groups
10916                if (!pkg.permissionGroups.isEmpty()) {
10917                    throw new PackageManagerException(
10918                            "Static shared libs cannot declare permission groups");
10919                }
10920
10921                // Static shared libs cannot declare permissions
10922                if (!pkg.permissions.isEmpty()) {
10923                    throw new PackageManagerException(
10924                            "Static shared libs cannot declare permissions");
10925                }
10926
10927                // Static shared libs cannot declare protected broadcasts
10928                if (pkg.protectedBroadcasts != null) {
10929                    throw new PackageManagerException(
10930                            "Static shared libs cannot declare protected broadcasts");
10931                }
10932
10933                // Static shared libs cannot be overlay targets
10934                if (pkg.mOverlayTarget != null) {
10935                    throw new PackageManagerException(
10936                            "Static shared libs cannot be overlay targets");
10937                }
10938
10939                // The version codes must be ordered as lib versions
10940                long minVersionCode = Long.MIN_VALUE;
10941                long maxVersionCode = Long.MAX_VALUE;
10942
10943                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10944                        pkg.staticSharedLibName);
10945                if (versionedLib != null) {
10946                    final int versionCount = versionedLib.size();
10947                    for (int i = 0; i < versionCount; i++) {
10948                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10949                        final long libVersionCode = libInfo.getDeclaringPackage()
10950                                .getLongVersionCode();
10951                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10952                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10953                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10954                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10955                        } else {
10956                            minVersionCode = maxVersionCode = libVersionCode;
10957                            break;
10958                        }
10959                    }
10960                }
10961                if (pkg.getLongVersionCode() < minVersionCode
10962                        || pkg.getLongVersionCode() > maxVersionCode) {
10963                    throw new PackageManagerException("Static shared"
10964                            + " lib version codes must be ordered as lib versions");
10965                }
10966            }
10967
10968            // Only privileged apps and updated privileged apps can add child packages.
10969            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10970                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10971                    throw new PackageManagerException("Only privileged apps can add child "
10972                            + "packages. Ignoring package " + pkg.packageName);
10973                }
10974                final int childCount = pkg.childPackages.size();
10975                for (int i = 0; i < childCount; i++) {
10976                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10977                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10978                            childPkg.packageName)) {
10979                        throw new PackageManagerException("Can't override child of "
10980                                + "another disabled app. Ignoring package " + pkg.packageName);
10981                    }
10982                }
10983            }
10984
10985            // If we're only installing presumed-existing packages, require that the
10986            // scanned APK is both already known and at the path previously established
10987            // for it.  Previously unknown packages we pick up normally, but if we have an
10988            // a priori expectation about this package's install presence, enforce it.
10989            // With a singular exception for new system packages. When an OTA contains
10990            // a new system package, we allow the codepath to change from a system location
10991            // to the user-installed location. If we don't allow this change, any newer,
10992            // user-installed version of the application will be ignored.
10993            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10994                if (mExpectingBetter.containsKey(pkg.packageName)) {
10995                    logCriticalInfo(Log.WARN,
10996                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10997                } else {
10998                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10999                    if (known != null) {
11000                        if (DEBUG_PACKAGE_SCANNING) {
11001                            Log.d(TAG, "Examining " + pkg.codePath
11002                                    + " and requiring known paths " + known.codePathString
11003                                    + " & " + known.resourcePathString);
11004                        }
11005                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11006                                || !pkg.applicationInfo.getResourcePath().equals(
11007                                        known.resourcePathString)) {
11008                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11009                                    "Application package " + pkg.packageName
11010                                    + " found at " + pkg.applicationInfo.getCodePath()
11011                                    + " but expected at " + known.codePathString
11012                                    + "; ignoring.");
11013                        }
11014                    } else {
11015                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11016                                "Application package " + pkg.packageName
11017                                + " not found; ignoring.");
11018                    }
11019                }
11020            }
11021
11022            // Verify that this new package doesn't have any content providers
11023            // that conflict with existing packages.  Only do this if the
11024            // package isn't already installed, since we don't want to break
11025            // things that are installed.
11026            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11027                final int N = pkg.providers.size();
11028                int i;
11029                for (i=0; i<N; i++) {
11030                    PackageParser.Provider p = pkg.providers.get(i);
11031                    if (p.info.authority != null) {
11032                        String names[] = p.info.authority.split(";");
11033                        for (int j = 0; j < names.length; j++) {
11034                            if (mProvidersByAuthority.containsKey(names[j])) {
11035                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11036                                final String otherPackageName =
11037                                        ((other != null && other.getComponentName() != null) ?
11038                                                other.getComponentName().getPackageName() : "?");
11039                                throw new PackageManagerException(
11040                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11041                                        "Can't install because provider name " + names[j]
11042                                                + " (in package " + pkg.applicationInfo.packageName
11043                                                + ") is already used by " + otherPackageName);
11044                            }
11045                        }
11046                    }
11047                }
11048            }
11049
11050            // Verify that packages sharing a user with a privileged app are marked as privileged.
11051            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
11052                SharedUserSetting sharedUserSetting = null;
11053                try {
11054                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
11055                } catch (PackageManagerException ignore) {}
11056                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
11057                    // Exempt SharedUsers signed with the platform key.
11058                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
11059                    if ((platformPkgSetting.signatures.mSigningDetails
11060                            != PackageParser.SigningDetails.UNKNOWN)
11061                            && (compareSignatures(
11062                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11063                                    pkg.mSigningDetails.signatures)
11064                                            != PackageManager.SIGNATURE_MATCH)) {
11065                        throw new PackageManagerException("Apps that share a user with a " +
11066                                "privileged app must themselves be marked as privileged. " +
11067                                pkg.packageName + " shares privileged user " +
11068                                pkg.mSharedUserId + ".");
11069                    }
11070                }
11071            }
11072
11073            // Apply policies specific for runtime resource overlays (RROs).
11074            if (pkg.mOverlayTarget != null) {
11075                // System overlays have some restrictions on their use of the 'static' state.
11076                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11077                    // We are scanning a system overlay. This can be the first scan of the
11078                    // system/vendor/oem partition, or an update to the system overlay.
11079                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11080                        // This must be an update to a system overlay.
11081                        final PackageSetting previousPkg = assertNotNull(
11082                                mSettings.getPackageLPr(pkg.packageName),
11083                                "previous package state not present");
11084
11085                        // Static overlays cannot be updated.
11086                        if (previousPkg.pkg.mOverlayIsStatic) {
11087                            throw new PackageManagerException("Overlay " + pkg.packageName +
11088                                    " is static and cannot be upgraded.");
11089                        // Non-static overlays cannot be converted to static overlays.
11090                        } else if (pkg.mOverlayIsStatic) {
11091                            throw new PackageManagerException("Overlay " + pkg.packageName +
11092                                    " cannot be upgraded into a static overlay.");
11093                        }
11094                    }
11095                } else {
11096                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11097                    if (pkg.mOverlayIsStatic) {
11098                        throw new PackageManagerException("Overlay " + pkg.packageName +
11099                                " is static but not pre-installed.");
11100                    }
11101
11102                    // The only case where we allow installation of a non-system overlay is when
11103                    // its signature is signed with the platform certificate.
11104                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11105                    if ((platformPkgSetting.signatures.mSigningDetails
11106                            != PackageParser.SigningDetails.UNKNOWN)
11107                            && (compareSignatures(
11108                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11109                                    pkg.mSigningDetails.signatures)
11110                                            != PackageManager.SIGNATURE_MATCH)) {
11111                        throw new PackageManagerException("Overlay " + pkg.packageName +
11112                                " must be signed with the platform certificate.");
11113                    }
11114                }
11115            }
11116        }
11117    }
11118
11119    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11120            int type, String declaringPackageName, long declaringVersionCode) {
11121        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11122        if (versionedLib == null) {
11123            versionedLib = new LongSparseArray<>();
11124            mSharedLibraries.put(name, versionedLib);
11125            if (type == SharedLibraryInfo.TYPE_STATIC) {
11126                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11127            }
11128        } else if (versionedLib.indexOfKey(version) >= 0) {
11129            return false;
11130        }
11131        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11132                version, type, declaringPackageName, declaringVersionCode);
11133        versionedLib.put(version, libEntry);
11134        return true;
11135    }
11136
11137    private boolean removeSharedLibraryLPw(String name, long version) {
11138        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11139        if (versionedLib == null) {
11140            return false;
11141        }
11142        final int libIdx = versionedLib.indexOfKey(version);
11143        if (libIdx < 0) {
11144            return false;
11145        }
11146        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11147        versionedLib.remove(version);
11148        if (versionedLib.size() <= 0) {
11149            mSharedLibraries.remove(name);
11150            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11151                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11152                        .getPackageName());
11153            }
11154        }
11155        return true;
11156    }
11157
11158    /**
11159     * Adds a scanned package to the system. When this method is finished, the package will
11160     * be available for query, resolution, etc...
11161     */
11162    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11163            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
11164        final String pkgName = pkg.packageName;
11165        if (mCustomResolverComponentName != null &&
11166                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11167            setUpCustomResolverActivity(pkg);
11168        }
11169
11170        if (pkg.packageName.equals("android")) {
11171            synchronized (mPackages) {
11172                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11173                    // Set up information for our fall-back user intent resolution activity.
11174                    mPlatformPackage = pkg;
11175                    pkg.mVersionCode = mSdkVersion;
11176                    pkg.mVersionCodeMajor = 0;
11177                    mAndroidApplication = pkg.applicationInfo;
11178                    if (!mResolverReplaced) {
11179                        mResolveActivity.applicationInfo = mAndroidApplication;
11180                        mResolveActivity.name = ResolverActivity.class.getName();
11181                        mResolveActivity.packageName = mAndroidApplication.packageName;
11182                        mResolveActivity.processName = "system:ui";
11183                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11184                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11185                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11186                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11187                        mResolveActivity.exported = true;
11188                        mResolveActivity.enabled = true;
11189                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11190                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11191                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11192                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11193                                | ActivityInfo.CONFIG_ORIENTATION
11194                                | ActivityInfo.CONFIG_KEYBOARD
11195                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11196                        mResolveInfo.activityInfo = mResolveActivity;
11197                        mResolveInfo.priority = 0;
11198                        mResolveInfo.preferredOrder = 0;
11199                        mResolveInfo.match = 0;
11200                        mResolveComponentName = new ComponentName(
11201                                mAndroidApplication.packageName, mResolveActivity.name);
11202                    }
11203                }
11204            }
11205        }
11206
11207        ArrayList<PackageParser.Package> clientLibPkgs = null;
11208        // writer
11209        synchronized (mPackages) {
11210            boolean hasStaticSharedLibs = false;
11211
11212            // Any app can add new static shared libraries
11213            if (pkg.staticSharedLibName != null) {
11214                // Static shared libs don't allow renaming as they have synthetic package
11215                // names to allow install of multiple versions, so use name from manifest.
11216                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11217                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11218                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11219                    hasStaticSharedLibs = true;
11220                } else {
11221                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11222                                + pkg.staticSharedLibName + " already exists; skipping");
11223                }
11224                // Static shared libs cannot be updated once installed since they
11225                // use synthetic package name which includes the version code, so
11226                // not need to update other packages's shared lib dependencies.
11227            }
11228
11229            if (!hasStaticSharedLibs
11230                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11231                // Only system apps can add new dynamic shared libraries.
11232                if (pkg.libraryNames != null) {
11233                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11234                        String name = pkg.libraryNames.get(i);
11235                        boolean allowed = false;
11236                        if (pkg.isUpdatedSystemApp()) {
11237                            // New library entries can only be added through the
11238                            // system image.  This is important to get rid of a lot
11239                            // of nasty edge cases: for example if we allowed a non-
11240                            // system update of the app to add a library, then uninstalling
11241                            // the update would make the library go away, and assumptions
11242                            // we made such as through app install filtering would now
11243                            // have allowed apps on the device which aren't compatible
11244                            // with it.  Better to just have the restriction here, be
11245                            // conservative, and create many fewer cases that can negatively
11246                            // impact the user experience.
11247                            final PackageSetting sysPs = mSettings
11248                                    .getDisabledSystemPkgLPr(pkg.packageName);
11249                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11250                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11251                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11252                                        allowed = true;
11253                                        break;
11254                                    }
11255                                }
11256                            }
11257                        } else {
11258                            allowed = true;
11259                        }
11260                        if (allowed) {
11261                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11262                                    SharedLibraryInfo.VERSION_UNDEFINED,
11263                                    SharedLibraryInfo.TYPE_DYNAMIC,
11264                                    pkg.packageName, pkg.getLongVersionCode())) {
11265                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11266                                        + name + " already exists; skipping");
11267                            }
11268                        } else {
11269                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11270                                    + name + " that is not declared on system image; skipping");
11271                        }
11272                    }
11273
11274                    if ((scanFlags & SCAN_BOOTING) == 0) {
11275                        // If we are not booting, we need to update any applications
11276                        // that are clients of our shared library.  If we are booting,
11277                        // this will all be done once the scan is complete.
11278                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11279                    }
11280                }
11281            }
11282        }
11283
11284        if ((scanFlags & SCAN_BOOTING) != 0) {
11285            // No apps can run during boot scan, so they don't need to be frozen
11286        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11287            // Caller asked to not kill app, so it's probably not frozen
11288        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11289            // Caller asked us to ignore frozen check for some reason; they
11290            // probably didn't know the package name
11291        } else {
11292            // We're doing major surgery on this package, so it better be frozen
11293            // right now to keep it from launching
11294            checkPackageFrozen(pkgName);
11295        }
11296
11297        // Also need to kill any apps that are dependent on the library.
11298        if (clientLibPkgs != null) {
11299            for (int i=0; i<clientLibPkgs.size(); i++) {
11300                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11301                killApplication(clientPkg.applicationInfo.packageName,
11302                        clientPkg.applicationInfo.uid, "update lib");
11303            }
11304        }
11305
11306        // writer
11307        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11308
11309        synchronized (mPackages) {
11310            // We don't expect installation to fail beyond this point
11311
11312            // Add the new setting to mSettings
11313            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11314            // Add the new setting to mPackages
11315            mPackages.put(pkg.applicationInfo.packageName, pkg);
11316            // Make sure we don't accidentally delete its data.
11317            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11318            while (iter.hasNext()) {
11319                PackageCleanItem item = iter.next();
11320                if (pkgName.equals(item.packageName)) {
11321                    iter.remove();
11322                }
11323            }
11324
11325            // Add the package's KeySets to the global KeySetManagerService
11326            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11327            ksms.addScannedPackageLPw(pkg);
11328
11329            int N = pkg.providers.size();
11330            StringBuilder r = null;
11331            int i;
11332            for (i=0; i<N; i++) {
11333                PackageParser.Provider p = pkg.providers.get(i);
11334                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11335                        p.info.processName);
11336                mProviders.addProvider(p);
11337                p.syncable = p.info.isSyncable;
11338                if (p.info.authority != null) {
11339                    String names[] = p.info.authority.split(";");
11340                    p.info.authority = null;
11341                    for (int j = 0; j < names.length; j++) {
11342                        if (j == 1 && p.syncable) {
11343                            // We only want the first authority for a provider to possibly be
11344                            // syncable, so if we already added this provider using a different
11345                            // authority clear the syncable flag. We copy the provider before
11346                            // changing it because the mProviders object contains a reference
11347                            // to a provider that we don't want to change.
11348                            // Only do this for the second authority since the resulting provider
11349                            // object can be the same for all future authorities for this provider.
11350                            p = new PackageParser.Provider(p);
11351                            p.syncable = false;
11352                        }
11353                        if (!mProvidersByAuthority.containsKey(names[j])) {
11354                            mProvidersByAuthority.put(names[j], p);
11355                            if (p.info.authority == null) {
11356                                p.info.authority = names[j];
11357                            } else {
11358                                p.info.authority = p.info.authority + ";" + names[j];
11359                            }
11360                            if (DEBUG_PACKAGE_SCANNING) {
11361                                if (chatty)
11362                                    Log.d(TAG, "Registered content provider: " + names[j]
11363                                            + ", className = " + p.info.name + ", isSyncable = "
11364                                            + p.info.isSyncable);
11365                            }
11366                        } else {
11367                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11368                            Slog.w(TAG, "Skipping provider name " + names[j] +
11369                                    " (in package " + pkg.applicationInfo.packageName +
11370                                    "): name already used by "
11371                                    + ((other != null && other.getComponentName() != null)
11372                                            ? other.getComponentName().getPackageName() : "?"));
11373                        }
11374                    }
11375                }
11376                if (chatty) {
11377                    if (r == null) {
11378                        r = new StringBuilder(256);
11379                    } else {
11380                        r.append(' ');
11381                    }
11382                    r.append(p.info.name);
11383                }
11384            }
11385            if (r != null) {
11386                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11387            }
11388
11389            N = pkg.services.size();
11390            r = null;
11391            for (i=0; i<N; i++) {
11392                PackageParser.Service s = pkg.services.get(i);
11393                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11394                        s.info.processName);
11395                mServices.addService(s);
11396                if (chatty) {
11397                    if (r == null) {
11398                        r = new StringBuilder(256);
11399                    } else {
11400                        r.append(' ');
11401                    }
11402                    r.append(s.info.name);
11403                }
11404            }
11405            if (r != null) {
11406                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11407            }
11408
11409            N = pkg.receivers.size();
11410            r = null;
11411            for (i=0; i<N; i++) {
11412                PackageParser.Activity a = pkg.receivers.get(i);
11413                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11414                        a.info.processName);
11415                mReceivers.addActivity(a, "receiver");
11416                if (chatty) {
11417                    if (r == null) {
11418                        r = new StringBuilder(256);
11419                    } else {
11420                        r.append(' ');
11421                    }
11422                    r.append(a.info.name);
11423                }
11424            }
11425            if (r != null) {
11426                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11427            }
11428
11429            N = pkg.activities.size();
11430            r = null;
11431            for (i=0; i<N; i++) {
11432                PackageParser.Activity a = pkg.activities.get(i);
11433                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11434                        a.info.processName);
11435                mActivities.addActivity(a, "activity");
11436                if (chatty) {
11437                    if (r == null) {
11438                        r = new StringBuilder(256);
11439                    } else {
11440                        r.append(' ');
11441                    }
11442                    r.append(a.info.name);
11443                }
11444            }
11445            if (r != null) {
11446                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11447            }
11448
11449            // Don't allow ephemeral applications to define new permissions groups.
11450            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11451                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11452                        + " ignored: instant apps cannot define new permission groups.");
11453            } else {
11454                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11455            }
11456
11457            // Don't allow ephemeral applications to define new permissions.
11458            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11459                Slog.w(TAG, "Permissions from package " + pkg.packageName
11460                        + " ignored: instant apps cannot define new permissions.");
11461            } else {
11462                mPermissionManager.addAllPermissions(pkg, chatty);
11463            }
11464
11465            N = pkg.instrumentation.size();
11466            r = null;
11467            for (i=0; i<N; i++) {
11468                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11469                a.info.packageName = pkg.applicationInfo.packageName;
11470                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11471                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11472                a.info.splitNames = pkg.splitNames;
11473                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11474                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11475                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11476                a.info.dataDir = pkg.applicationInfo.dataDir;
11477                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11478                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11479                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11480                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11481                mInstrumentation.put(a.getComponentName(), a);
11482                if (chatty) {
11483                    if (r == null) {
11484                        r = new StringBuilder(256);
11485                    } else {
11486                        r.append(' ');
11487                    }
11488                    r.append(a.info.name);
11489                }
11490            }
11491            if (r != null) {
11492                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11493            }
11494
11495            if (pkg.protectedBroadcasts != null) {
11496                N = pkg.protectedBroadcasts.size();
11497                synchronized (mProtectedBroadcasts) {
11498                    for (i = 0; i < N; i++) {
11499                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11500                    }
11501                }
11502            }
11503        }
11504
11505        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11506    }
11507
11508    /**
11509     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11510     * is derived purely on the basis of the contents of {@code scanFile} and
11511     * {@code cpuAbiOverride}.
11512     *
11513     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11514     */
11515    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11516            boolean extractLibs)
11517                    throws PackageManagerException {
11518        // Give ourselves some initial paths; we'll come back for another
11519        // pass once we've determined ABI below.
11520        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11521
11522        // We would never need to extract libs for forward-locked and external packages,
11523        // since the container service will do it for us. We shouldn't attempt to
11524        // extract libs from system app when it was not updated.
11525        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11526                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11527            extractLibs = false;
11528        }
11529
11530        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11531        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11532
11533        NativeLibraryHelper.Handle handle = null;
11534        try {
11535            handle = NativeLibraryHelper.Handle.create(pkg);
11536            // TODO(multiArch): This can be null for apps that didn't go through the
11537            // usual installation process. We can calculate it again, like we
11538            // do during install time.
11539            //
11540            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11541            // unnecessary.
11542            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11543
11544            // Null out the abis so that they can be recalculated.
11545            pkg.applicationInfo.primaryCpuAbi = null;
11546            pkg.applicationInfo.secondaryCpuAbi = null;
11547            if (isMultiArch(pkg.applicationInfo)) {
11548                // Warn if we've set an abiOverride for multi-lib packages..
11549                // By definition, we need to copy both 32 and 64 bit libraries for
11550                // such packages.
11551                if (pkg.cpuAbiOverride != null
11552                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11553                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11554                }
11555
11556                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11557                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11558                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11559                    if (extractLibs) {
11560                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11561                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11562                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11563                                useIsaSpecificSubdirs);
11564                    } else {
11565                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11566                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11567                    }
11568                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11569                }
11570
11571                // Shared library native code should be in the APK zip aligned
11572                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11573                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11574                            "Shared library native lib extraction not supported");
11575                }
11576
11577                maybeThrowExceptionForMultiArchCopy(
11578                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11579
11580                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11581                    if (extractLibs) {
11582                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11583                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11584                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11585                                useIsaSpecificSubdirs);
11586                    } else {
11587                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11588                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11589                    }
11590                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11591                }
11592
11593                maybeThrowExceptionForMultiArchCopy(
11594                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11595
11596                if (abi64 >= 0) {
11597                    // Shared library native libs should be in the APK zip aligned
11598                    if (extractLibs && pkg.isLibrary()) {
11599                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11600                                "Shared library native lib extraction not supported");
11601                    }
11602                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11603                }
11604
11605                if (abi32 >= 0) {
11606                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11607                    if (abi64 >= 0) {
11608                        if (pkg.use32bitAbi) {
11609                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11610                            pkg.applicationInfo.primaryCpuAbi = abi;
11611                        } else {
11612                            pkg.applicationInfo.secondaryCpuAbi = abi;
11613                        }
11614                    } else {
11615                        pkg.applicationInfo.primaryCpuAbi = abi;
11616                    }
11617                }
11618            } else {
11619                String[] abiList = (cpuAbiOverride != null) ?
11620                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11621
11622                // Enable gross and lame hacks for apps that are built with old
11623                // SDK tools. We must scan their APKs for renderscript bitcode and
11624                // not launch them if it's present. Don't bother checking on devices
11625                // that don't have 64 bit support.
11626                boolean needsRenderScriptOverride = false;
11627                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11628                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11629                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11630                    needsRenderScriptOverride = true;
11631                }
11632
11633                final int copyRet;
11634                if (extractLibs) {
11635                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11636                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11637                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11638                } else {
11639                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11640                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11641                }
11642                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11643
11644                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11645                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11646                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11647                }
11648
11649                if (copyRet >= 0) {
11650                    // Shared libraries that have native libs must be multi-architecture
11651                    if (pkg.isLibrary()) {
11652                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11653                                "Shared library with native libs must be multiarch");
11654                    }
11655                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11656                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11657                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11658                } else if (needsRenderScriptOverride) {
11659                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11660                }
11661            }
11662        } catch (IOException ioe) {
11663            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11664        } finally {
11665            IoUtils.closeQuietly(handle);
11666        }
11667
11668        // Now that we've calculated the ABIs and determined if it's an internal app,
11669        // we will go ahead and populate the nativeLibraryPath.
11670        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11671    }
11672
11673    /**
11674     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11675     * i.e, so that all packages can be run inside a single process if required.
11676     *
11677     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11678     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11679     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11680     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11681     * updating a package that belongs to a shared user.
11682     *
11683     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11684     * adds unnecessary complexity.
11685     */
11686    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11687            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11688        List<String> changedAbiCodePath = null;
11689        String requiredInstructionSet = null;
11690        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11691            requiredInstructionSet = VMRuntime.getInstructionSet(
11692                     scannedPackage.applicationInfo.primaryCpuAbi);
11693        }
11694
11695        PackageSetting requirer = null;
11696        for (PackageSetting ps : packagesForUser) {
11697            // If packagesForUser contains scannedPackage, we skip it. This will happen
11698            // when scannedPackage is an update of an existing package. Without this check,
11699            // we will never be able to change the ABI of any package belonging to a shared
11700            // user, even if it's compatible with other packages.
11701            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11702                if (ps.primaryCpuAbiString == null) {
11703                    continue;
11704                }
11705
11706                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11707                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11708                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11709                    // this but there's not much we can do.
11710                    String errorMessage = "Instruction set mismatch, "
11711                            + ((requirer == null) ? "[caller]" : requirer)
11712                            + " requires " + requiredInstructionSet + " whereas " + ps
11713                            + " requires " + instructionSet;
11714                    Slog.w(TAG, errorMessage);
11715                }
11716
11717                if (requiredInstructionSet == null) {
11718                    requiredInstructionSet = instructionSet;
11719                    requirer = ps;
11720                }
11721            }
11722        }
11723
11724        if (requiredInstructionSet != null) {
11725            String adjustedAbi;
11726            if (requirer != null) {
11727                // requirer != null implies that either scannedPackage was null or that scannedPackage
11728                // did not require an ABI, in which case we have to adjust scannedPackage to match
11729                // the ABI of the set (which is the same as requirer's ABI)
11730                adjustedAbi = requirer.primaryCpuAbiString;
11731                if (scannedPackage != null) {
11732                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11733                }
11734            } else {
11735                // requirer == null implies that we're updating all ABIs in the set to
11736                // match scannedPackage.
11737                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11738            }
11739
11740            for (PackageSetting ps : packagesForUser) {
11741                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11742                    if (ps.primaryCpuAbiString != null) {
11743                        continue;
11744                    }
11745
11746                    ps.primaryCpuAbiString = adjustedAbi;
11747                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11748                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11749                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11750                        if (DEBUG_ABI_SELECTION) {
11751                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11752                                    + " (requirer="
11753                                    + (requirer != null ? requirer.pkg : "null")
11754                                    + ", scannedPackage="
11755                                    + (scannedPackage != null ? scannedPackage : "null")
11756                                    + ")");
11757                        }
11758                        if (changedAbiCodePath == null) {
11759                            changedAbiCodePath = new ArrayList<>();
11760                        }
11761                        changedAbiCodePath.add(ps.codePathString);
11762                    }
11763                }
11764            }
11765        }
11766        return changedAbiCodePath;
11767    }
11768
11769    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11770        synchronized (mPackages) {
11771            mResolverReplaced = true;
11772            // Set up information for custom user intent resolution activity.
11773            mResolveActivity.applicationInfo = pkg.applicationInfo;
11774            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11775            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11776            mResolveActivity.processName = pkg.applicationInfo.packageName;
11777            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11778            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11779                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11780            mResolveActivity.theme = 0;
11781            mResolveActivity.exported = true;
11782            mResolveActivity.enabled = true;
11783            mResolveInfo.activityInfo = mResolveActivity;
11784            mResolveInfo.priority = 0;
11785            mResolveInfo.preferredOrder = 0;
11786            mResolveInfo.match = 0;
11787            mResolveComponentName = mCustomResolverComponentName;
11788            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11789                    mResolveComponentName);
11790        }
11791    }
11792
11793    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11794        if (installerActivity == null) {
11795            if (DEBUG_INSTANT) {
11796                Slog.d(TAG, "Clear ephemeral installer activity");
11797            }
11798            mInstantAppInstallerActivity = null;
11799            return;
11800        }
11801
11802        if (DEBUG_INSTANT) {
11803            Slog.d(TAG, "Set ephemeral installer activity: "
11804                    + installerActivity.getComponentName());
11805        }
11806        // Set up information for ephemeral installer activity
11807        mInstantAppInstallerActivity = installerActivity;
11808        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11809                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11810        mInstantAppInstallerActivity.exported = true;
11811        mInstantAppInstallerActivity.enabled = true;
11812        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11813        mInstantAppInstallerInfo.priority = 1;
11814        mInstantAppInstallerInfo.preferredOrder = 1;
11815        mInstantAppInstallerInfo.isDefault = true;
11816        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11817                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11818    }
11819
11820    private static String calculateBundledApkRoot(final String codePathString) {
11821        final File codePath = new File(codePathString);
11822        final File codeRoot;
11823        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11824            codeRoot = Environment.getRootDirectory();
11825        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11826            codeRoot = Environment.getOemDirectory();
11827        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11828            codeRoot = Environment.getVendorDirectory();
11829        } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) {
11830            codeRoot = Environment.getOdmDirectory();
11831        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11832            codeRoot = Environment.getProductDirectory();
11833        } else {
11834            // Unrecognized code path; take its top real segment as the apk root:
11835            // e.g. /something/app/blah.apk => /something
11836            try {
11837                File f = codePath.getCanonicalFile();
11838                File parent = f.getParentFile();    // non-null because codePath is a file
11839                File tmp;
11840                while ((tmp = parent.getParentFile()) != null) {
11841                    f = parent;
11842                    parent = tmp;
11843                }
11844                codeRoot = f;
11845                Slog.w(TAG, "Unrecognized code path "
11846                        + codePath + " - using " + codeRoot);
11847            } catch (IOException e) {
11848                // Can't canonicalize the code path -- shenanigans?
11849                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11850                return Environment.getRootDirectory().getPath();
11851            }
11852        }
11853        return codeRoot.getPath();
11854    }
11855
11856    /**
11857     * Derive and set the location of native libraries for the given package,
11858     * which varies depending on where and how the package was installed.
11859     */
11860    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11861        final ApplicationInfo info = pkg.applicationInfo;
11862        final String codePath = pkg.codePath;
11863        final File codeFile = new File(codePath);
11864        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11865        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11866
11867        info.nativeLibraryRootDir = null;
11868        info.nativeLibraryRootRequiresIsa = false;
11869        info.nativeLibraryDir = null;
11870        info.secondaryNativeLibraryDir = null;
11871
11872        if (isApkFile(codeFile)) {
11873            // Monolithic install
11874            if (bundledApp) {
11875                // If "/system/lib64/apkname" exists, assume that is the per-package
11876                // native library directory to use; otherwise use "/system/lib/apkname".
11877                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11878                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11879                        getPrimaryInstructionSet(info));
11880
11881                // This is a bundled system app so choose the path based on the ABI.
11882                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11883                // is just the default path.
11884                final String apkName = deriveCodePathName(codePath);
11885                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11886                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11887                        apkName).getAbsolutePath();
11888
11889                if (info.secondaryCpuAbi != null) {
11890                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11891                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11892                            secondaryLibDir, apkName).getAbsolutePath();
11893                }
11894            } else if (asecApp) {
11895                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11896                        .getAbsolutePath();
11897            } else {
11898                final String apkName = deriveCodePathName(codePath);
11899                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11900                        .getAbsolutePath();
11901            }
11902
11903            info.nativeLibraryRootRequiresIsa = false;
11904            info.nativeLibraryDir = info.nativeLibraryRootDir;
11905        } else {
11906            // Cluster install
11907            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11908            info.nativeLibraryRootRequiresIsa = true;
11909
11910            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11911                    getPrimaryInstructionSet(info)).getAbsolutePath();
11912
11913            if (info.secondaryCpuAbi != null) {
11914                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11915                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11916            }
11917        }
11918    }
11919
11920    /**
11921     * Calculate the abis and roots for a bundled app. These can uniquely
11922     * be determined from the contents of the system partition, i.e whether
11923     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11924     * of this information, and instead assume that the system was built
11925     * sensibly.
11926     */
11927    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11928                                           PackageSetting pkgSetting) {
11929        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11930
11931        // If "/system/lib64/apkname" exists, assume that is the per-package
11932        // native library directory to use; otherwise use "/system/lib/apkname".
11933        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11934        setBundledAppAbi(pkg, apkRoot, apkName);
11935        // pkgSetting might be null during rescan following uninstall of updates
11936        // to a bundled app, so accommodate that possibility.  The settings in
11937        // that case will be established later from the parsed package.
11938        //
11939        // If the settings aren't null, sync them up with what we've just derived.
11940        // note that apkRoot isn't stored in the package settings.
11941        if (pkgSetting != null) {
11942            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11943            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11944        }
11945    }
11946
11947    /**
11948     * Deduces the ABI of a bundled app and sets the relevant fields on the
11949     * parsed pkg object.
11950     *
11951     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11952     *        under which system libraries are installed.
11953     * @param apkName the name of the installed package.
11954     */
11955    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11956        final File codeFile = new File(pkg.codePath);
11957
11958        final boolean has64BitLibs;
11959        final boolean has32BitLibs;
11960        if (isApkFile(codeFile)) {
11961            // Monolithic install
11962            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11963            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11964        } else {
11965            // Cluster install
11966            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11967            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11968                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11969                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11970                has64BitLibs = (new File(rootDir, isa)).exists();
11971            } else {
11972                has64BitLibs = false;
11973            }
11974            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11975                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11976                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11977                has32BitLibs = (new File(rootDir, isa)).exists();
11978            } else {
11979                has32BitLibs = false;
11980            }
11981        }
11982
11983        if (has64BitLibs && !has32BitLibs) {
11984            // The package has 64 bit libs, but not 32 bit libs. Its primary
11985            // ABI should be 64 bit. We can safely assume here that the bundled
11986            // native libraries correspond to the most preferred ABI in the list.
11987
11988            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11989            pkg.applicationInfo.secondaryCpuAbi = null;
11990        } else if (has32BitLibs && !has64BitLibs) {
11991            // The package has 32 bit libs but not 64 bit libs. Its primary
11992            // ABI should be 32 bit.
11993
11994            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11995            pkg.applicationInfo.secondaryCpuAbi = null;
11996        } else if (has32BitLibs && has64BitLibs) {
11997            // The application has both 64 and 32 bit bundled libraries. We check
11998            // here that the app declares multiArch support, and warn if it doesn't.
11999            //
12000            // We will be lenient here and record both ABIs. The primary will be the
12001            // ABI that's higher on the list, i.e, a device that's configured to prefer
12002            // 64 bit apps will see a 64 bit primary ABI,
12003
12004            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12005                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12006            }
12007
12008            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12009                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12010                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12011            } else {
12012                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12013                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12014            }
12015        } else {
12016            pkg.applicationInfo.primaryCpuAbi = null;
12017            pkg.applicationInfo.secondaryCpuAbi = null;
12018        }
12019    }
12020
12021    private void killApplication(String pkgName, int appId, String reason) {
12022        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12023    }
12024
12025    private void killApplication(String pkgName, int appId, int userId, String reason) {
12026        // Request the ActivityManager to kill the process(only for existing packages)
12027        // so that we do not end up in a confused state while the user is still using the older
12028        // version of the application while the new one gets installed.
12029        final long token = Binder.clearCallingIdentity();
12030        try {
12031            IActivityManager am = ActivityManager.getService();
12032            if (am != null) {
12033                try {
12034                    am.killApplication(pkgName, appId, userId, reason);
12035                } catch (RemoteException e) {
12036                }
12037            }
12038        } finally {
12039            Binder.restoreCallingIdentity(token);
12040        }
12041    }
12042
12043    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12044        // Remove the parent package setting
12045        PackageSetting ps = (PackageSetting) pkg.mExtras;
12046        if (ps != null) {
12047            removePackageLI(ps, chatty);
12048        }
12049        // Remove the child package setting
12050        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12051        for (int i = 0; i < childCount; i++) {
12052            PackageParser.Package childPkg = pkg.childPackages.get(i);
12053            ps = (PackageSetting) childPkg.mExtras;
12054            if (ps != null) {
12055                removePackageLI(ps, chatty);
12056            }
12057        }
12058    }
12059
12060    void removePackageLI(PackageSetting ps, boolean chatty) {
12061        if (DEBUG_INSTALL) {
12062            if (chatty)
12063                Log.d(TAG, "Removing package " + ps.name);
12064        }
12065
12066        // writer
12067        synchronized (mPackages) {
12068            mPackages.remove(ps.name);
12069            final PackageParser.Package pkg = ps.pkg;
12070            if (pkg != null) {
12071                cleanPackageDataStructuresLILPw(pkg, chatty);
12072            }
12073        }
12074    }
12075
12076    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12077        if (DEBUG_INSTALL) {
12078            if (chatty)
12079                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12080        }
12081
12082        // writer
12083        synchronized (mPackages) {
12084            // Remove the parent package
12085            mPackages.remove(pkg.applicationInfo.packageName);
12086            cleanPackageDataStructuresLILPw(pkg, chatty);
12087
12088            // Remove the child packages
12089            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12090            for (int i = 0; i < childCount; i++) {
12091                PackageParser.Package childPkg = pkg.childPackages.get(i);
12092                mPackages.remove(childPkg.applicationInfo.packageName);
12093                cleanPackageDataStructuresLILPw(childPkg, chatty);
12094            }
12095        }
12096    }
12097
12098    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12099        int N = pkg.providers.size();
12100        StringBuilder r = null;
12101        int i;
12102        for (i=0; i<N; i++) {
12103            PackageParser.Provider p = pkg.providers.get(i);
12104            mProviders.removeProvider(p);
12105            if (p.info.authority == null) {
12106
12107                /* There was another ContentProvider with this authority when
12108                 * this app was installed so this authority is null,
12109                 * Ignore it as we don't have to unregister the provider.
12110                 */
12111                continue;
12112            }
12113            String names[] = p.info.authority.split(";");
12114            for (int j = 0; j < names.length; j++) {
12115                if (mProvidersByAuthority.get(names[j]) == p) {
12116                    mProvidersByAuthority.remove(names[j]);
12117                    if (DEBUG_REMOVE) {
12118                        if (chatty)
12119                            Log.d(TAG, "Unregistered content provider: " + names[j]
12120                                    + ", className = " + p.info.name + ", isSyncable = "
12121                                    + p.info.isSyncable);
12122                    }
12123                }
12124            }
12125            if (DEBUG_REMOVE && chatty) {
12126                if (r == null) {
12127                    r = new StringBuilder(256);
12128                } else {
12129                    r.append(' ');
12130                }
12131                r.append(p.info.name);
12132            }
12133        }
12134        if (r != null) {
12135            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12136        }
12137
12138        N = pkg.services.size();
12139        r = null;
12140        for (i=0; i<N; i++) {
12141            PackageParser.Service s = pkg.services.get(i);
12142            mServices.removeService(s);
12143            if (chatty) {
12144                if (r == null) {
12145                    r = new StringBuilder(256);
12146                } else {
12147                    r.append(' ');
12148                }
12149                r.append(s.info.name);
12150            }
12151        }
12152        if (r != null) {
12153            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12154        }
12155
12156        N = pkg.receivers.size();
12157        r = null;
12158        for (i=0; i<N; i++) {
12159            PackageParser.Activity a = pkg.receivers.get(i);
12160            mReceivers.removeActivity(a, "receiver");
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, "  Receivers: " + r);
12172        }
12173
12174        N = pkg.activities.size();
12175        r = null;
12176        for (i=0; i<N; i++) {
12177            PackageParser.Activity a = pkg.activities.get(i);
12178            mActivities.removeActivity(a, "activity");
12179            if (DEBUG_REMOVE && chatty) {
12180                if (r == null) {
12181                    r = new StringBuilder(256);
12182                } else {
12183                    r.append(' ');
12184                }
12185                r.append(a.info.name);
12186            }
12187        }
12188        if (r != null) {
12189            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12190        }
12191
12192        mPermissionManager.removeAllPermissions(pkg, chatty);
12193
12194        N = pkg.instrumentation.size();
12195        r = null;
12196        for (i=0; i<N; i++) {
12197            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12198            mInstrumentation.remove(a.getComponentName());
12199            if (DEBUG_REMOVE && chatty) {
12200                if (r == null) {
12201                    r = new StringBuilder(256);
12202                } else {
12203                    r.append(' ');
12204                }
12205                r.append(a.info.name);
12206            }
12207        }
12208        if (r != null) {
12209            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12210        }
12211
12212        r = null;
12213        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12214            // Only system apps can hold shared libraries.
12215            if (pkg.libraryNames != null) {
12216                for (i = 0; i < pkg.libraryNames.size(); i++) {
12217                    String name = pkg.libraryNames.get(i);
12218                    if (removeSharedLibraryLPw(name, 0)) {
12219                        if (DEBUG_REMOVE && chatty) {
12220                            if (r == null) {
12221                                r = new StringBuilder(256);
12222                            } else {
12223                                r.append(' ');
12224                            }
12225                            r.append(name);
12226                        }
12227                    }
12228                }
12229            }
12230        }
12231
12232        r = null;
12233
12234        // Any package can hold static shared libraries.
12235        if (pkg.staticSharedLibName != null) {
12236            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12237                if (DEBUG_REMOVE && chatty) {
12238                    if (r == null) {
12239                        r = new StringBuilder(256);
12240                    } else {
12241                        r.append(' ');
12242                    }
12243                    r.append(pkg.staticSharedLibName);
12244                }
12245            }
12246        }
12247
12248        if (r != null) {
12249            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12250        }
12251    }
12252
12253
12254    final class ActivityIntentResolver
12255            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12256        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12257                boolean defaultOnly, int userId) {
12258            if (!sUserManager.exists(userId)) return null;
12259            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12260            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12261        }
12262
12263        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12264                int userId) {
12265            if (!sUserManager.exists(userId)) return null;
12266            mFlags = flags;
12267            return super.queryIntent(intent, resolvedType,
12268                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12269                    userId);
12270        }
12271
12272        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12273                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12274            if (!sUserManager.exists(userId)) return null;
12275            if (packageActivities == null) {
12276                return null;
12277            }
12278            mFlags = flags;
12279            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12280            final int N = packageActivities.size();
12281            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12282                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12283
12284            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12285            for (int i = 0; i < N; ++i) {
12286                intentFilters = packageActivities.get(i).intents;
12287                if (intentFilters != null && intentFilters.size() > 0) {
12288                    PackageParser.ActivityIntentInfo[] array =
12289                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12290                    intentFilters.toArray(array);
12291                    listCut.add(array);
12292                }
12293            }
12294            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12295        }
12296
12297        /**
12298         * Finds a privileged activity that matches the specified activity names.
12299         */
12300        private PackageParser.Activity findMatchingActivity(
12301                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12302            for (PackageParser.Activity sysActivity : activityList) {
12303                if (sysActivity.info.name.equals(activityInfo.name)) {
12304                    return sysActivity;
12305                }
12306                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12307                    return sysActivity;
12308                }
12309                if (sysActivity.info.targetActivity != null) {
12310                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12311                        return sysActivity;
12312                    }
12313                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12314                        return sysActivity;
12315                    }
12316                }
12317            }
12318            return null;
12319        }
12320
12321        public class IterGenerator<E> {
12322            public Iterator<E> generate(ActivityIntentInfo info) {
12323                return null;
12324            }
12325        }
12326
12327        public class ActionIterGenerator extends IterGenerator<String> {
12328            @Override
12329            public Iterator<String> generate(ActivityIntentInfo info) {
12330                return info.actionsIterator();
12331            }
12332        }
12333
12334        public class CategoriesIterGenerator extends IterGenerator<String> {
12335            @Override
12336            public Iterator<String> generate(ActivityIntentInfo info) {
12337                return info.categoriesIterator();
12338            }
12339        }
12340
12341        public class SchemesIterGenerator extends IterGenerator<String> {
12342            @Override
12343            public Iterator<String> generate(ActivityIntentInfo info) {
12344                return info.schemesIterator();
12345            }
12346        }
12347
12348        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12349            @Override
12350            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12351                return info.authoritiesIterator();
12352            }
12353        }
12354
12355        /**
12356         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12357         * MODIFIED. Do not pass in a list that should not be changed.
12358         */
12359        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12360                IterGenerator<T> generator, Iterator<T> searchIterator) {
12361            // loop through the set of actions; every one must be found in the intent filter
12362            while (searchIterator.hasNext()) {
12363                // we must have at least one filter in the list to consider a match
12364                if (intentList.size() == 0) {
12365                    break;
12366                }
12367
12368                final T searchAction = searchIterator.next();
12369
12370                // loop through the set of intent filters
12371                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12372                while (intentIter.hasNext()) {
12373                    final ActivityIntentInfo intentInfo = intentIter.next();
12374                    boolean selectionFound = false;
12375
12376                    // loop through the intent filter's selection criteria; at least one
12377                    // of them must match the searched criteria
12378                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12379                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12380                        final T intentSelection = intentSelectionIter.next();
12381                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12382                            selectionFound = true;
12383                            break;
12384                        }
12385                    }
12386
12387                    // the selection criteria wasn't found in this filter's set; this filter
12388                    // is not a potential match
12389                    if (!selectionFound) {
12390                        intentIter.remove();
12391                    }
12392                }
12393            }
12394        }
12395
12396        private boolean isProtectedAction(ActivityIntentInfo filter) {
12397            final Iterator<String> actionsIter = filter.actionsIterator();
12398            while (actionsIter != null && actionsIter.hasNext()) {
12399                final String filterAction = actionsIter.next();
12400                if (PROTECTED_ACTIONS.contains(filterAction)) {
12401                    return true;
12402                }
12403            }
12404            return false;
12405        }
12406
12407        /**
12408         * Adjusts the priority of the given intent filter according to policy.
12409         * <p>
12410         * <ul>
12411         * <li>The priority for non privileged applications is capped to '0'</li>
12412         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12413         * <li>The priority for unbundled updates to privileged applications is capped to the
12414         *      priority defined on the system partition</li>
12415         * </ul>
12416         * <p>
12417         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12418         * allowed to obtain any priority on any action.
12419         */
12420        private void adjustPriority(
12421                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12422            // nothing to do; priority is fine as-is
12423            if (intent.getPriority() <= 0) {
12424                return;
12425            }
12426
12427            final ActivityInfo activityInfo = intent.activity.info;
12428            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12429
12430            final boolean privilegedApp =
12431                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12432            if (!privilegedApp) {
12433                // non-privileged applications can never define a priority >0
12434                if (DEBUG_FILTERS) {
12435                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12436                            + " package: " + applicationInfo.packageName
12437                            + " activity: " + intent.activity.className
12438                            + " origPrio: " + intent.getPriority());
12439                }
12440                intent.setPriority(0);
12441                return;
12442            }
12443
12444            if (systemActivities == null) {
12445                // the system package is not disabled; we're parsing the system partition
12446                if (isProtectedAction(intent)) {
12447                    if (mDeferProtectedFilters) {
12448                        // We can't deal with these just yet. No component should ever obtain a
12449                        // >0 priority for a protected actions, with ONE exception -- the setup
12450                        // wizard. The setup wizard, however, cannot be known until we're able to
12451                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12452                        // until all intent filters have been processed. Chicken, meet egg.
12453                        // Let the filter temporarily have a high priority and rectify the
12454                        // priorities after all system packages have been scanned.
12455                        mProtectedFilters.add(intent);
12456                        if (DEBUG_FILTERS) {
12457                            Slog.i(TAG, "Protected action; save for later;"
12458                                    + " package: " + applicationInfo.packageName
12459                                    + " activity: " + intent.activity.className
12460                                    + " origPrio: " + intent.getPriority());
12461                        }
12462                        return;
12463                    } else {
12464                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12465                            Slog.i(TAG, "No setup wizard;"
12466                                + " All protected intents capped to priority 0");
12467                        }
12468                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12469                            if (DEBUG_FILTERS) {
12470                                Slog.i(TAG, "Found setup wizard;"
12471                                    + " allow priority " + intent.getPriority() + ";"
12472                                    + " package: " + intent.activity.info.packageName
12473                                    + " activity: " + intent.activity.className
12474                                    + " priority: " + intent.getPriority());
12475                            }
12476                            // setup wizard gets whatever it wants
12477                            return;
12478                        }
12479                        if (DEBUG_FILTERS) {
12480                            Slog.i(TAG, "Protected action; cap priority to 0;"
12481                                    + " package: " + intent.activity.info.packageName
12482                                    + " activity: " + intent.activity.className
12483                                    + " origPrio: " + intent.getPriority());
12484                        }
12485                        intent.setPriority(0);
12486                        return;
12487                    }
12488                }
12489                // privileged apps on the system image get whatever priority they request
12490                return;
12491            }
12492
12493            // privileged app unbundled update ... try to find the same activity
12494            final PackageParser.Activity foundActivity =
12495                    findMatchingActivity(systemActivities, activityInfo);
12496            if (foundActivity == null) {
12497                // this is a new activity; it cannot obtain >0 priority
12498                if (DEBUG_FILTERS) {
12499                    Slog.i(TAG, "New activity; cap priority to 0;"
12500                            + " package: " + applicationInfo.packageName
12501                            + " activity: " + intent.activity.className
12502                            + " origPrio: " + intent.getPriority());
12503                }
12504                intent.setPriority(0);
12505                return;
12506            }
12507
12508            // found activity, now check for filter equivalence
12509
12510            // a shallow copy is enough; we modify the list, not its contents
12511            final List<ActivityIntentInfo> intentListCopy =
12512                    new ArrayList<>(foundActivity.intents);
12513            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12514
12515            // find matching action subsets
12516            final Iterator<String> actionsIterator = intent.actionsIterator();
12517            if (actionsIterator != null) {
12518                getIntentListSubset(
12519                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12520                if (intentListCopy.size() == 0) {
12521                    // no more intents to match; we're not equivalent
12522                    if (DEBUG_FILTERS) {
12523                        Slog.i(TAG, "Mismatched action; 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 category subsets
12534            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12535            if (categoriesIterator != null) {
12536                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12537                        categoriesIterator);
12538                if (intentListCopy.size() == 0) {
12539                    // no more intents to match; we're not equivalent
12540                    if (DEBUG_FILTERS) {
12541                        Slog.i(TAG, "Mismatched category; 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 schemes subsets
12552            final Iterator<String> schemesIterator = intent.schemesIterator();
12553            if (schemesIterator != null) {
12554                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12555                        schemesIterator);
12556                if (intentListCopy.size() == 0) {
12557                    // no more intents to match; we're not equivalent
12558                    if (DEBUG_FILTERS) {
12559                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12560                                + " package: " + applicationInfo.packageName
12561                                + " activity: " + intent.activity.className
12562                                + " origPrio: " + intent.getPriority());
12563                    }
12564                    intent.setPriority(0);
12565                    return;
12566                }
12567            }
12568
12569            // find matching authorities subsets
12570            final Iterator<IntentFilter.AuthorityEntry>
12571                    authoritiesIterator = intent.authoritiesIterator();
12572            if (authoritiesIterator != null) {
12573                getIntentListSubset(intentListCopy,
12574                        new AuthoritiesIterGenerator(),
12575                        authoritiesIterator);
12576                if (intentListCopy.size() == 0) {
12577                    // no more intents to match; we're not equivalent
12578                    if (DEBUG_FILTERS) {
12579                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12580                                + " package: " + applicationInfo.packageName
12581                                + " activity: " + intent.activity.className
12582                                + " origPrio: " + intent.getPriority());
12583                    }
12584                    intent.setPriority(0);
12585                    return;
12586                }
12587            }
12588
12589            // we found matching filter(s); app gets the max priority of all intents
12590            int cappedPriority = 0;
12591            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12592                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12593            }
12594            if (intent.getPriority() > cappedPriority) {
12595                if (DEBUG_FILTERS) {
12596                    Slog.i(TAG, "Found matching filter(s);"
12597                            + " cap priority to " + cappedPriority + ";"
12598                            + " package: " + applicationInfo.packageName
12599                            + " activity: " + intent.activity.className
12600                            + " origPrio: " + intent.getPriority());
12601                }
12602                intent.setPriority(cappedPriority);
12603                return;
12604            }
12605            // all this for nothing; the requested priority was <= what was on the system
12606        }
12607
12608        public final void addActivity(PackageParser.Activity a, String type) {
12609            mActivities.put(a.getComponentName(), a);
12610            if (DEBUG_SHOW_INFO)
12611                Log.v(
12612                TAG, "  " + type + " " +
12613                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12614            if (DEBUG_SHOW_INFO)
12615                Log.v(TAG, "    Class=" + a.info.name);
12616            final int NI = a.intents.size();
12617            for (int j=0; j<NI; j++) {
12618                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12619                if ("activity".equals(type)) {
12620                    final PackageSetting ps =
12621                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12622                    final List<PackageParser.Activity> systemActivities =
12623                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12624                    adjustPriority(systemActivities, intent);
12625                }
12626                if (DEBUG_SHOW_INFO) {
12627                    Log.v(TAG, "    IntentFilter:");
12628                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12629                }
12630                if (!intent.debugCheck()) {
12631                    Log.w(TAG, "==> For Activity " + a.info.name);
12632                }
12633                addFilter(intent);
12634            }
12635        }
12636
12637        public final void removeActivity(PackageParser.Activity a, String type) {
12638            mActivities.remove(a.getComponentName());
12639            if (DEBUG_SHOW_INFO) {
12640                Log.v(TAG, "  " + type + " "
12641                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12642                                : a.info.name) + ":");
12643                Log.v(TAG, "    Class=" + a.info.name);
12644            }
12645            final int NI = a.intents.size();
12646            for (int j=0; j<NI; j++) {
12647                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12648                if (DEBUG_SHOW_INFO) {
12649                    Log.v(TAG, "    IntentFilter:");
12650                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12651                }
12652                removeFilter(intent);
12653            }
12654        }
12655
12656        @Override
12657        protected boolean allowFilterResult(
12658                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12659            ActivityInfo filterAi = filter.activity.info;
12660            for (int i=dest.size()-1; i>=0; i--) {
12661                ActivityInfo destAi = dest.get(i).activityInfo;
12662                if (destAi.name == filterAi.name
12663                        && destAi.packageName == filterAi.packageName) {
12664                    return false;
12665                }
12666            }
12667            return true;
12668        }
12669
12670        @Override
12671        protected ActivityIntentInfo[] newArray(int size) {
12672            return new ActivityIntentInfo[size];
12673        }
12674
12675        @Override
12676        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12677            if (!sUserManager.exists(userId)) return true;
12678            PackageParser.Package p = filter.activity.owner;
12679            if (p != null) {
12680                PackageSetting ps = (PackageSetting)p.mExtras;
12681                if (ps != null) {
12682                    // System apps are never considered stopped for purposes of
12683                    // filtering, because there may be no way for the user to
12684                    // actually re-launch them.
12685                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12686                            && ps.getStopped(userId);
12687                }
12688            }
12689            return false;
12690        }
12691
12692        @Override
12693        protected boolean isPackageForFilter(String packageName,
12694                PackageParser.ActivityIntentInfo info) {
12695            return packageName.equals(info.activity.owner.packageName);
12696        }
12697
12698        @Override
12699        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12700                int match, int userId) {
12701            if (!sUserManager.exists(userId)) return null;
12702            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12703                return null;
12704            }
12705            final PackageParser.Activity activity = info.activity;
12706            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12707            if (ps == null) {
12708                return null;
12709            }
12710            final PackageUserState userState = ps.readUserState(userId);
12711            ActivityInfo ai =
12712                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12713            if (ai == null) {
12714                return null;
12715            }
12716            final boolean matchExplicitlyVisibleOnly =
12717                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12718            final boolean matchVisibleToInstantApp =
12719                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12720            final boolean componentVisible =
12721                    matchVisibleToInstantApp
12722                    && info.isVisibleToInstantApp()
12723                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12724            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12725            // throw out filters that aren't visible to ephemeral apps
12726            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12727                return null;
12728            }
12729            // throw out instant app filters if we're not explicitly requesting them
12730            if (!matchInstantApp && userState.instantApp) {
12731                return null;
12732            }
12733            // throw out instant app filters if updates are available; will trigger
12734            // instant app resolution
12735            if (userState.instantApp && ps.isUpdateAvailable()) {
12736                return null;
12737            }
12738            final ResolveInfo res = new ResolveInfo();
12739            res.activityInfo = ai;
12740            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12741                res.filter = info;
12742            }
12743            if (info != null) {
12744                res.handleAllWebDataURI = info.handleAllWebDataURI();
12745            }
12746            res.priority = info.getPriority();
12747            res.preferredOrder = activity.owner.mPreferredOrder;
12748            //System.out.println("Result: " + res.activityInfo.className +
12749            //                   " = " + res.priority);
12750            res.match = match;
12751            res.isDefault = info.hasDefault;
12752            res.labelRes = info.labelRes;
12753            res.nonLocalizedLabel = info.nonLocalizedLabel;
12754            if (userNeedsBadging(userId)) {
12755                res.noResourceId = true;
12756            } else {
12757                res.icon = info.icon;
12758            }
12759            res.iconResourceId = info.icon;
12760            res.system = res.activityInfo.applicationInfo.isSystemApp();
12761            res.isInstantAppAvailable = userState.instantApp;
12762            return res;
12763        }
12764
12765        @Override
12766        protected void sortResults(List<ResolveInfo> results) {
12767            Collections.sort(results, mResolvePrioritySorter);
12768        }
12769
12770        @Override
12771        protected void dumpFilter(PrintWriter out, String prefix,
12772                PackageParser.ActivityIntentInfo filter) {
12773            out.print(prefix); out.print(
12774                    Integer.toHexString(System.identityHashCode(filter.activity)));
12775                    out.print(' ');
12776                    filter.activity.printComponentShortName(out);
12777                    out.print(" filter ");
12778                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12779        }
12780
12781        @Override
12782        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12783            return filter.activity;
12784        }
12785
12786        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12787            PackageParser.Activity activity = (PackageParser.Activity)label;
12788            out.print(prefix); out.print(
12789                    Integer.toHexString(System.identityHashCode(activity)));
12790                    out.print(' ');
12791                    activity.printComponentShortName(out);
12792            if (count > 1) {
12793                out.print(" ("); out.print(count); out.print(" filters)");
12794            }
12795            out.println();
12796        }
12797
12798        // Keys are String (activity class name), values are Activity.
12799        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12800                = new ArrayMap<ComponentName, PackageParser.Activity>();
12801        private int mFlags;
12802    }
12803
12804    private final class ServiceIntentResolver
12805            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12806        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12807                boolean defaultOnly, int userId) {
12808            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12809            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12810        }
12811
12812        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12813                int userId) {
12814            if (!sUserManager.exists(userId)) return null;
12815            mFlags = flags;
12816            return super.queryIntent(intent, resolvedType,
12817                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12818                    userId);
12819        }
12820
12821        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12822                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12823            if (!sUserManager.exists(userId)) return null;
12824            if (packageServices == null) {
12825                return null;
12826            }
12827            mFlags = flags;
12828            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12829            final int N = packageServices.size();
12830            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12831                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12832
12833            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12834            for (int i = 0; i < N; ++i) {
12835                intentFilters = packageServices.get(i).intents;
12836                if (intentFilters != null && intentFilters.size() > 0) {
12837                    PackageParser.ServiceIntentInfo[] array =
12838                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12839                    intentFilters.toArray(array);
12840                    listCut.add(array);
12841                }
12842            }
12843            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12844        }
12845
12846        public final void addService(PackageParser.Service s) {
12847            mServices.put(s.getComponentName(), s);
12848            if (DEBUG_SHOW_INFO) {
12849                Log.v(TAG, "  "
12850                        + (s.info.nonLocalizedLabel != null
12851                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12852                Log.v(TAG, "    Class=" + s.info.name);
12853            }
12854            final int NI = s.intents.size();
12855            int j;
12856            for (j=0; j<NI; j++) {
12857                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12858                if (DEBUG_SHOW_INFO) {
12859                    Log.v(TAG, "    IntentFilter:");
12860                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12861                }
12862                if (!intent.debugCheck()) {
12863                    Log.w(TAG, "==> For Service " + s.info.name);
12864                }
12865                addFilter(intent);
12866            }
12867        }
12868
12869        public final void removeService(PackageParser.Service s) {
12870            mServices.remove(s.getComponentName());
12871            if (DEBUG_SHOW_INFO) {
12872                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12873                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12874                Log.v(TAG, "    Class=" + s.info.name);
12875            }
12876            final int NI = s.intents.size();
12877            int j;
12878            for (j=0; j<NI; j++) {
12879                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12880                if (DEBUG_SHOW_INFO) {
12881                    Log.v(TAG, "    IntentFilter:");
12882                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12883                }
12884                removeFilter(intent);
12885            }
12886        }
12887
12888        @Override
12889        protected boolean allowFilterResult(
12890                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12891            ServiceInfo filterSi = filter.service.info;
12892            for (int i=dest.size()-1; i>=0; i--) {
12893                ServiceInfo destAi = dest.get(i).serviceInfo;
12894                if (destAi.name == filterSi.name
12895                        && destAi.packageName == filterSi.packageName) {
12896                    return false;
12897                }
12898            }
12899            return true;
12900        }
12901
12902        @Override
12903        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12904            return new PackageParser.ServiceIntentInfo[size];
12905        }
12906
12907        @Override
12908        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12909            if (!sUserManager.exists(userId)) return true;
12910            PackageParser.Package p = filter.service.owner;
12911            if (p != null) {
12912                PackageSetting ps = (PackageSetting)p.mExtras;
12913                if (ps != null) {
12914                    // System apps are never considered stopped for purposes of
12915                    // filtering, because there may be no way for the user to
12916                    // actually re-launch them.
12917                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12918                            && ps.getStopped(userId);
12919                }
12920            }
12921            return false;
12922        }
12923
12924        @Override
12925        protected boolean isPackageForFilter(String packageName,
12926                PackageParser.ServiceIntentInfo info) {
12927            return packageName.equals(info.service.owner.packageName);
12928        }
12929
12930        @Override
12931        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12932                int match, int userId) {
12933            if (!sUserManager.exists(userId)) return null;
12934            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12935            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12936                return null;
12937            }
12938            final PackageParser.Service service = info.service;
12939            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12940            if (ps == null) {
12941                return null;
12942            }
12943            final PackageUserState userState = ps.readUserState(userId);
12944            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12945                    userState, userId);
12946            if (si == null) {
12947                return null;
12948            }
12949            final boolean matchVisibleToInstantApp =
12950                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12951            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12952            // throw out filters that aren't visible to ephemeral apps
12953            if (matchVisibleToInstantApp
12954                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12955                return null;
12956            }
12957            // throw out ephemeral filters if we're not explicitly requesting them
12958            if (!isInstantApp && userState.instantApp) {
12959                return null;
12960            }
12961            // throw out instant app filters if updates are available; will trigger
12962            // instant app resolution
12963            if (userState.instantApp && ps.isUpdateAvailable()) {
12964                return null;
12965            }
12966            final ResolveInfo res = new ResolveInfo();
12967            res.serviceInfo = si;
12968            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12969                res.filter = filter;
12970            }
12971            res.priority = info.getPriority();
12972            res.preferredOrder = service.owner.mPreferredOrder;
12973            res.match = match;
12974            res.isDefault = info.hasDefault;
12975            res.labelRes = info.labelRes;
12976            res.nonLocalizedLabel = info.nonLocalizedLabel;
12977            res.icon = info.icon;
12978            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12979            return res;
12980        }
12981
12982        @Override
12983        protected void sortResults(List<ResolveInfo> results) {
12984            Collections.sort(results, mResolvePrioritySorter);
12985        }
12986
12987        @Override
12988        protected void dumpFilter(PrintWriter out, String prefix,
12989                PackageParser.ServiceIntentInfo filter) {
12990            out.print(prefix); out.print(
12991                    Integer.toHexString(System.identityHashCode(filter.service)));
12992                    out.print(' ');
12993                    filter.service.printComponentShortName(out);
12994                    out.print(" filter ");
12995                    out.print(Integer.toHexString(System.identityHashCode(filter)));
12996                    if (filter.service.info.permission != null) {
12997                        out.print(" permission "); out.println(filter.service.info.permission);
12998                    } else {
12999                        out.println();
13000                    }
13001        }
13002
13003        @Override
13004        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13005            return filter.service;
13006        }
13007
13008        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13009            PackageParser.Service service = (PackageParser.Service)label;
13010            out.print(prefix); out.print(
13011                    Integer.toHexString(System.identityHashCode(service)));
13012                    out.print(' ');
13013                    service.printComponentShortName(out);
13014            if (count > 1) {
13015                out.print(" ("); out.print(count); out.print(" filters)");
13016            }
13017            out.println();
13018        }
13019
13020//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13021//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13022//            final List<ResolveInfo> retList = Lists.newArrayList();
13023//            while (i.hasNext()) {
13024//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13025//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13026//                    retList.add(resolveInfo);
13027//                }
13028//            }
13029//            return retList;
13030//        }
13031
13032        // Keys are String (activity class name), values are Activity.
13033        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13034                = new ArrayMap<ComponentName, PackageParser.Service>();
13035        private int mFlags;
13036    }
13037
13038    private final class ProviderIntentResolver
13039            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13040        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13041                boolean defaultOnly, int userId) {
13042            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13043            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13044        }
13045
13046        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13047                int userId) {
13048            if (!sUserManager.exists(userId))
13049                return null;
13050            mFlags = flags;
13051            return super.queryIntent(intent, resolvedType,
13052                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13053                    userId);
13054        }
13055
13056        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13057                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13058            if (!sUserManager.exists(userId))
13059                return null;
13060            if (packageProviders == null) {
13061                return null;
13062            }
13063            mFlags = flags;
13064            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13065            final int N = packageProviders.size();
13066            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13067                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13068
13069            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13070            for (int i = 0; i < N; ++i) {
13071                intentFilters = packageProviders.get(i).intents;
13072                if (intentFilters != null && intentFilters.size() > 0) {
13073                    PackageParser.ProviderIntentInfo[] array =
13074                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13075                    intentFilters.toArray(array);
13076                    listCut.add(array);
13077                }
13078            }
13079            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13080        }
13081
13082        public final void addProvider(PackageParser.Provider p) {
13083            if (mProviders.containsKey(p.getComponentName())) {
13084                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13085                return;
13086            }
13087
13088            mProviders.put(p.getComponentName(), p);
13089            if (DEBUG_SHOW_INFO) {
13090                Log.v(TAG, "  "
13091                        + (p.info.nonLocalizedLabel != null
13092                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13093                Log.v(TAG, "    Class=" + p.info.name);
13094            }
13095            final int NI = p.intents.size();
13096            int j;
13097            for (j = 0; j < NI; j++) {
13098                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13099                if (DEBUG_SHOW_INFO) {
13100                    Log.v(TAG, "    IntentFilter:");
13101                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13102                }
13103                if (!intent.debugCheck()) {
13104                    Log.w(TAG, "==> For Provider " + p.info.name);
13105                }
13106                addFilter(intent);
13107            }
13108        }
13109
13110        public final void removeProvider(PackageParser.Provider p) {
13111            mProviders.remove(p.getComponentName());
13112            if (DEBUG_SHOW_INFO) {
13113                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13114                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13115                Log.v(TAG, "    Class=" + p.info.name);
13116            }
13117            final int NI = p.intents.size();
13118            int j;
13119            for (j = 0; j < NI; j++) {
13120                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13121                if (DEBUG_SHOW_INFO) {
13122                    Log.v(TAG, "    IntentFilter:");
13123                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13124                }
13125                removeFilter(intent);
13126            }
13127        }
13128
13129        @Override
13130        protected boolean allowFilterResult(
13131                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13132            ProviderInfo filterPi = filter.provider.info;
13133            for (int i = dest.size() - 1; i >= 0; i--) {
13134                ProviderInfo destPi = dest.get(i).providerInfo;
13135                if (destPi.name == filterPi.name
13136                        && destPi.packageName == filterPi.packageName) {
13137                    return false;
13138                }
13139            }
13140            return true;
13141        }
13142
13143        @Override
13144        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13145            return new PackageParser.ProviderIntentInfo[size];
13146        }
13147
13148        @Override
13149        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13150            if (!sUserManager.exists(userId))
13151                return true;
13152            PackageParser.Package p = filter.provider.owner;
13153            if (p != null) {
13154                PackageSetting ps = (PackageSetting) p.mExtras;
13155                if (ps != null) {
13156                    // System apps are never considered stopped for purposes of
13157                    // filtering, because there may be no way for the user to
13158                    // actually re-launch them.
13159                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13160                            && ps.getStopped(userId);
13161                }
13162            }
13163            return false;
13164        }
13165
13166        @Override
13167        protected boolean isPackageForFilter(String packageName,
13168                PackageParser.ProviderIntentInfo info) {
13169            return packageName.equals(info.provider.owner.packageName);
13170        }
13171
13172        @Override
13173        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13174                int match, int userId) {
13175            if (!sUserManager.exists(userId))
13176                return null;
13177            final PackageParser.ProviderIntentInfo info = filter;
13178            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13179                return null;
13180            }
13181            final PackageParser.Provider provider = info.provider;
13182            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13183            if (ps == null) {
13184                return null;
13185            }
13186            final PackageUserState userState = ps.readUserState(userId);
13187            final boolean matchVisibleToInstantApp =
13188                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13189            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13190            // throw out filters that aren't visible to instant applications
13191            if (matchVisibleToInstantApp
13192                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13193                return null;
13194            }
13195            // throw out instant application filters if we're not explicitly requesting them
13196            if (!isInstantApp && userState.instantApp) {
13197                return null;
13198            }
13199            // throw out instant application filters if updates are available; will trigger
13200            // instant application resolution
13201            if (userState.instantApp && ps.isUpdateAvailable()) {
13202                return null;
13203            }
13204            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13205                    userState, userId);
13206            if (pi == null) {
13207                return null;
13208            }
13209            final ResolveInfo res = new ResolveInfo();
13210            res.providerInfo = pi;
13211            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13212                res.filter = filter;
13213            }
13214            res.priority = info.getPriority();
13215            res.preferredOrder = provider.owner.mPreferredOrder;
13216            res.match = match;
13217            res.isDefault = info.hasDefault;
13218            res.labelRes = info.labelRes;
13219            res.nonLocalizedLabel = info.nonLocalizedLabel;
13220            res.icon = info.icon;
13221            res.system = res.providerInfo.applicationInfo.isSystemApp();
13222            return res;
13223        }
13224
13225        @Override
13226        protected void sortResults(List<ResolveInfo> results) {
13227            Collections.sort(results, mResolvePrioritySorter);
13228        }
13229
13230        @Override
13231        protected void dumpFilter(PrintWriter out, String prefix,
13232                PackageParser.ProviderIntentInfo filter) {
13233            out.print(prefix);
13234            out.print(
13235                    Integer.toHexString(System.identityHashCode(filter.provider)));
13236            out.print(' ');
13237            filter.provider.printComponentShortName(out);
13238            out.print(" filter ");
13239            out.println(Integer.toHexString(System.identityHashCode(filter)));
13240        }
13241
13242        @Override
13243        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13244            return filter.provider;
13245        }
13246
13247        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13248            PackageParser.Provider provider = (PackageParser.Provider)label;
13249            out.print(prefix); out.print(
13250                    Integer.toHexString(System.identityHashCode(provider)));
13251                    out.print(' ');
13252                    provider.printComponentShortName(out);
13253            if (count > 1) {
13254                out.print(" ("); out.print(count); out.print(" filters)");
13255            }
13256            out.println();
13257        }
13258
13259        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13260                = new ArrayMap<ComponentName, PackageParser.Provider>();
13261        private int mFlags;
13262    }
13263
13264    static final class InstantAppIntentResolver
13265            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13266            AuxiliaryResolveInfo.AuxiliaryFilter> {
13267        /**
13268         * The result that has the highest defined order. Ordering applies on a
13269         * per-package basis. Mapping is from package name to Pair of order and
13270         * EphemeralResolveInfo.
13271         * <p>
13272         * NOTE: This is implemented as a field variable for convenience and efficiency.
13273         * By having a field variable, we're able to track filter ordering as soon as
13274         * a non-zero order is defined. Otherwise, multiple loops across the result set
13275         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13276         * this needs to be contained entirely within {@link #filterResults}.
13277         */
13278        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13279
13280        @Override
13281        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13282            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13283        }
13284
13285        @Override
13286        protected boolean isPackageForFilter(String packageName,
13287                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13288            return true;
13289        }
13290
13291        @Override
13292        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13293                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13294            if (!sUserManager.exists(userId)) {
13295                return null;
13296            }
13297            final String packageName = responseObj.resolveInfo.getPackageName();
13298            final Integer order = responseObj.getOrder();
13299            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13300                    mOrderResult.get(packageName);
13301            // ordering is enabled and this item's order isn't high enough
13302            if (lastOrderResult != null && lastOrderResult.first >= order) {
13303                return null;
13304            }
13305            final InstantAppResolveInfo res = responseObj.resolveInfo;
13306            if (order > 0) {
13307                // non-zero order, enable ordering
13308                mOrderResult.put(packageName, new Pair<>(order, res));
13309            }
13310            return responseObj;
13311        }
13312
13313        @Override
13314        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13315            // only do work if ordering is enabled [most of the time it won't be]
13316            if (mOrderResult.size() == 0) {
13317                return;
13318            }
13319            int resultSize = results.size();
13320            for (int i = 0; i < resultSize; i++) {
13321                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13322                final String packageName = info.getPackageName();
13323                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13324                if (savedInfo == null) {
13325                    // package doesn't having ordering
13326                    continue;
13327                }
13328                if (savedInfo.second == info) {
13329                    // circled back to the highest ordered item; remove from order list
13330                    mOrderResult.remove(packageName);
13331                    if (mOrderResult.size() == 0) {
13332                        // no more ordered items
13333                        break;
13334                    }
13335                    continue;
13336                }
13337                // item has a worse order, remove it from the result list
13338                results.remove(i);
13339                resultSize--;
13340                i--;
13341            }
13342        }
13343    }
13344
13345    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13346            new Comparator<ResolveInfo>() {
13347        public int compare(ResolveInfo r1, ResolveInfo r2) {
13348            int v1 = r1.priority;
13349            int v2 = r2.priority;
13350            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13351            if (v1 != v2) {
13352                return (v1 > v2) ? -1 : 1;
13353            }
13354            v1 = r1.preferredOrder;
13355            v2 = r2.preferredOrder;
13356            if (v1 != v2) {
13357                return (v1 > v2) ? -1 : 1;
13358            }
13359            if (r1.isDefault != r2.isDefault) {
13360                return r1.isDefault ? -1 : 1;
13361            }
13362            v1 = r1.match;
13363            v2 = r2.match;
13364            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13365            if (v1 != v2) {
13366                return (v1 > v2) ? -1 : 1;
13367            }
13368            if (r1.system != r2.system) {
13369                return r1.system ? -1 : 1;
13370            }
13371            if (r1.activityInfo != null) {
13372                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13373            }
13374            if (r1.serviceInfo != null) {
13375                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13376            }
13377            if (r1.providerInfo != null) {
13378                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13379            }
13380            return 0;
13381        }
13382    };
13383
13384    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13385            new Comparator<ProviderInfo>() {
13386        public int compare(ProviderInfo p1, ProviderInfo p2) {
13387            final int v1 = p1.initOrder;
13388            final int v2 = p2.initOrder;
13389            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13390        }
13391    };
13392
13393    @Override
13394    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13395            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13396            final int[] userIds, int[] instantUserIds) {
13397        mHandler.post(new Runnable() {
13398            @Override
13399            public void run() {
13400                try {
13401                    final IActivityManager am = ActivityManager.getService();
13402                    if (am == null) return;
13403                    final int[] resolvedUserIds;
13404                    if (userIds == null) {
13405                        resolvedUserIds = am.getRunningUserIds();
13406                    } else {
13407                        resolvedUserIds = userIds;
13408                    }
13409                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13410                            resolvedUserIds, false);
13411                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13412                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13413                                instantUserIds, true);
13414                    }
13415                } catch (RemoteException ex) {
13416                }
13417            }
13418        });
13419    }
13420
13421    @Override
13422    public void notifyPackageAdded(String packageName) {
13423        final PackageListObserver[] observers;
13424        synchronized (mPackages) {
13425            if (mPackageListObservers.size() == 0) {
13426                return;
13427            }
13428            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13429        }
13430        for (int i = observers.length - 1; i >= 0; --i) {
13431            observers[i].onPackageAdded(packageName);
13432        }
13433    }
13434
13435    @Override
13436    public void notifyPackageRemoved(String packageName) {
13437        final PackageListObserver[] observers;
13438        synchronized (mPackages) {
13439            if (mPackageListObservers.size() == 0) {
13440                return;
13441            }
13442            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13443        }
13444        for (int i = observers.length - 1; i >= 0; --i) {
13445            observers[i].onPackageRemoved(packageName);
13446        }
13447    }
13448
13449    /**
13450     * Sends a broadcast for the given action.
13451     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13452     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13453     * the system and applications allowed to see instant applications to receive package
13454     * lifecycle events for instant applications.
13455     */
13456    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13457            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13458            int[] userIds, boolean isInstantApp)
13459                    throws RemoteException {
13460        for (int id : userIds) {
13461            final Intent intent = new Intent(action,
13462                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13463            final String[] requiredPermissions =
13464                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13465            if (extras != null) {
13466                intent.putExtras(extras);
13467            }
13468            if (targetPkg != null) {
13469                intent.setPackage(targetPkg);
13470            }
13471            // Modify the UID when posting to other users
13472            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13473            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13474                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13475                intent.putExtra(Intent.EXTRA_UID, uid);
13476            }
13477            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13478            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13479            if (DEBUG_BROADCASTS) {
13480                RuntimeException here = new RuntimeException("here");
13481                here.fillInStackTrace();
13482                Slog.d(TAG, "Sending to user " + id + ": "
13483                        + intent.toShortString(false, true, false, false)
13484                        + " " + intent.getExtras(), here);
13485            }
13486            am.broadcastIntent(null, intent, null, finishedReceiver,
13487                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13488                    null, finishedReceiver != null, false, id);
13489        }
13490    }
13491
13492    /**
13493     * Check if the external storage media is available. This is true if there
13494     * is a mounted external storage medium or if the external storage is
13495     * emulated.
13496     */
13497    private boolean isExternalMediaAvailable() {
13498        return mMediaMounted || Environment.isExternalStorageEmulated();
13499    }
13500
13501    @Override
13502    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13503        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13504            return null;
13505        }
13506        if (!isExternalMediaAvailable()) {
13507                // If the external storage is no longer mounted at this point,
13508                // the caller may not have been able to delete all of this
13509                // packages files and can not delete any more.  Bail.
13510            return null;
13511        }
13512        synchronized (mPackages) {
13513            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13514            if (lastPackage != null) {
13515                pkgs.remove(lastPackage);
13516            }
13517            if (pkgs.size() > 0) {
13518                return pkgs.get(0);
13519            }
13520        }
13521        return null;
13522    }
13523
13524    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13525        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13526                userId, andCode ? 1 : 0, packageName);
13527        if (mSystemReady) {
13528            msg.sendToTarget();
13529        } else {
13530            if (mPostSystemReadyMessages == null) {
13531                mPostSystemReadyMessages = new ArrayList<>();
13532            }
13533            mPostSystemReadyMessages.add(msg);
13534        }
13535    }
13536
13537    void startCleaningPackages() {
13538        // reader
13539        if (!isExternalMediaAvailable()) {
13540            return;
13541        }
13542        synchronized (mPackages) {
13543            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13544                return;
13545            }
13546        }
13547        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13548        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13549        IActivityManager am = ActivityManager.getService();
13550        if (am != null) {
13551            int dcsUid = -1;
13552            synchronized (mPackages) {
13553                if (!mDefaultContainerWhitelisted) {
13554                    mDefaultContainerWhitelisted = true;
13555                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13556                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13557                }
13558            }
13559            try {
13560                if (dcsUid > 0) {
13561                    am.backgroundWhitelistUid(dcsUid);
13562                }
13563                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13564                        UserHandle.USER_SYSTEM);
13565            } catch (RemoteException e) {
13566            }
13567        }
13568    }
13569
13570    /**
13571     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13572     * it is acting on behalf on an enterprise or the user).
13573     *
13574     * Note that the ordering of the conditionals in this method is important. The checks we perform
13575     * are as follows, in this order:
13576     *
13577     * 1) If the install is being performed by a system app, we can trust the app to have set the
13578     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13579     *    what it is.
13580     * 2) If the install is being performed by a device or profile owner app, the install reason
13581     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13582     *    set the install reason correctly. If the app targets an older SDK version where install
13583     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13584     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13585     * 3) In all other cases, the install is being performed by a regular app that is neither part
13586     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13587     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13588     *    set to enterprise policy and if so, change it to unknown instead.
13589     */
13590    private int fixUpInstallReason(String installerPackageName, int installerUid,
13591            int installReason) {
13592        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13593                == PERMISSION_GRANTED) {
13594            // If the install is being performed by a system app, we trust that app to have set the
13595            // install reason correctly.
13596            return installReason;
13597        }
13598
13599        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13600            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13601        if (dpm != null) {
13602            ComponentName owner = null;
13603            try {
13604                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13605                if (owner == null) {
13606                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13607                }
13608            } catch (RemoteException e) {
13609            }
13610            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13611                // If the install is being performed by a device or profile owner, the install
13612                // reason should be enterprise policy.
13613                return PackageManager.INSTALL_REASON_POLICY;
13614            }
13615        }
13616
13617        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13618            // If the install is being performed by a regular app (i.e. neither system app nor
13619            // device or profile owner), we have no reason to believe that the app is acting on
13620            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13621            // change it to unknown instead.
13622            return PackageManager.INSTALL_REASON_UNKNOWN;
13623        }
13624
13625        // If the install is being performed by a regular app and the install reason was set to any
13626        // value but enterprise policy, leave the install reason unchanged.
13627        return installReason;
13628    }
13629
13630    void installStage(String packageName, File stagedDir,
13631            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13632            String installerPackageName, int installerUid, UserHandle user,
13633            PackageParser.SigningDetails signingDetails) {
13634        if (DEBUG_INSTANT) {
13635            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13636                Slog.d(TAG, "Ephemeral install of " + packageName);
13637            }
13638        }
13639        final VerificationInfo verificationInfo = new VerificationInfo(
13640                sessionParams.originatingUri, sessionParams.referrerUri,
13641                sessionParams.originatingUid, installerUid);
13642
13643        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13644
13645        final Message msg = mHandler.obtainMessage(INIT_COPY);
13646        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13647                sessionParams.installReason);
13648        final InstallParams params = new InstallParams(origin, null, observer,
13649                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13650                verificationInfo, user, sessionParams.abiOverride,
13651                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13652        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13653        msg.obj = params;
13654
13655        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13656                System.identityHashCode(msg.obj));
13657        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13658                System.identityHashCode(msg.obj));
13659
13660        mHandler.sendMessage(msg);
13661    }
13662
13663    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13664            int userId) {
13665        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13666        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13667        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13668        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13669        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13670                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13671
13672        // Send a session commit broadcast
13673        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13674        info.installReason = pkgSetting.getInstallReason(userId);
13675        info.appPackageName = packageName;
13676        sendSessionCommitBroadcast(info, userId);
13677    }
13678
13679    @Override
13680    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13681            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13682        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13683            return;
13684        }
13685        Bundle extras = new Bundle(1);
13686        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13687        final int uid = UserHandle.getUid(
13688                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13689        extras.putInt(Intent.EXTRA_UID, uid);
13690
13691        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13692                packageName, extras, 0, null, null, userIds, instantUserIds);
13693        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13694            mHandler.post(() -> {
13695                        for (int userId : userIds) {
13696                            sendBootCompletedBroadcastToSystemApp(
13697                                    packageName, includeStopped, userId);
13698                        }
13699                    }
13700            );
13701        }
13702    }
13703
13704    /**
13705     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13706     * automatically without needing an explicit launch.
13707     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13708     */
13709    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13710            int userId) {
13711        // If user is not running, the app didn't miss any broadcast
13712        if (!mUserManagerInternal.isUserRunning(userId)) {
13713            return;
13714        }
13715        final IActivityManager am = ActivityManager.getService();
13716        try {
13717            // Deliver LOCKED_BOOT_COMPLETED first
13718            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13719                    .setPackage(packageName);
13720            if (includeStopped) {
13721                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13722            }
13723            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13724            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13725                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13726
13727            // Deliver BOOT_COMPLETED only if user is unlocked
13728            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13729                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13730                if (includeStopped) {
13731                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13732                }
13733                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13734                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13735            }
13736        } catch (RemoteException e) {
13737            throw e.rethrowFromSystemServer();
13738        }
13739    }
13740
13741    @Override
13742    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13743            int userId) {
13744        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13745        PackageSetting pkgSetting;
13746        final int callingUid = Binder.getCallingUid();
13747        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13748                true /* requireFullPermission */, true /* checkShell */,
13749                "setApplicationHiddenSetting for user " + userId);
13750
13751        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13752            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13753            return false;
13754        }
13755
13756        long callingId = Binder.clearCallingIdentity();
13757        try {
13758            boolean sendAdded = false;
13759            boolean sendRemoved = false;
13760            // writer
13761            synchronized (mPackages) {
13762                pkgSetting = mSettings.mPackages.get(packageName);
13763                if (pkgSetting == null) {
13764                    return false;
13765                }
13766                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13767                    return false;
13768                }
13769                // Do not allow "android" is being disabled
13770                if ("android".equals(packageName)) {
13771                    Slog.w(TAG, "Cannot hide package: android");
13772                    return false;
13773                }
13774                // Cannot hide static shared libs as they are considered
13775                // a part of the using app (emulating static linking). Also
13776                // static libs are installed always on internal storage.
13777                PackageParser.Package pkg = mPackages.get(packageName);
13778                if (pkg != null && pkg.staticSharedLibName != null) {
13779                    Slog.w(TAG, "Cannot hide package: " + packageName
13780                            + " providing static shared library: "
13781                            + pkg.staticSharedLibName);
13782                    return false;
13783                }
13784                // Only allow protected packages to hide themselves.
13785                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13786                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13787                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13788                    return false;
13789                }
13790
13791                if (pkgSetting.getHidden(userId) != hidden) {
13792                    pkgSetting.setHidden(hidden, userId);
13793                    mSettings.writePackageRestrictionsLPr(userId);
13794                    if (hidden) {
13795                        sendRemoved = true;
13796                    } else {
13797                        sendAdded = true;
13798                    }
13799                }
13800            }
13801            if (sendAdded) {
13802                sendPackageAddedForUser(packageName, pkgSetting, userId);
13803                return true;
13804            }
13805            if (sendRemoved) {
13806                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13807                        "hiding pkg");
13808                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13809                return true;
13810            }
13811        } finally {
13812            Binder.restoreCallingIdentity(callingId);
13813        }
13814        return false;
13815    }
13816
13817    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13818            int userId) {
13819        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13820        info.removedPackage = packageName;
13821        info.installerPackageName = pkgSetting.installerPackageName;
13822        info.removedUsers = new int[] {userId};
13823        info.broadcastUsers = new int[] {userId};
13824        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13825        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13826    }
13827
13828    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13829        if (pkgList.length > 0) {
13830            Bundle extras = new Bundle(1);
13831            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13832
13833            sendPackageBroadcast(
13834                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13835                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13836                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13837                    new int[] {userId}, null);
13838        }
13839    }
13840
13841    /**
13842     * Returns true if application is not found or there was an error. Otherwise it returns
13843     * the hidden state of the package for the given user.
13844     */
13845    @Override
13846    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13847        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13848        final int callingUid = Binder.getCallingUid();
13849        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13850                true /* requireFullPermission */, false /* checkShell */,
13851                "getApplicationHidden for user " + userId);
13852        PackageSetting ps;
13853        long callingId = Binder.clearCallingIdentity();
13854        try {
13855            // writer
13856            synchronized (mPackages) {
13857                ps = mSettings.mPackages.get(packageName);
13858                if (ps == null) {
13859                    return true;
13860                }
13861                if (filterAppAccessLPr(ps, callingUid, userId)) {
13862                    return true;
13863                }
13864                return ps.getHidden(userId);
13865            }
13866        } finally {
13867            Binder.restoreCallingIdentity(callingId);
13868        }
13869    }
13870
13871    /**
13872     * @hide
13873     */
13874    @Override
13875    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13876            int installReason) {
13877        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13878                null);
13879        PackageSetting pkgSetting;
13880        final int callingUid = Binder.getCallingUid();
13881        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13882                true /* requireFullPermission */, true /* checkShell */,
13883                "installExistingPackage for user " + userId);
13884        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13885            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13886        }
13887
13888        long callingId = Binder.clearCallingIdentity();
13889        try {
13890            boolean installed = false;
13891            final boolean instantApp =
13892                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13893            final boolean fullApp =
13894                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13895
13896            // writer
13897            synchronized (mPackages) {
13898                pkgSetting = mSettings.mPackages.get(packageName);
13899                if (pkgSetting == null) {
13900                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13901                }
13902                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13903                    // only allow the existing package to be used if it's installed as a full
13904                    // application for at least one user
13905                    boolean installAllowed = false;
13906                    for (int checkUserId : sUserManager.getUserIds()) {
13907                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13908                        if (installAllowed) {
13909                            break;
13910                        }
13911                    }
13912                    if (!installAllowed) {
13913                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13914                    }
13915                }
13916                if (!pkgSetting.getInstalled(userId)) {
13917                    pkgSetting.setInstalled(true, userId);
13918                    pkgSetting.setHidden(false, userId);
13919                    pkgSetting.setInstallReason(installReason, userId);
13920                    mSettings.writePackageRestrictionsLPr(userId);
13921                    mSettings.writeKernelMappingLPr(pkgSetting);
13922                    installed = true;
13923                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13924                    // upgrade app from instant to full; we don't allow app downgrade
13925                    installed = true;
13926                }
13927                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13928            }
13929
13930            if (installed) {
13931                if (pkgSetting.pkg != null) {
13932                    synchronized (mInstallLock) {
13933                        // We don't need to freeze for a brand new install
13934                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13935                    }
13936                }
13937                sendPackageAddedForUser(packageName, pkgSetting, userId);
13938                synchronized (mPackages) {
13939                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13940                }
13941            }
13942        } finally {
13943            Binder.restoreCallingIdentity(callingId);
13944        }
13945
13946        return PackageManager.INSTALL_SUCCEEDED;
13947    }
13948
13949    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13950            boolean instantApp, boolean fullApp) {
13951        // no state specified; do nothing
13952        if (!instantApp && !fullApp) {
13953            return;
13954        }
13955        if (userId != UserHandle.USER_ALL) {
13956            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13957                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13958            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13959                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13960            }
13961        } else {
13962            for (int currentUserId : sUserManager.getUserIds()) {
13963                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13964                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13965                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13966                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13967                }
13968            }
13969        }
13970    }
13971
13972    boolean isUserRestricted(int userId, String restrictionKey) {
13973        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13974        if (restrictions.getBoolean(restrictionKey, false)) {
13975            Log.w(TAG, "User is restricted: " + restrictionKey);
13976            return true;
13977        }
13978        return false;
13979    }
13980
13981    @Override
13982    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13983            PersistableBundle appExtras, PersistableBundle launcherExtras, String callingPackage,
13984            int userId) {
13985        try {
13986            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS, null);
13987        } catch (SecurityException e) {
13988            mContext.enforceCallingOrSelfPermission(Manifest.permission.MANAGE_USERS,
13989                    "Callers need to have either " + Manifest.permission.SUSPEND_APPS + " or "
13990                            + Manifest.permission.MANAGE_USERS);
13991        }
13992        final int callingUid = Binder.getCallingUid();
13993        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13994                true /* requireFullPermission */, true /* checkShell */,
13995                "setPackagesSuspended for user " + userId);
13996        if (callingUid != Process.ROOT_UID &&
13997                !UserHandle.isSameApp(getPackageUid(callingPackage, 0, userId), callingUid)) {
13998            throw new IllegalArgumentException("callingPackage " + callingPackage + " does not"
13999                    + " belong to calling app id " + UserHandle.getAppId(callingUid));
14000        }
14001
14002        if (ArrayUtils.isEmpty(packageNames)) {
14003            return packageNames;
14004        }
14005
14006        final List<String> changedPackagesList = new ArrayList<>(packageNames.length);
14007        final List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14008        final long callingId = Binder.clearCallingIdentity();
14009        try {
14010            synchronized (mPackages) {
14011                for (int i = 0; i < packageNames.length; i++) {
14012                    final String packageName = packageNames[i];
14013                    if (callingPackage.equals(packageName)) {
14014                        Slog.w(TAG, "Calling package: " + callingPackage + " trying to "
14015                                + (suspended ? "" : "un") + "suspend itself. Ignoring");
14016                        unactionedPackages.add(packageName);
14017                        continue;
14018                    }
14019                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14020                    if (pkgSetting == null
14021                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14022                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14023                                + "\". Skipping suspending/un-suspending.");
14024                        unactionedPackages.add(packageName);
14025                        continue;
14026                    }
14027                    if (pkgSetting.getSuspended(userId) != suspended) {
14028                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14029                            unactionedPackages.add(packageName);
14030                            continue;
14031                        }
14032                        pkgSetting.setSuspended(suspended, callingPackage, appExtras,
14033                                launcherExtras, userId);
14034                        changedPackagesList.add(packageName);
14035                    }
14036                }
14037            }
14038        } finally {
14039            Binder.restoreCallingIdentity(callingId);
14040        }
14041        if (!changedPackagesList.isEmpty()) {
14042            final String[] changedPackages = changedPackagesList.toArray(
14043                    new String[changedPackagesList.size()]);
14044            sendPackagesSuspendedForUser(changedPackages, userId, suspended);
14045            sendMyPackageSuspendedOrUnsuspended(changedPackages, suspended, appExtras, userId);
14046            synchronized (mPackages) {
14047                scheduleWritePackageRestrictionsLocked(userId);
14048            }
14049        }
14050
14051        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14052    }
14053
14054    @Override
14055    public PersistableBundle getSuspendedPackageAppExtras(String packageName, int userId) {
14056        final int callingUid = Binder.getCallingUid();
14057        if (getPackageUid(packageName, 0, userId) != callingUid) {
14058            mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, null);
14059        }
14060        synchronized (mPackages) {
14061            final PackageSetting ps = mSettings.mPackages.get(packageName);
14062            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14063                throw new IllegalArgumentException("Unknown target package: " + packageName);
14064            }
14065            final PackageUserState packageUserState = ps.readUserState(userId);
14066            if (packageUserState.suspended) {
14067                return packageUserState.suspendedAppExtras;
14068            }
14069            return null;
14070        }
14071    }
14072
14073    @Override
14074    public void setSuspendedPackageAppExtras(String packageName, PersistableBundle appExtras,
14075            int userId) {
14076        final int callingUid = Binder.getCallingUid();
14077        mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, null);
14078        synchronized (mPackages) {
14079            final PackageSetting ps = mSettings.mPackages.get(packageName);
14080            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14081                throw new IllegalArgumentException("Unknown target package: " + packageName);
14082            }
14083            final PackageUserState packageUserState = ps.readUserState(userId);
14084            if (packageUserState.suspended) {
14085                packageUserState.suspendedAppExtras = appExtras;
14086                sendMyPackageSuspendedOrUnsuspended(new String[] {packageName}, true, appExtras,
14087                        userId);
14088            }
14089        }
14090    }
14091
14092    private void sendMyPackageSuspendedOrUnsuspended(String[] affectedPackages, boolean suspended,
14093            PersistableBundle appExtras, int userId) {
14094        final String action;
14095        final Bundle intentExtras = new Bundle();
14096        if (suspended) {
14097            action = Intent.ACTION_MY_PACKAGE_SUSPENDED;
14098            if (appExtras != null) {
14099                final Bundle bundledAppExtras = new Bundle(appExtras.deepCopy());
14100                intentExtras.putBundle(Intent.EXTRA_SUSPENDED_PACKAGE_EXTRAS, bundledAppExtras);
14101            }
14102        } else {
14103            action = Intent.ACTION_MY_PACKAGE_UNSUSPENDED;
14104        }
14105        mHandler.post(new Runnable() {
14106            @Override
14107            public void run() {
14108                try {
14109                    final IActivityManager am = ActivityManager.getService();
14110                    if (am == null) {
14111                        Slog.wtf(TAG, "IActivityManager null. Cannot send MY_PACKAGE_ "
14112                                + (suspended ? "" : "UN") + "SUSPENDED broadcasts");
14113                        return;
14114                    }
14115                    final int[] targetUserIds = new int[] {userId};
14116                    for (String packageName : affectedPackages) {
14117                        doSendBroadcast(am, action, null, intentExtras,
14118                                Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, packageName, null,
14119                                targetUserIds, false);
14120                    }
14121                } catch (RemoteException ex) {
14122                    // Shouldn't happen as AMS is in the same process.
14123                }
14124            }
14125        });
14126    }
14127
14128    @Override
14129    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14130        final int callingUid = Binder.getCallingUid();
14131        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14132                true /* requireFullPermission */, false /* checkShell */,
14133                "isPackageSuspendedForUser for user " + userId);
14134        if (getPackageUid(packageName, 0, userId) != callingUid) {
14135            mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, null);
14136        }
14137        synchronized (mPackages) {
14138            final PackageSetting ps = mSettings.mPackages.get(packageName);
14139            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14140                throw new IllegalArgumentException("Unknown target package: " + packageName);
14141            }
14142            return ps.getSuspended(userId);
14143        }
14144    }
14145
14146    void onSuspendingPackageRemoved(String packageName, int userId) {
14147        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14148                : new int[] {userId};
14149        synchronized (mPackages) {
14150            for (PackageSetting ps : mSettings.mPackages.values()) {
14151                for (int user : userIds) {
14152                    final PackageUserState pus = ps.readUserState(user);
14153                    if (pus.suspended && packageName.equals(pus.suspendingPackage)) {
14154                        ps.setSuspended(false, null, null, null, user);
14155                    }
14156                }
14157            }
14158        }
14159    }
14160
14161    @GuardedBy("mPackages")
14162    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14163        if (isPackageDeviceAdmin(packageName, userId)) {
14164            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14165                    + "\": has an active device admin");
14166            return false;
14167        }
14168
14169        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14170        if (packageName.equals(activeLauncherPackageName)) {
14171            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14172                    + "\": contains the active launcher");
14173            return false;
14174        }
14175
14176        if (packageName.equals(mRequiredInstallerPackage)) {
14177            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14178                    + "\": required for package installation");
14179            return false;
14180        }
14181
14182        if (packageName.equals(mRequiredUninstallerPackage)) {
14183            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14184                    + "\": required for package uninstallation");
14185            return false;
14186        }
14187
14188        if (packageName.equals(mRequiredVerifierPackage)) {
14189            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14190                    + "\": required for package verification");
14191            return false;
14192        }
14193
14194        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14195            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14196                    + "\": is the default dialer");
14197            return false;
14198        }
14199
14200        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14201            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14202                    + "\": protected package");
14203            return false;
14204        }
14205
14206        // Cannot suspend static shared libs as they are considered
14207        // a part of the using app (emulating static linking). Also
14208        // static libs are installed always on internal storage.
14209        PackageParser.Package pkg = mPackages.get(packageName);
14210        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14211            Slog.w(TAG, "Cannot suspend package: " + packageName
14212                    + " providing static shared library: "
14213                    + pkg.staticSharedLibName);
14214            return false;
14215        }
14216
14217        if (PLATFORM_PACKAGE_NAME.equals(packageName)) {
14218            Slog.w(TAG, "Cannot suspend package: " + packageName);
14219            return false;
14220        }
14221
14222        return true;
14223    }
14224
14225    private String getActiveLauncherPackageName(int userId) {
14226        Intent intent = new Intent(Intent.ACTION_MAIN);
14227        intent.addCategory(Intent.CATEGORY_HOME);
14228        ResolveInfo resolveInfo = resolveIntent(
14229                intent,
14230                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14231                PackageManager.MATCH_DEFAULT_ONLY,
14232                userId);
14233
14234        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14235    }
14236
14237    private String getDefaultDialerPackageName(int userId) {
14238        synchronized (mPackages) {
14239            return mSettings.getDefaultDialerPackageNameLPw(userId);
14240        }
14241    }
14242
14243    @Override
14244    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14245        mContext.enforceCallingOrSelfPermission(
14246                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14247                "Only package verification agents can verify applications");
14248
14249        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14250        final PackageVerificationResponse response = new PackageVerificationResponse(
14251                verificationCode, Binder.getCallingUid());
14252        msg.arg1 = id;
14253        msg.obj = response;
14254        mHandler.sendMessage(msg);
14255    }
14256
14257    @Override
14258    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14259            long millisecondsToDelay) {
14260        mContext.enforceCallingOrSelfPermission(
14261                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14262                "Only package verification agents can extend verification timeouts");
14263
14264        final PackageVerificationState state = mPendingVerification.get(id);
14265        final PackageVerificationResponse response = new PackageVerificationResponse(
14266                verificationCodeAtTimeout, Binder.getCallingUid());
14267
14268        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14269            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14270        }
14271        if (millisecondsToDelay < 0) {
14272            millisecondsToDelay = 0;
14273        }
14274        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14275                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14276            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14277        }
14278
14279        if ((state != null) && !state.timeoutExtended()) {
14280            state.extendTimeout();
14281
14282            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14283            msg.arg1 = id;
14284            msg.obj = response;
14285            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14286        }
14287    }
14288
14289    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14290            int verificationCode, UserHandle user) {
14291        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14292        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14293        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14294        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14295        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14296
14297        mContext.sendBroadcastAsUser(intent, user,
14298                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14299    }
14300
14301    private ComponentName matchComponentForVerifier(String packageName,
14302            List<ResolveInfo> receivers) {
14303        ActivityInfo targetReceiver = null;
14304
14305        final int NR = receivers.size();
14306        for (int i = 0; i < NR; i++) {
14307            final ResolveInfo info = receivers.get(i);
14308            if (info.activityInfo == null) {
14309                continue;
14310            }
14311
14312            if (packageName.equals(info.activityInfo.packageName)) {
14313                targetReceiver = info.activityInfo;
14314                break;
14315            }
14316        }
14317
14318        if (targetReceiver == null) {
14319            return null;
14320        }
14321
14322        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14323    }
14324
14325    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14326            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14327        if (pkgInfo.verifiers.length == 0) {
14328            return null;
14329        }
14330
14331        final int N = pkgInfo.verifiers.length;
14332        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14333        for (int i = 0; i < N; i++) {
14334            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14335
14336            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14337                    receivers);
14338            if (comp == null) {
14339                continue;
14340            }
14341
14342            final int verifierUid = getUidForVerifier(verifierInfo);
14343            if (verifierUid == -1) {
14344                continue;
14345            }
14346
14347            if (DEBUG_VERIFY) {
14348                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14349                        + " with the correct signature");
14350            }
14351            sufficientVerifiers.add(comp);
14352            verificationState.addSufficientVerifier(verifierUid);
14353        }
14354
14355        return sufficientVerifiers;
14356    }
14357
14358    private int getUidForVerifier(VerifierInfo verifierInfo) {
14359        synchronized (mPackages) {
14360            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14361            if (pkg == null) {
14362                return -1;
14363            } else if (pkg.mSigningDetails.signatures.length != 1) {
14364                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14365                        + " has more than one signature; ignoring");
14366                return -1;
14367            }
14368
14369            /*
14370             * If the public key of the package's signature does not match
14371             * our expected public key, then this is a different package and
14372             * we should skip.
14373             */
14374
14375            final byte[] expectedPublicKey;
14376            try {
14377                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14378                final PublicKey publicKey = verifierSig.getPublicKey();
14379                expectedPublicKey = publicKey.getEncoded();
14380            } catch (CertificateException e) {
14381                return -1;
14382            }
14383
14384            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14385
14386            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14387                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14388                        + " does not have the expected public key; ignoring");
14389                return -1;
14390            }
14391
14392            return pkg.applicationInfo.uid;
14393        }
14394    }
14395
14396    @Override
14397    public void finishPackageInstall(int token, boolean didLaunch) {
14398        enforceSystemOrRoot("Only the system is allowed to finish installs");
14399
14400        if (DEBUG_INSTALL) {
14401            Slog.v(TAG, "BM finishing package install for " + token);
14402        }
14403        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14404
14405        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14406        mHandler.sendMessage(msg);
14407    }
14408
14409    /**
14410     * Get the verification agent timeout.  Used for both the APK verifier and the
14411     * intent filter verifier.
14412     *
14413     * @return verification timeout in milliseconds
14414     */
14415    private long getVerificationTimeout() {
14416        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14417                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14418                DEFAULT_VERIFICATION_TIMEOUT);
14419    }
14420
14421    /**
14422     * Get the default verification agent response code.
14423     *
14424     * @return default verification response code
14425     */
14426    private int getDefaultVerificationResponse(UserHandle user) {
14427        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14428            return PackageManager.VERIFICATION_REJECT;
14429        }
14430        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14431                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14432                DEFAULT_VERIFICATION_RESPONSE);
14433    }
14434
14435    /**
14436     * Check whether or not package verification has been enabled.
14437     *
14438     * @return true if verification should be performed
14439     */
14440    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14441        if (!DEFAULT_VERIFY_ENABLE) {
14442            return false;
14443        }
14444
14445        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14446
14447        // Check if installing from ADB
14448        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14449            // Do not run verification in a test harness environment
14450            if (ActivityManager.isRunningInTestHarness()) {
14451                return false;
14452            }
14453            if (ensureVerifyAppsEnabled) {
14454                return true;
14455            }
14456            // Check if the developer does not want package verification for ADB installs
14457            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14458                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14459                return false;
14460            }
14461        } else {
14462            // only when not installed from ADB, skip verification for instant apps when
14463            // the installer and verifier are the same.
14464            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14465                if (mInstantAppInstallerActivity != null
14466                        && mInstantAppInstallerActivity.packageName.equals(
14467                                mRequiredVerifierPackage)) {
14468                    try {
14469                        mContext.getSystemService(AppOpsManager.class)
14470                                .checkPackage(installerUid, mRequiredVerifierPackage);
14471                        if (DEBUG_VERIFY) {
14472                            Slog.i(TAG, "disable verification for instant app");
14473                        }
14474                        return false;
14475                    } catch (SecurityException ignore) { }
14476                }
14477            }
14478        }
14479
14480        if (ensureVerifyAppsEnabled) {
14481            return true;
14482        }
14483
14484        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14485                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14486    }
14487
14488    @Override
14489    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14490            throws RemoteException {
14491        mContext.enforceCallingOrSelfPermission(
14492                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14493                "Only intentfilter verification agents can verify applications");
14494
14495        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14496        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14497                Binder.getCallingUid(), verificationCode, failedDomains);
14498        msg.arg1 = id;
14499        msg.obj = response;
14500        mHandler.sendMessage(msg);
14501    }
14502
14503    @Override
14504    public int getIntentVerificationStatus(String packageName, int userId) {
14505        final int callingUid = Binder.getCallingUid();
14506        if (UserHandle.getUserId(callingUid) != userId) {
14507            mContext.enforceCallingOrSelfPermission(
14508                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14509                    "getIntentVerificationStatus" + userId);
14510        }
14511        if (getInstantAppPackageName(callingUid) != null) {
14512            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14513        }
14514        synchronized (mPackages) {
14515            final PackageSetting ps = mSettings.mPackages.get(packageName);
14516            if (ps == null
14517                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14518                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14519            }
14520            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14521        }
14522    }
14523
14524    @Override
14525    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14526        mContext.enforceCallingOrSelfPermission(
14527                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14528
14529        boolean result = false;
14530        synchronized (mPackages) {
14531            final PackageSetting ps = mSettings.mPackages.get(packageName);
14532            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14533                return false;
14534            }
14535            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14536        }
14537        if (result) {
14538            scheduleWritePackageRestrictionsLocked(userId);
14539        }
14540        return result;
14541    }
14542
14543    @Override
14544    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14545            String packageName) {
14546        final int callingUid = Binder.getCallingUid();
14547        if (getInstantAppPackageName(callingUid) != null) {
14548            return ParceledListSlice.emptyList();
14549        }
14550        synchronized (mPackages) {
14551            final PackageSetting ps = mSettings.mPackages.get(packageName);
14552            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14553                return ParceledListSlice.emptyList();
14554            }
14555            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14556        }
14557    }
14558
14559    @Override
14560    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14561        if (TextUtils.isEmpty(packageName)) {
14562            return ParceledListSlice.emptyList();
14563        }
14564        final int callingUid = Binder.getCallingUid();
14565        final int callingUserId = UserHandle.getUserId(callingUid);
14566        synchronized (mPackages) {
14567            PackageParser.Package pkg = mPackages.get(packageName);
14568            if (pkg == null || pkg.activities == null) {
14569                return ParceledListSlice.emptyList();
14570            }
14571            if (pkg.mExtras == null) {
14572                return ParceledListSlice.emptyList();
14573            }
14574            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14575            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14576                return ParceledListSlice.emptyList();
14577            }
14578            final int count = pkg.activities.size();
14579            ArrayList<IntentFilter> result = new ArrayList<>();
14580            for (int n=0; n<count; n++) {
14581                PackageParser.Activity activity = pkg.activities.get(n);
14582                if (activity.intents != null && activity.intents.size() > 0) {
14583                    result.addAll(activity.intents);
14584                }
14585            }
14586            return new ParceledListSlice<>(result);
14587        }
14588    }
14589
14590    @Override
14591    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14592        mContext.enforceCallingOrSelfPermission(
14593                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14594        if (UserHandle.getCallingUserId() != userId) {
14595            mContext.enforceCallingOrSelfPermission(
14596                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14597        }
14598
14599        synchronized (mPackages) {
14600            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14601            if (packageName != null) {
14602                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14603                        packageName, userId);
14604            }
14605            return result;
14606        }
14607    }
14608
14609    @Override
14610    public String getDefaultBrowserPackageName(int userId) {
14611        if (UserHandle.getCallingUserId() != userId) {
14612            mContext.enforceCallingOrSelfPermission(
14613                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14614        }
14615        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14616            return null;
14617        }
14618        synchronized (mPackages) {
14619            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14620        }
14621    }
14622
14623    /**
14624     * Get the "allow unknown sources" setting.
14625     *
14626     * @return the current "allow unknown sources" setting
14627     */
14628    private int getUnknownSourcesSettings() {
14629        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14630                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14631                -1);
14632    }
14633
14634    @Override
14635    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14636        final int callingUid = Binder.getCallingUid();
14637        if (getInstantAppPackageName(callingUid) != null) {
14638            return;
14639        }
14640        // writer
14641        synchronized (mPackages) {
14642            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14643            if (targetPackageSetting == null
14644                    || filterAppAccessLPr(
14645                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14646                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14647            }
14648
14649            PackageSetting installerPackageSetting;
14650            if (installerPackageName != null) {
14651                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14652                if (installerPackageSetting == null) {
14653                    throw new IllegalArgumentException("Unknown installer package: "
14654                            + installerPackageName);
14655                }
14656            } else {
14657                installerPackageSetting = null;
14658            }
14659
14660            Signature[] callerSignature;
14661            Object obj = mSettings.getUserIdLPr(callingUid);
14662            if (obj != null) {
14663                if (obj instanceof SharedUserSetting) {
14664                    callerSignature =
14665                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14666                } else if (obj instanceof PackageSetting) {
14667                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14668                } else {
14669                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14670                }
14671            } else {
14672                throw new SecurityException("Unknown calling UID: " + callingUid);
14673            }
14674
14675            // Verify: can't set installerPackageName to a package that is
14676            // not signed with the same cert as the caller.
14677            if (installerPackageSetting != null) {
14678                if (compareSignatures(callerSignature,
14679                        installerPackageSetting.signatures.mSigningDetails.signatures)
14680                        != PackageManager.SIGNATURE_MATCH) {
14681                    throw new SecurityException(
14682                            "Caller does not have same cert as new installer package "
14683                            + installerPackageName);
14684                }
14685            }
14686
14687            // Verify: if target already has an installer package, it must
14688            // be signed with the same cert as the caller.
14689            if (targetPackageSetting.installerPackageName != null) {
14690                PackageSetting setting = mSettings.mPackages.get(
14691                        targetPackageSetting.installerPackageName);
14692                // If the currently set package isn't valid, then it's always
14693                // okay to change it.
14694                if (setting != null) {
14695                    if (compareSignatures(callerSignature,
14696                            setting.signatures.mSigningDetails.signatures)
14697                            != PackageManager.SIGNATURE_MATCH) {
14698                        throw new SecurityException(
14699                                "Caller does not have same cert as old installer package "
14700                                + targetPackageSetting.installerPackageName);
14701                    }
14702                }
14703            }
14704
14705            // Okay!
14706            targetPackageSetting.installerPackageName = installerPackageName;
14707            if (installerPackageName != null) {
14708                mSettings.mInstallerPackages.add(installerPackageName);
14709            }
14710            scheduleWriteSettingsLocked();
14711        }
14712    }
14713
14714    @Override
14715    public void setApplicationCategoryHint(String packageName, int categoryHint,
14716            String callerPackageName) {
14717        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14718            throw new SecurityException("Instant applications don't have access to this method");
14719        }
14720        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14721                callerPackageName);
14722        synchronized (mPackages) {
14723            PackageSetting ps = mSettings.mPackages.get(packageName);
14724            if (ps == null) {
14725                throw new IllegalArgumentException("Unknown target package " + packageName);
14726            }
14727            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14728                throw new IllegalArgumentException("Unknown target package " + packageName);
14729            }
14730            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14731                throw new IllegalArgumentException("Calling package " + callerPackageName
14732                        + " is not installer for " + packageName);
14733            }
14734
14735            if (ps.categoryHint != categoryHint) {
14736                ps.categoryHint = categoryHint;
14737                scheduleWriteSettingsLocked();
14738            }
14739        }
14740    }
14741
14742    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14743        // Queue up an async operation since the package installation may take a little while.
14744        mHandler.post(new Runnable() {
14745            public void run() {
14746                mHandler.removeCallbacks(this);
14747                 // Result object to be returned
14748                PackageInstalledInfo res = new PackageInstalledInfo();
14749                res.setReturnCode(currentStatus);
14750                res.uid = -1;
14751                res.pkg = null;
14752                res.removedInfo = null;
14753                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14754                    args.doPreInstall(res.returnCode);
14755                    synchronized (mInstallLock) {
14756                        installPackageTracedLI(args, res);
14757                    }
14758                    args.doPostInstall(res.returnCode, res.uid);
14759                }
14760
14761                // A restore should be performed at this point if (a) the install
14762                // succeeded, (b) the operation is not an update, and (c) the new
14763                // package has not opted out of backup participation.
14764                final boolean update = res.removedInfo != null
14765                        && res.removedInfo.removedPackage != null;
14766                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14767                boolean doRestore = !update
14768                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14769
14770                // Set up the post-install work request bookkeeping.  This will be used
14771                // and cleaned up by the post-install event handling regardless of whether
14772                // there's a restore pass performed.  Token values are >= 1.
14773                int token;
14774                if (mNextInstallToken < 0) mNextInstallToken = 1;
14775                token = mNextInstallToken++;
14776
14777                PostInstallData data = new PostInstallData(args, res);
14778                mRunningInstalls.put(token, data);
14779                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14780
14781                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14782                    // Pass responsibility to the Backup Manager.  It will perform a
14783                    // restore if appropriate, then pass responsibility back to the
14784                    // Package Manager to run the post-install observer callbacks
14785                    // and broadcasts.
14786                    IBackupManager bm = IBackupManager.Stub.asInterface(
14787                            ServiceManager.getService(Context.BACKUP_SERVICE));
14788                    if (bm != null) {
14789                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14790                                + " to BM for possible restore");
14791                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14792                        try {
14793                            // TODO: http://b/22388012
14794                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14795                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14796                            } else {
14797                                doRestore = false;
14798                            }
14799                        } catch (RemoteException e) {
14800                            // can't happen; the backup manager is local
14801                        } catch (Exception e) {
14802                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14803                            doRestore = false;
14804                        }
14805                    } else {
14806                        Slog.e(TAG, "Backup Manager not found!");
14807                        doRestore = false;
14808                    }
14809                }
14810
14811                if (!doRestore) {
14812                    // No restore possible, or the Backup Manager was mysteriously not
14813                    // available -- just fire the post-install work request directly.
14814                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14815
14816                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14817
14818                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14819                    mHandler.sendMessage(msg);
14820                }
14821            }
14822        });
14823    }
14824
14825    /**
14826     * Callback from PackageSettings whenever an app is first transitioned out of the
14827     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14828     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14829     * here whether the app is the target of an ongoing install, and only send the
14830     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14831     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14832     * handling.
14833     */
14834    void notifyFirstLaunch(final String packageName, final String installerPackage,
14835            final int userId) {
14836        // Serialize this with the rest of the install-process message chain.  In the
14837        // restore-at-install case, this Runnable will necessarily run before the
14838        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14839        // are coherent.  In the non-restore case, the app has already completed install
14840        // and been launched through some other means, so it is not in a problematic
14841        // state for observers to see the FIRST_LAUNCH signal.
14842        mHandler.post(new Runnable() {
14843            @Override
14844            public void run() {
14845                for (int i = 0; i < mRunningInstalls.size(); i++) {
14846                    final PostInstallData data = mRunningInstalls.valueAt(i);
14847                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14848                        continue;
14849                    }
14850                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14851                        // right package; but is it for the right user?
14852                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14853                            if (userId == data.res.newUsers[uIndex]) {
14854                                if (DEBUG_BACKUP) {
14855                                    Slog.i(TAG, "Package " + packageName
14856                                            + " being restored so deferring FIRST_LAUNCH");
14857                                }
14858                                return;
14859                            }
14860                        }
14861                    }
14862                }
14863                // didn't find it, so not being restored
14864                if (DEBUG_BACKUP) {
14865                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14866                }
14867                final boolean isInstantApp = isInstantApp(packageName, userId);
14868                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14869                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14870                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14871            }
14872        });
14873    }
14874
14875    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14876            int[] userIds, int[] instantUserIds) {
14877        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14878                installerPkg, null, userIds, instantUserIds);
14879    }
14880
14881    private abstract class HandlerParams {
14882        private static final int MAX_RETRIES = 4;
14883
14884        /**
14885         * Number of times startCopy() has been attempted and had a non-fatal
14886         * error.
14887         */
14888        private int mRetries = 0;
14889
14890        /** User handle for the user requesting the information or installation. */
14891        private final UserHandle mUser;
14892        String traceMethod;
14893        int traceCookie;
14894
14895        HandlerParams(UserHandle user) {
14896            mUser = user;
14897        }
14898
14899        UserHandle getUser() {
14900            return mUser;
14901        }
14902
14903        HandlerParams setTraceMethod(String traceMethod) {
14904            this.traceMethod = traceMethod;
14905            return this;
14906        }
14907
14908        HandlerParams setTraceCookie(int traceCookie) {
14909            this.traceCookie = traceCookie;
14910            return this;
14911        }
14912
14913        final boolean startCopy() {
14914            boolean res;
14915            try {
14916                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14917
14918                if (++mRetries > MAX_RETRIES) {
14919                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14920                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14921                    handleServiceError();
14922                    return false;
14923                } else {
14924                    handleStartCopy();
14925                    res = true;
14926                }
14927            } catch (RemoteException e) {
14928                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14929                mHandler.sendEmptyMessage(MCS_RECONNECT);
14930                res = false;
14931            }
14932            handleReturnCode();
14933            return res;
14934        }
14935
14936        final void serviceError() {
14937            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14938            handleServiceError();
14939            handleReturnCode();
14940        }
14941
14942        abstract void handleStartCopy() throws RemoteException;
14943        abstract void handleServiceError();
14944        abstract void handleReturnCode();
14945    }
14946
14947    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14948        for (File path : paths) {
14949            try {
14950                mcs.clearDirectory(path.getAbsolutePath());
14951            } catch (RemoteException e) {
14952            }
14953        }
14954    }
14955
14956    static class OriginInfo {
14957        /**
14958         * Location where install is coming from, before it has been
14959         * copied/renamed into place. This could be a single monolithic APK
14960         * file, or a cluster directory. This location may be untrusted.
14961         */
14962        final File file;
14963
14964        /**
14965         * Flag indicating that {@link #file} or {@link #cid} has already been
14966         * staged, meaning downstream users don't need to defensively copy the
14967         * contents.
14968         */
14969        final boolean staged;
14970
14971        /**
14972         * Flag indicating that {@link #file} or {@link #cid} is an already
14973         * installed app that is being moved.
14974         */
14975        final boolean existing;
14976
14977        final String resolvedPath;
14978        final File resolvedFile;
14979
14980        static OriginInfo fromNothing() {
14981            return new OriginInfo(null, false, false);
14982        }
14983
14984        static OriginInfo fromUntrustedFile(File file) {
14985            return new OriginInfo(file, false, false);
14986        }
14987
14988        static OriginInfo fromExistingFile(File file) {
14989            return new OriginInfo(file, false, true);
14990        }
14991
14992        static OriginInfo fromStagedFile(File file) {
14993            return new OriginInfo(file, true, false);
14994        }
14995
14996        private OriginInfo(File file, boolean staged, boolean existing) {
14997            this.file = file;
14998            this.staged = staged;
14999            this.existing = existing;
15000
15001            if (file != null) {
15002                resolvedPath = file.getAbsolutePath();
15003                resolvedFile = file;
15004            } else {
15005                resolvedPath = null;
15006                resolvedFile = null;
15007            }
15008        }
15009    }
15010
15011    static class MoveInfo {
15012        final int moveId;
15013        final String fromUuid;
15014        final String toUuid;
15015        final String packageName;
15016        final String dataAppName;
15017        final int appId;
15018        final String seinfo;
15019        final int targetSdkVersion;
15020
15021        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15022                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15023            this.moveId = moveId;
15024            this.fromUuid = fromUuid;
15025            this.toUuid = toUuid;
15026            this.packageName = packageName;
15027            this.dataAppName = dataAppName;
15028            this.appId = appId;
15029            this.seinfo = seinfo;
15030            this.targetSdkVersion = targetSdkVersion;
15031        }
15032    }
15033
15034    static class VerificationInfo {
15035        /** A constant used to indicate that a uid value is not present. */
15036        public static final int NO_UID = -1;
15037
15038        /** URI referencing where the package was downloaded from. */
15039        final Uri originatingUri;
15040
15041        /** HTTP referrer URI associated with the originatingURI. */
15042        final Uri referrer;
15043
15044        /** UID of the application that the install request originated from. */
15045        final int originatingUid;
15046
15047        /** UID of application requesting the install */
15048        final int installerUid;
15049
15050        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15051            this.originatingUri = originatingUri;
15052            this.referrer = referrer;
15053            this.originatingUid = originatingUid;
15054            this.installerUid = installerUid;
15055        }
15056    }
15057
15058    class InstallParams extends HandlerParams {
15059        final OriginInfo origin;
15060        final MoveInfo move;
15061        final IPackageInstallObserver2 observer;
15062        int installFlags;
15063        final String installerPackageName;
15064        final String volumeUuid;
15065        private InstallArgs mArgs;
15066        private int mRet;
15067        final String packageAbiOverride;
15068        final String[] grantedRuntimePermissions;
15069        final VerificationInfo verificationInfo;
15070        final PackageParser.SigningDetails signingDetails;
15071        final int installReason;
15072
15073        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15074                int installFlags, String installerPackageName, String volumeUuid,
15075                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15076                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
15077            super(user);
15078            this.origin = origin;
15079            this.move = move;
15080            this.observer = observer;
15081            this.installFlags = installFlags;
15082            this.installerPackageName = installerPackageName;
15083            this.volumeUuid = volumeUuid;
15084            this.verificationInfo = verificationInfo;
15085            this.packageAbiOverride = packageAbiOverride;
15086            this.grantedRuntimePermissions = grantedPermissions;
15087            this.signingDetails = signingDetails;
15088            this.installReason = installReason;
15089        }
15090
15091        @Override
15092        public String toString() {
15093            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15094                    + " file=" + origin.file + "}";
15095        }
15096
15097        private int installLocationPolicy(PackageInfoLite pkgLite) {
15098            String packageName = pkgLite.packageName;
15099            int installLocation = pkgLite.installLocation;
15100            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15101            // reader
15102            synchronized (mPackages) {
15103                // Currently installed package which the new package is attempting to replace or
15104                // null if no such package is installed.
15105                PackageParser.Package installedPkg = mPackages.get(packageName);
15106                // Package which currently owns the data which the new package will own if installed.
15107                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15108                // will be null whereas dataOwnerPkg will contain information about the package
15109                // which was uninstalled while keeping its data.
15110                PackageParser.Package dataOwnerPkg = installedPkg;
15111                if (dataOwnerPkg  == null) {
15112                    PackageSetting ps = mSettings.mPackages.get(packageName);
15113                    if (ps != null) {
15114                        dataOwnerPkg = ps.pkg;
15115                    }
15116                }
15117
15118                if (dataOwnerPkg != null) {
15119                    // If installed, the package will get access to data left on the device by its
15120                    // predecessor. As a security measure, this is permited only if this is not a
15121                    // version downgrade or if the predecessor package is marked as debuggable and
15122                    // a downgrade is explicitly requested.
15123                    //
15124                    // On debuggable platform builds, downgrades are permitted even for
15125                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15126                    // not offer security guarantees and thus it's OK to disable some security
15127                    // mechanisms to make debugging/testing easier on those builds. However, even on
15128                    // debuggable builds downgrades of packages are permitted only if requested via
15129                    // installFlags. This is because we aim to keep the behavior of debuggable
15130                    // platform builds as close as possible to the behavior of non-debuggable
15131                    // platform builds.
15132                    final boolean downgradeRequested =
15133                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15134                    final boolean packageDebuggable =
15135                                (dataOwnerPkg.applicationInfo.flags
15136                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15137                    final boolean downgradePermitted =
15138                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15139                    if (!downgradePermitted) {
15140                        try {
15141                            checkDowngrade(dataOwnerPkg, pkgLite);
15142                        } catch (PackageManagerException e) {
15143                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15144                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15145                        }
15146                    }
15147                }
15148
15149                if (installedPkg != null) {
15150                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15151                        // Check for updated system application.
15152                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15153                            if (onSd) {
15154                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15155                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15156                            }
15157                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15158                        } else {
15159                            if (onSd) {
15160                                // Install flag overrides everything.
15161                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15162                            }
15163                            // If current upgrade specifies particular preference
15164                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15165                                // Application explicitly specified internal.
15166                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15167                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15168                                // App explictly prefers external. Let policy decide
15169                            } else {
15170                                // Prefer previous location
15171                                if (isExternal(installedPkg)) {
15172                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15173                                }
15174                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15175                            }
15176                        }
15177                    } else {
15178                        // Invalid install. Return error code
15179                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15180                    }
15181                }
15182            }
15183            // All the special cases have been taken care of.
15184            // Return result based on recommended install location.
15185            if (onSd) {
15186                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15187            }
15188            return pkgLite.recommendedInstallLocation;
15189        }
15190
15191        /*
15192         * Invoke remote method to get package information and install
15193         * location values. Override install location based on default
15194         * policy if needed and then create install arguments based
15195         * on the install location.
15196         */
15197        public void handleStartCopy() throws RemoteException {
15198            int ret = PackageManager.INSTALL_SUCCEEDED;
15199
15200            // If we're already staged, we've firmly committed to an install location
15201            if (origin.staged) {
15202                if (origin.file != null) {
15203                    installFlags |= PackageManager.INSTALL_INTERNAL;
15204                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15205                } else {
15206                    throw new IllegalStateException("Invalid stage location");
15207                }
15208            }
15209
15210            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15211            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15212            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15213            PackageInfoLite pkgLite = null;
15214
15215            if (onInt && onSd) {
15216                // Check if both bits are set.
15217                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15218                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15219            } else if (onSd && ephemeral) {
15220                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15221                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15222            } else {
15223                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15224                        packageAbiOverride);
15225
15226                if (DEBUG_INSTANT && ephemeral) {
15227                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15228                }
15229
15230                /*
15231                 * If we have too little free space, try to free cache
15232                 * before giving up.
15233                 */
15234                if (!origin.staged && pkgLite.recommendedInstallLocation
15235                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15236                    // TODO: focus freeing disk space on the target device
15237                    final StorageManager storage = StorageManager.from(mContext);
15238                    final long lowThreshold = storage.getStorageLowBytes(
15239                            Environment.getDataDirectory());
15240
15241                    final long sizeBytes = mContainerService.calculateInstalledSize(
15242                            origin.resolvedPath, packageAbiOverride);
15243
15244                    try {
15245                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15246                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15247                                installFlags, packageAbiOverride);
15248                    } catch (InstallerException e) {
15249                        Slog.w(TAG, "Failed to free cache", e);
15250                    }
15251
15252                    /*
15253                     * The cache free must have deleted the file we
15254                     * downloaded to install.
15255                     *
15256                     * TODO: fix the "freeCache" call to not delete
15257                     *       the file we care about.
15258                     */
15259                    if (pkgLite.recommendedInstallLocation
15260                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15261                        pkgLite.recommendedInstallLocation
15262                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15263                    }
15264                }
15265            }
15266
15267            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15268                int loc = pkgLite.recommendedInstallLocation;
15269                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15270                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15271                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15272                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15273                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15274                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15275                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15276                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15277                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15278                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15279                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15280                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15281                } else {
15282                    // Override with defaults if needed.
15283                    loc = installLocationPolicy(pkgLite);
15284                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15285                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15286                    } else if (!onSd && !onInt) {
15287                        // Override install location with flags
15288                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15289                            // Set the flag to install on external media.
15290                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15291                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15292                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15293                            if (DEBUG_INSTANT) {
15294                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15295                            }
15296                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15297                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15298                                    |PackageManager.INSTALL_INTERNAL);
15299                        } else {
15300                            // Make sure the flag for installing on external
15301                            // media is unset
15302                            installFlags |= PackageManager.INSTALL_INTERNAL;
15303                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15304                        }
15305                    }
15306                }
15307            }
15308
15309            final InstallArgs args = createInstallArgs(this);
15310            mArgs = args;
15311
15312            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15313                // TODO: http://b/22976637
15314                // Apps installed for "all" users use the device owner to verify the app
15315                UserHandle verifierUser = getUser();
15316                if (verifierUser == UserHandle.ALL) {
15317                    verifierUser = UserHandle.SYSTEM;
15318                }
15319
15320                /*
15321                 * Determine if we have any installed package verifiers. If we
15322                 * do, then we'll defer to them to verify the packages.
15323                 */
15324                final int requiredUid = mRequiredVerifierPackage == null ? -1
15325                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15326                                verifierUser.getIdentifier());
15327                final int installerUid =
15328                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15329                if (!origin.existing && requiredUid != -1
15330                        && isVerificationEnabled(
15331                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15332                    final Intent verification = new Intent(
15333                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15334                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15335                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15336                            PACKAGE_MIME_TYPE);
15337                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15338
15339                    // Query all live verifiers based on current user state
15340                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15341                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15342                            false /*allowDynamicSplits*/);
15343
15344                    if (DEBUG_VERIFY) {
15345                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15346                                + verification.toString() + " with " + pkgLite.verifiers.length
15347                                + " optional verifiers");
15348                    }
15349
15350                    final int verificationId = mPendingVerificationToken++;
15351
15352                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15353
15354                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15355                            installerPackageName);
15356
15357                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15358                            installFlags);
15359
15360                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15361                            pkgLite.packageName);
15362
15363                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15364                            pkgLite.versionCode);
15365
15366                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15367                            pkgLite.getLongVersionCode());
15368
15369                    if (verificationInfo != null) {
15370                        if (verificationInfo.originatingUri != null) {
15371                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15372                                    verificationInfo.originatingUri);
15373                        }
15374                        if (verificationInfo.referrer != null) {
15375                            verification.putExtra(Intent.EXTRA_REFERRER,
15376                                    verificationInfo.referrer);
15377                        }
15378                        if (verificationInfo.originatingUid >= 0) {
15379                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15380                                    verificationInfo.originatingUid);
15381                        }
15382                        if (verificationInfo.installerUid >= 0) {
15383                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15384                                    verificationInfo.installerUid);
15385                        }
15386                    }
15387
15388                    final PackageVerificationState verificationState = new PackageVerificationState(
15389                            requiredUid, args);
15390
15391                    mPendingVerification.append(verificationId, verificationState);
15392
15393                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15394                            receivers, verificationState);
15395
15396                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15397                    final long idleDuration = getVerificationTimeout();
15398
15399                    /*
15400                     * If any sufficient verifiers were listed in the package
15401                     * manifest, attempt to ask them.
15402                     */
15403                    if (sufficientVerifiers != null) {
15404                        final int N = sufficientVerifiers.size();
15405                        if (N == 0) {
15406                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15407                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15408                        } else {
15409                            for (int i = 0; i < N; i++) {
15410                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15411                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15412                                        verifierComponent.getPackageName(), idleDuration,
15413                                        verifierUser.getIdentifier(), false, "package verifier");
15414
15415                                final Intent sufficientIntent = new Intent(verification);
15416                                sufficientIntent.setComponent(verifierComponent);
15417                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15418                            }
15419                        }
15420                    }
15421
15422                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15423                            mRequiredVerifierPackage, receivers);
15424                    if (ret == PackageManager.INSTALL_SUCCEEDED
15425                            && mRequiredVerifierPackage != null) {
15426                        Trace.asyncTraceBegin(
15427                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15428                        /*
15429                         * Send the intent to the required verification agent,
15430                         * but only start the verification timeout after the
15431                         * target BroadcastReceivers have run.
15432                         */
15433                        verification.setComponent(requiredVerifierComponent);
15434                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15435                                mRequiredVerifierPackage, idleDuration,
15436                                verifierUser.getIdentifier(), false, "package verifier");
15437                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15438                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15439                                new BroadcastReceiver() {
15440                                    @Override
15441                                    public void onReceive(Context context, Intent intent) {
15442                                        final Message msg = mHandler
15443                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15444                                        msg.arg1 = verificationId;
15445                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15446                                    }
15447                                }, null, 0, null, null);
15448
15449                        /*
15450                         * We don't want the copy to proceed until verification
15451                         * succeeds, so null out this field.
15452                         */
15453                        mArgs = null;
15454                    }
15455                } else {
15456                    /*
15457                     * No package verification is enabled, so immediately start
15458                     * the remote call to initiate copy using temporary file.
15459                     */
15460                    ret = args.copyApk(mContainerService, true);
15461                }
15462            }
15463
15464            mRet = ret;
15465        }
15466
15467        @Override
15468        void handleReturnCode() {
15469            // If mArgs is null, then MCS couldn't be reached. When it
15470            // reconnects, it will try again to install. At that point, this
15471            // will succeed.
15472            if (mArgs != null) {
15473                processPendingInstall(mArgs, mRet);
15474            }
15475        }
15476
15477        @Override
15478        void handleServiceError() {
15479            mArgs = createInstallArgs(this);
15480            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15481        }
15482    }
15483
15484    private InstallArgs createInstallArgs(InstallParams params) {
15485        if (params.move != null) {
15486            return new MoveInstallArgs(params);
15487        } else {
15488            return new FileInstallArgs(params);
15489        }
15490    }
15491
15492    /**
15493     * Create args that describe an existing installed package. Typically used
15494     * when cleaning up old installs, or used as a move source.
15495     */
15496    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15497            String resourcePath, String[] instructionSets) {
15498        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15499    }
15500
15501    static abstract class InstallArgs {
15502        /** @see InstallParams#origin */
15503        final OriginInfo origin;
15504        /** @see InstallParams#move */
15505        final MoveInfo move;
15506
15507        final IPackageInstallObserver2 observer;
15508        // Always refers to PackageManager flags only
15509        final int installFlags;
15510        final String installerPackageName;
15511        final String volumeUuid;
15512        final UserHandle user;
15513        final String abiOverride;
15514        final String[] installGrantPermissions;
15515        /** If non-null, drop an async trace when the install completes */
15516        final String traceMethod;
15517        final int traceCookie;
15518        final PackageParser.SigningDetails signingDetails;
15519        final int installReason;
15520
15521        // The list of instruction sets supported by this app. This is currently
15522        // only used during the rmdex() phase to clean up resources. We can get rid of this
15523        // if we move dex files under the common app path.
15524        /* nullable */ String[] instructionSets;
15525
15526        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15527                int installFlags, String installerPackageName, String volumeUuid,
15528                UserHandle user, String[] instructionSets,
15529                String abiOverride, String[] installGrantPermissions,
15530                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15531                int installReason) {
15532            this.origin = origin;
15533            this.move = move;
15534            this.installFlags = installFlags;
15535            this.observer = observer;
15536            this.installerPackageName = installerPackageName;
15537            this.volumeUuid = volumeUuid;
15538            this.user = user;
15539            this.instructionSets = instructionSets;
15540            this.abiOverride = abiOverride;
15541            this.installGrantPermissions = installGrantPermissions;
15542            this.traceMethod = traceMethod;
15543            this.traceCookie = traceCookie;
15544            this.signingDetails = signingDetails;
15545            this.installReason = installReason;
15546        }
15547
15548        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15549        abstract int doPreInstall(int status);
15550
15551        /**
15552         * Rename package into final resting place. All paths on the given
15553         * scanned package should be updated to reflect the rename.
15554         */
15555        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15556        abstract int doPostInstall(int status, int uid);
15557
15558        /** @see PackageSettingBase#codePathString */
15559        abstract String getCodePath();
15560        /** @see PackageSettingBase#resourcePathString */
15561        abstract String getResourcePath();
15562
15563        // Need installer lock especially for dex file removal.
15564        abstract void cleanUpResourcesLI();
15565        abstract boolean doPostDeleteLI(boolean delete);
15566
15567        /**
15568         * Called before the source arguments are copied. This is used mostly
15569         * for MoveParams when it needs to read the source file to put it in the
15570         * destination.
15571         */
15572        int doPreCopy() {
15573            return PackageManager.INSTALL_SUCCEEDED;
15574        }
15575
15576        /**
15577         * Called after the source arguments are copied. This is used mostly for
15578         * MoveParams when it needs to read the source file to put it in the
15579         * destination.
15580         */
15581        int doPostCopy(int uid) {
15582            return PackageManager.INSTALL_SUCCEEDED;
15583        }
15584
15585        protected boolean isFwdLocked() {
15586            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15587        }
15588
15589        protected boolean isExternalAsec() {
15590            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15591        }
15592
15593        protected boolean isEphemeral() {
15594            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15595        }
15596
15597        UserHandle getUser() {
15598            return user;
15599        }
15600    }
15601
15602    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15603        if (!allCodePaths.isEmpty()) {
15604            if (instructionSets == null) {
15605                throw new IllegalStateException("instructionSet == null");
15606            }
15607            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15608            for (String codePath : allCodePaths) {
15609                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15610                    try {
15611                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15612                    } catch (InstallerException ignored) {
15613                    }
15614                }
15615            }
15616        }
15617    }
15618
15619    /**
15620     * Logic to handle installation of non-ASEC applications, including copying
15621     * and renaming logic.
15622     */
15623    class FileInstallArgs extends InstallArgs {
15624        private File codeFile;
15625        private File resourceFile;
15626
15627        // Example topology:
15628        // /data/app/com.example/base.apk
15629        // /data/app/com.example/split_foo.apk
15630        // /data/app/com.example/lib/arm/libfoo.so
15631        // /data/app/com.example/lib/arm64/libfoo.so
15632        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15633
15634        /** New install */
15635        FileInstallArgs(InstallParams params) {
15636            super(params.origin, params.move, params.observer, params.installFlags,
15637                    params.installerPackageName, params.volumeUuid,
15638                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15639                    params.grantedRuntimePermissions,
15640                    params.traceMethod, params.traceCookie, params.signingDetails,
15641                    params.installReason);
15642            if (isFwdLocked()) {
15643                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15644            }
15645        }
15646
15647        /** Existing install */
15648        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15649            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15650                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15651                    PackageManager.INSTALL_REASON_UNKNOWN);
15652            this.codeFile = (codePath != null) ? new File(codePath) : null;
15653            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15654        }
15655
15656        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15657            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15658            try {
15659                return doCopyApk(imcs, temp);
15660            } finally {
15661                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15662            }
15663        }
15664
15665        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15666            if (origin.staged) {
15667                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15668                codeFile = origin.file;
15669                resourceFile = origin.file;
15670                return PackageManager.INSTALL_SUCCEEDED;
15671            }
15672
15673            try {
15674                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15675                final File tempDir =
15676                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15677                codeFile = tempDir;
15678                resourceFile = tempDir;
15679            } catch (IOException e) {
15680                Slog.w(TAG, "Failed to create copy file: " + e);
15681                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15682            }
15683
15684            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15685                @Override
15686                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15687                    if (!FileUtils.isValidExtFilename(name)) {
15688                        throw new IllegalArgumentException("Invalid filename: " + name);
15689                    }
15690                    try {
15691                        final File file = new File(codeFile, name);
15692                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15693                                O_RDWR | O_CREAT, 0644);
15694                        Os.chmod(file.getAbsolutePath(), 0644);
15695                        return new ParcelFileDescriptor(fd);
15696                    } catch (ErrnoException e) {
15697                        throw new RemoteException("Failed to open: " + e.getMessage());
15698                    }
15699                }
15700            };
15701
15702            int ret = PackageManager.INSTALL_SUCCEEDED;
15703            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15704            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15705                Slog.e(TAG, "Failed to copy package");
15706                return ret;
15707            }
15708
15709            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15710            NativeLibraryHelper.Handle handle = null;
15711            try {
15712                handle = NativeLibraryHelper.Handle.create(codeFile);
15713                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15714                        abiOverride);
15715            } catch (IOException e) {
15716                Slog.e(TAG, "Copying native libraries failed", e);
15717                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15718            } finally {
15719                IoUtils.closeQuietly(handle);
15720            }
15721
15722            return ret;
15723        }
15724
15725        int doPreInstall(int status) {
15726            if (status != PackageManager.INSTALL_SUCCEEDED) {
15727                cleanUp();
15728            }
15729            return status;
15730        }
15731
15732        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15733            if (status != PackageManager.INSTALL_SUCCEEDED) {
15734                cleanUp();
15735                return false;
15736            }
15737
15738            final File targetDir = codeFile.getParentFile();
15739            final File beforeCodeFile = codeFile;
15740            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15741
15742            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15743            try {
15744                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15745            } catch (ErrnoException e) {
15746                Slog.w(TAG, "Failed to rename", e);
15747                return false;
15748            }
15749
15750            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15751                Slog.w(TAG, "Failed to restorecon");
15752                return false;
15753            }
15754
15755            // Reflect the rename internally
15756            codeFile = afterCodeFile;
15757            resourceFile = afterCodeFile;
15758
15759            // Reflect the rename in scanned details
15760            try {
15761                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15762            } catch (IOException e) {
15763                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15764                return false;
15765            }
15766            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15767                    afterCodeFile, pkg.baseCodePath));
15768            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15769                    afterCodeFile, pkg.splitCodePaths));
15770
15771            // Reflect the rename in app info
15772            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15773            pkg.setApplicationInfoCodePath(pkg.codePath);
15774            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15775            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15776            pkg.setApplicationInfoResourcePath(pkg.codePath);
15777            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15778            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15779
15780            return true;
15781        }
15782
15783        int doPostInstall(int status, int uid) {
15784            if (status != PackageManager.INSTALL_SUCCEEDED) {
15785                cleanUp();
15786            }
15787            return status;
15788        }
15789
15790        @Override
15791        String getCodePath() {
15792            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15793        }
15794
15795        @Override
15796        String getResourcePath() {
15797            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15798        }
15799
15800        private boolean cleanUp() {
15801            if (codeFile == null || !codeFile.exists()) {
15802                return false;
15803            }
15804
15805            removeCodePathLI(codeFile);
15806
15807            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15808                resourceFile.delete();
15809            }
15810
15811            return true;
15812        }
15813
15814        void cleanUpResourcesLI() {
15815            // Try enumerating all code paths before deleting
15816            List<String> allCodePaths = Collections.EMPTY_LIST;
15817            if (codeFile != null && codeFile.exists()) {
15818                try {
15819                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15820                    allCodePaths = pkg.getAllCodePaths();
15821                } catch (PackageParserException e) {
15822                    // Ignored; we tried our best
15823                }
15824            }
15825
15826            cleanUp();
15827            removeDexFiles(allCodePaths, instructionSets);
15828        }
15829
15830        boolean doPostDeleteLI(boolean delete) {
15831            // XXX err, shouldn't we respect the delete flag?
15832            cleanUpResourcesLI();
15833            return true;
15834        }
15835    }
15836
15837    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15838            PackageManagerException {
15839        if (copyRet < 0) {
15840            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15841                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15842                throw new PackageManagerException(copyRet, message);
15843            }
15844        }
15845    }
15846
15847    /**
15848     * Extract the StorageManagerService "container ID" from the full code path of an
15849     * .apk.
15850     */
15851    static String cidFromCodePath(String fullCodePath) {
15852        int eidx = fullCodePath.lastIndexOf("/");
15853        String subStr1 = fullCodePath.substring(0, eidx);
15854        int sidx = subStr1.lastIndexOf("/");
15855        return subStr1.substring(sidx+1, eidx);
15856    }
15857
15858    /**
15859     * Logic to handle movement of existing installed applications.
15860     */
15861    class MoveInstallArgs extends InstallArgs {
15862        private File codeFile;
15863        private File resourceFile;
15864
15865        /** New install */
15866        MoveInstallArgs(InstallParams params) {
15867            super(params.origin, params.move, params.observer, params.installFlags,
15868                    params.installerPackageName, params.volumeUuid,
15869                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15870                    params.grantedRuntimePermissions,
15871                    params.traceMethod, params.traceCookie, params.signingDetails,
15872                    params.installReason);
15873        }
15874
15875        int copyApk(IMediaContainerService imcs, boolean temp) {
15876            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15877                    + move.fromUuid + " to " + move.toUuid);
15878            synchronized (mInstaller) {
15879                try {
15880                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15881                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15882                } catch (InstallerException e) {
15883                    Slog.w(TAG, "Failed to move app", e);
15884                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15885                }
15886            }
15887
15888            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15889            resourceFile = codeFile;
15890            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15891
15892            return PackageManager.INSTALL_SUCCEEDED;
15893        }
15894
15895        int doPreInstall(int status) {
15896            if (status != PackageManager.INSTALL_SUCCEEDED) {
15897                cleanUp(move.toUuid);
15898            }
15899            return status;
15900        }
15901
15902        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15903            if (status != PackageManager.INSTALL_SUCCEEDED) {
15904                cleanUp(move.toUuid);
15905                return false;
15906            }
15907
15908            // Reflect the move in app info
15909            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15910            pkg.setApplicationInfoCodePath(pkg.codePath);
15911            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15912            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15913            pkg.setApplicationInfoResourcePath(pkg.codePath);
15914            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15915            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15916
15917            return true;
15918        }
15919
15920        int doPostInstall(int status, int uid) {
15921            if (status == PackageManager.INSTALL_SUCCEEDED) {
15922                cleanUp(move.fromUuid);
15923            } else {
15924                cleanUp(move.toUuid);
15925            }
15926            return status;
15927        }
15928
15929        @Override
15930        String getCodePath() {
15931            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15932        }
15933
15934        @Override
15935        String getResourcePath() {
15936            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15937        }
15938
15939        private boolean cleanUp(String volumeUuid) {
15940            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15941                    move.dataAppName);
15942            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15943            final int[] userIds = sUserManager.getUserIds();
15944            synchronized (mInstallLock) {
15945                // Clean up both app data and code
15946                // All package moves are frozen until finished
15947                for (int userId : userIds) {
15948                    try {
15949                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15950                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15951                    } catch (InstallerException e) {
15952                        Slog.w(TAG, String.valueOf(e));
15953                    }
15954                }
15955                removeCodePathLI(codeFile);
15956            }
15957            return true;
15958        }
15959
15960        void cleanUpResourcesLI() {
15961            throw new UnsupportedOperationException();
15962        }
15963
15964        boolean doPostDeleteLI(boolean delete) {
15965            throw new UnsupportedOperationException();
15966        }
15967    }
15968
15969    static String getAsecPackageName(String packageCid) {
15970        int idx = packageCid.lastIndexOf("-");
15971        if (idx == -1) {
15972            return packageCid;
15973        }
15974        return packageCid.substring(0, idx);
15975    }
15976
15977    // Utility method used to create code paths based on package name and available index.
15978    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15979        String idxStr = "";
15980        int idx = 1;
15981        // Fall back to default value of idx=1 if prefix is not
15982        // part of oldCodePath
15983        if (oldCodePath != null) {
15984            String subStr = oldCodePath;
15985            // Drop the suffix right away
15986            if (suffix != null && subStr.endsWith(suffix)) {
15987                subStr = subStr.substring(0, subStr.length() - suffix.length());
15988            }
15989            // If oldCodePath already contains prefix find out the
15990            // ending index to either increment or decrement.
15991            int sidx = subStr.lastIndexOf(prefix);
15992            if (sidx != -1) {
15993                subStr = subStr.substring(sidx + prefix.length());
15994                if (subStr != null) {
15995                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15996                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15997                    }
15998                    try {
15999                        idx = Integer.parseInt(subStr);
16000                        if (idx <= 1) {
16001                            idx++;
16002                        } else {
16003                            idx--;
16004                        }
16005                    } catch(NumberFormatException e) {
16006                    }
16007                }
16008            }
16009        }
16010        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16011        return prefix + idxStr;
16012    }
16013
16014    private File getNextCodePath(File targetDir, String packageName) {
16015        File result;
16016        SecureRandom random = new SecureRandom();
16017        byte[] bytes = new byte[16];
16018        do {
16019            random.nextBytes(bytes);
16020            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16021            result = new File(targetDir, packageName + "-" + suffix);
16022        } while (result.exists());
16023        return result;
16024    }
16025
16026    // Utility method that returns the relative package path with respect
16027    // to the installation directory. Like say for /data/data/com.test-1.apk
16028    // string com.test-1 is returned.
16029    static String deriveCodePathName(String codePath) {
16030        if (codePath == null) {
16031            return null;
16032        }
16033        final File codeFile = new File(codePath);
16034        final String name = codeFile.getName();
16035        if (codeFile.isDirectory()) {
16036            return name;
16037        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16038            final int lastDot = name.lastIndexOf('.');
16039            return name.substring(0, lastDot);
16040        } else {
16041            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16042            return null;
16043        }
16044    }
16045
16046    static class PackageInstalledInfo {
16047        String name;
16048        int uid;
16049        // The set of users that originally had this package installed.
16050        int[] origUsers;
16051        // The set of users that now have this package installed.
16052        int[] newUsers;
16053        PackageParser.Package pkg;
16054        int returnCode;
16055        String returnMsg;
16056        String installerPackageName;
16057        PackageRemovedInfo removedInfo;
16058        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16059
16060        public void setError(int code, String msg) {
16061            setReturnCode(code);
16062            setReturnMessage(msg);
16063            Slog.w(TAG, msg);
16064        }
16065
16066        public void setError(String msg, PackageParserException e) {
16067            setReturnCode(e.error);
16068            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16069            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16070            for (int i = 0; i < childCount; i++) {
16071                addedChildPackages.valueAt(i).setError(msg, e);
16072            }
16073            Slog.w(TAG, msg, e);
16074        }
16075
16076        public void setError(String msg, PackageManagerException e) {
16077            returnCode = e.error;
16078            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16079            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16080            for (int i = 0; i < childCount; i++) {
16081                addedChildPackages.valueAt(i).setError(msg, e);
16082            }
16083            Slog.w(TAG, msg, e);
16084        }
16085
16086        public void setReturnCode(int returnCode) {
16087            this.returnCode = returnCode;
16088            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16089            for (int i = 0; i < childCount; i++) {
16090                addedChildPackages.valueAt(i).returnCode = returnCode;
16091            }
16092        }
16093
16094        private void setReturnMessage(String returnMsg) {
16095            this.returnMsg = returnMsg;
16096            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16097            for (int i = 0; i < childCount; i++) {
16098                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16099            }
16100        }
16101
16102        // In some error cases we want to convey more info back to the observer
16103        String origPackage;
16104        String origPermission;
16105    }
16106
16107    /*
16108     * Install a non-existing package.
16109     */
16110    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16111            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16112            String volumeUuid, PackageInstalledInfo res, int installReason) {
16113        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16114
16115        // Remember this for later, in case we need to rollback this install
16116        String pkgName = pkg.packageName;
16117
16118        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16119
16120        synchronized(mPackages) {
16121            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16122            if (renamedPackage != null) {
16123                // A package with the same name is already installed, though
16124                // it has been renamed to an older name.  The package we
16125                // are trying to install should be installed as an update to
16126                // the existing one, but that has not been requested, so bail.
16127                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16128                        + " without first uninstalling package running as "
16129                        + renamedPackage);
16130                return;
16131            }
16132            if (mPackages.containsKey(pkgName)) {
16133                // Don't allow installation over an existing package with the same name.
16134                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16135                        + " without first uninstalling.");
16136                return;
16137            }
16138        }
16139
16140        try {
16141            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
16142                    System.currentTimeMillis(), user);
16143
16144            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16145
16146            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16147                prepareAppDataAfterInstallLIF(newPackage);
16148
16149            } else {
16150                // Remove package from internal structures, but keep around any
16151                // data that might have already existed
16152                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16153                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16154            }
16155        } catch (PackageManagerException e) {
16156            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16157        }
16158
16159        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16160    }
16161
16162    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16163        try (DigestInputStream digestStream =
16164                new DigestInputStream(new FileInputStream(file), digest)) {
16165            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16166        }
16167    }
16168
16169    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16170            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16171            PackageInstalledInfo res, int installReason) {
16172        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16173
16174        final PackageParser.Package oldPackage;
16175        final PackageSetting ps;
16176        final String pkgName = pkg.packageName;
16177        final int[] allUsers;
16178        final int[] installedUsers;
16179
16180        synchronized(mPackages) {
16181            oldPackage = mPackages.get(pkgName);
16182            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16183
16184            // don't allow upgrade to target a release SDK from a pre-release SDK
16185            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16186                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16187            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16188                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16189            if (oldTargetsPreRelease
16190                    && !newTargetsPreRelease
16191                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16192                Slog.w(TAG, "Can't install package targeting released sdk");
16193                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16194                return;
16195            }
16196
16197            ps = mSettings.mPackages.get(pkgName);
16198
16199            // verify signatures are valid
16200            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16201            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16202                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16203                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16204                            "New package not signed by keys specified by upgrade-keysets: "
16205                                    + pkgName);
16206                    return;
16207                }
16208            } else {
16209
16210                // default to original signature matching
16211                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16212                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
16213                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16214                            "New package has a different signature: " + pkgName);
16215                    return;
16216                }
16217            }
16218
16219            // don't allow a system upgrade unless the upgrade hash matches
16220            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16221                byte[] digestBytes = null;
16222                try {
16223                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16224                    updateDigest(digest, new File(pkg.baseCodePath));
16225                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16226                        for (String path : pkg.splitCodePaths) {
16227                            updateDigest(digest, new File(path));
16228                        }
16229                    }
16230                    digestBytes = digest.digest();
16231                } catch (NoSuchAlgorithmException | IOException e) {
16232                    res.setError(INSTALL_FAILED_INVALID_APK,
16233                            "Could not compute hash: " + pkgName);
16234                    return;
16235                }
16236                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16237                    res.setError(INSTALL_FAILED_INVALID_APK,
16238                            "New package fails restrict-update check: " + pkgName);
16239                    return;
16240                }
16241                // retain upgrade restriction
16242                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16243            }
16244
16245            // Check for shared user id changes
16246            String invalidPackageName =
16247                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16248            if (invalidPackageName != null) {
16249                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16250                        "Package " + invalidPackageName + " tried to change user "
16251                                + oldPackage.mSharedUserId);
16252                return;
16253            }
16254
16255            // check if the new package supports all of the abis which the old package supports
16256            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16257            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16258            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16259                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16260                        "Update to package " + pkgName + " doesn't support multi arch");
16261                return;
16262            }
16263
16264            // In case of rollback, remember per-user/profile install state
16265            allUsers = sUserManager.getUserIds();
16266            installedUsers = ps.queryInstalledUsers(allUsers, true);
16267
16268            // don't allow an upgrade from full to ephemeral
16269            if (isInstantApp) {
16270                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16271                    for (int currentUser : allUsers) {
16272                        if (!ps.getInstantApp(currentUser)) {
16273                            // can't downgrade from full to instant
16274                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16275                                    + " for user: " + currentUser);
16276                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16277                            return;
16278                        }
16279                    }
16280                } else if (!ps.getInstantApp(user.getIdentifier())) {
16281                    // can't downgrade from full to instant
16282                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16283                            + " for user: " + user.getIdentifier());
16284                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16285                    return;
16286                }
16287            }
16288        }
16289
16290        // Update what is removed
16291        res.removedInfo = new PackageRemovedInfo(this);
16292        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16293        res.removedInfo.removedPackage = oldPackage.packageName;
16294        res.removedInfo.installerPackageName = ps.installerPackageName;
16295        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16296        res.removedInfo.isUpdate = true;
16297        res.removedInfo.origUsers = installedUsers;
16298        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16299        for (int i = 0; i < installedUsers.length; i++) {
16300            final int userId = installedUsers[i];
16301            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16302        }
16303
16304        final int childCount = (oldPackage.childPackages != null)
16305                ? oldPackage.childPackages.size() : 0;
16306        for (int i = 0; i < childCount; i++) {
16307            boolean childPackageUpdated = false;
16308            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16309            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16310            if (res.addedChildPackages != null) {
16311                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16312                if (childRes != null) {
16313                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16314                    childRes.removedInfo.removedPackage = childPkg.packageName;
16315                    if (childPs != null) {
16316                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16317                    }
16318                    childRes.removedInfo.isUpdate = true;
16319                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16320                    childPackageUpdated = true;
16321                }
16322            }
16323            if (!childPackageUpdated) {
16324                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16325                childRemovedRes.removedPackage = childPkg.packageName;
16326                if (childPs != null) {
16327                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16328                }
16329                childRemovedRes.isUpdate = false;
16330                childRemovedRes.dataRemoved = true;
16331                synchronized (mPackages) {
16332                    if (childPs != null) {
16333                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16334                    }
16335                }
16336                if (res.removedInfo.removedChildPackages == null) {
16337                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16338                }
16339                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16340            }
16341        }
16342
16343        boolean sysPkg = (isSystemApp(oldPackage));
16344        if (sysPkg) {
16345            // Set the system/privileged/oem/vendor/product flags as needed
16346            final boolean privileged =
16347                    (oldPackage.applicationInfo.privateFlags
16348                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16349            final boolean oem =
16350                    (oldPackage.applicationInfo.privateFlags
16351                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16352            final boolean vendor =
16353                    (oldPackage.applicationInfo.privateFlags
16354                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16355            final boolean product =
16356                    (oldPackage.applicationInfo.privateFlags
16357                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16358            final @ParseFlags int systemParseFlags = parseFlags;
16359            final @ScanFlags int systemScanFlags = scanFlags
16360                    | SCAN_AS_SYSTEM
16361                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16362                    | (oem ? SCAN_AS_OEM : 0)
16363                    | (vendor ? SCAN_AS_VENDOR : 0)
16364                    | (product ? SCAN_AS_PRODUCT : 0);
16365
16366            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16367                    user, allUsers, installerPackageName, res, installReason);
16368        } else {
16369            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16370                    user, allUsers, installerPackageName, res, installReason);
16371        }
16372    }
16373
16374    @Override
16375    public List<String> getPreviousCodePaths(String packageName) {
16376        final int callingUid = Binder.getCallingUid();
16377        final List<String> result = new ArrayList<>();
16378        if (getInstantAppPackageName(callingUid) != null) {
16379            return result;
16380        }
16381        final PackageSetting ps = mSettings.mPackages.get(packageName);
16382        if (ps != null
16383                && ps.oldCodePaths != null
16384                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16385            result.addAll(ps.oldCodePaths);
16386        }
16387        return result;
16388    }
16389
16390    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16391            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16392            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16393            String installerPackageName, PackageInstalledInfo res, int installReason) {
16394        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16395                + deletedPackage);
16396
16397        String pkgName = deletedPackage.packageName;
16398        boolean deletedPkg = true;
16399        boolean addedPkg = false;
16400        boolean updatedSettings = false;
16401        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16402        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16403                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16404
16405        final long origUpdateTime = (pkg.mExtras != null)
16406                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16407
16408        // First delete the existing package while retaining the data directory
16409        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16410                res.removedInfo, true, pkg)) {
16411            // If the existing package wasn't successfully deleted
16412            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16413            deletedPkg = false;
16414        } else {
16415            // Successfully deleted the old package; proceed with replace.
16416
16417            // If deleted package lived in a container, give users a chance to
16418            // relinquish resources before killing.
16419            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16420                if (DEBUG_INSTALL) {
16421                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16422                }
16423                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16424                final ArrayList<String> pkgList = new ArrayList<String>(1);
16425                pkgList.add(deletedPackage.applicationInfo.packageName);
16426                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16427            }
16428
16429            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16430                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16431
16432            try {
16433                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16434                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16435                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16436                        installReason);
16437
16438                // Update the in-memory copy of the previous code paths.
16439                PackageSetting ps = mSettings.mPackages.get(pkgName);
16440                if (!killApp) {
16441                    if (ps.oldCodePaths == null) {
16442                        ps.oldCodePaths = new ArraySet<>();
16443                    }
16444                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16445                    if (deletedPackage.splitCodePaths != null) {
16446                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16447                    }
16448                } else {
16449                    ps.oldCodePaths = null;
16450                }
16451                if (ps.childPackageNames != null) {
16452                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16453                        final String childPkgName = ps.childPackageNames.get(i);
16454                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16455                        childPs.oldCodePaths = ps.oldCodePaths;
16456                    }
16457                }
16458                // set instant app status, but, only if it's explicitly specified
16459                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16460                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16461                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16462                prepareAppDataAfterInstallLIF(newPackage);
16463                addedPkg = true;
16464                mDexManager.notifyPackageUpdated(newPackage.packageName,
16465                        newPackage.baseCodePath, newPackage.splitCodePaths);
16466            } catch (PackageManagerException e) {
16467                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16468            }
16469        }
16470
16471        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16472            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16473
16474            // Revert all internal state mutations and added folders for the failed install
16475            if (addedPkg) {
16476                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16477                        res.removedInfo, true, null);
16478            }
16479
16480            // Restore the old package
16481            if (deletedPkg) {
16482                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16483                File restoreFile = new File(deletedPackage.codePath);
16484                // Parse old package
16485                boolean oldExternal = isExternal(deletedPackage);
16486                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16487                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16488                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16489                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16490                try {
16491                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16492                            null);
16493                } catch (PackageManagerException e) {
16494                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16495                            + e.getMessage());
16496                    return;
16497                }
16498
16499                synchronized (mPackages) {
16500                    // Ensure the installer package name up to date
16501                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16502
16503                    // Update permissions for restored package
16504                    mPermissionManager.updatePermissions(
16505                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16506                            mPermissionCallback);
16507
16508                    mSettings.writeLPr();
16509                }
16510
16511                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16512            }
16513        } else {
16514            synchronized (mPackages) {
16515                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16516                if (ps != null) {
16517                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16518                    if (res.removedInfo.removedChildPackages != null) {
16519                        final int childCount = res.removedInfo.removedChildPackages.size();
16520                        // Iterate in reverse as we may modify the collection
16521                        for (int i = childCount - 1; i >= 0; i--) {
16522                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16523                            if (res.addedChildPackages.containsKey(childPackageName)) {
16524                                res.removedInfo.removedChildPackages.removeAt(i);
16525                            } else {
16526                                PackageRemovedInfo childInfo = res.removedInfo
16527                                        .removedChildPackages.valueAt(i);
16528                                childInfo.removedForAllUsers = mPackages.get(
16529                                        childInfo.removedPackage) == null;
16530                            }
16531                        }
16532                    }
16533                }
16534            }
16535        }
16536    }
16537
16538    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16539            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16540            final @ScanFlags int scanFlags, UserHandle user,
16541            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16542            int installReason) {
16543        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16544                + ", old=" + deletedPackage);
16545
16546        final boolean disabledSystem;
16547
16548        // Remove existing system package
16549        removePackageLI(deletedPackage, true);
16550
16551        synchronized (mPackages) {
16552            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16553        }
16554        if (!disabledSystem) {
16555            // We didn't need to disable the .apk as a current system package,
16556            // which means we are replacing another update that is already
16557            // installed.  We need to make sure to delete the older one's .apk.
16558            res.removedInfo.args = createInstallArgsForExisting(0,
16559                    deletedPackage.applicationInfo.getCodePath(),
16560                    deletedPackage.applicationInfo.getResourcePath(),
16561                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16562        } else {
16563            res.removedInfo.args = null;
16564        }
16565
16566        // Successfully disabled the old package. Now proceed with re-installation
16567        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16568                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16569
16570        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16571        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16572                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16573
16574        PackageParser.Package newPackage = null;
16575        try {
16576            // Add the package to the internal data structures
16577            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16578
16579            // Set the update and install times
16580            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16581            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16582                    System.currentTimeMillis());
16583
16584            // Update the package dynamic state if succeeded
16585            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16586                // Now that the install succeeded make sure we remove data
16587                // directories for any child package the update removed.
16588                final int deletedChildCount = (deletedPackage.childPackages != null)
16589                        ? deletedPackage.childPackages.size() : 0;
16590                final int newChildCount = (newPackage.childPackages != null)
16591                        ? newPackage.childPackages.size() : 0;
16592                for (int i = 0; i < deletedChildCount; i++) {
16593                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16594                    boolean childPackageDeleted = true;
16595                    for (int j = 0; j < newChildCount; j++) {
16596                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16597                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16598                            childPackageDeleted = false;
16599                            break;
16600                        }
16601                    }
16602                    if (childPackageDeleted) {
16603                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16604                                deletedChildPkg.packageName);
16605                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16606                            PackageRemovedInfo removedChildRes = res.removedInfo
16607                                    .removedChildPackages.get(deletedChildPkg.packageName);
16608                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16609                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16610                        }
16611                    }
16612                }
16613
16614                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16615                        installReason);
16616                prepareAppDataAfterInstallLIF(newPackage);
16617
16618                mDexManager.notifyPackageUpdated(newPackage.packageName,
16619                            newPackage.baseCodePath, newPackage.splitCodePaths);
16620            }
16621        } catch (PackageManagerException e) {
16622            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16623            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16624        }
16625
16626        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16627            // Re installation failed. Restore old information
16628            // Remove new pkg information
16629            if (newPackage != null) {
16630                removeInstalledPackageLI(newPackage, true);
16631            }
16632            // Add back the old system package
16633            try {
16634                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16635            } catch (PackageManagerException e) {
16636                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16637            }
16638
16639            synchronized (mPackages) {
16640                if (disabledSystem) {
16641                    enableSystemPackageLPw(deletedPackage);
16642                }
16643
16644                // Ensure the installer package name up to date
16645                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16646
16647                // Update permissions for restored package
16648                mPermissionManager.updatePermissions(
16649                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16650                        mPermissionCallback);
16651
16652                mSettings.writeLPr();
16653            }
16654
16655            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16656                    + " after failed upgrade");
16657        }
16658    }
16659
16660    /**
16661     * Checks whether the parent or any of the child packages have a change shared
16662     * user. For a package to be a valid update the shred users of the parent and
16663     * the children should match. We may later support changing child shared users.
16664     * @param oldPkg The updated package.
16665     * @param newPkg The update package.
16666     * @return The shared user that change between the versions.
16667     */
16668    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16669            PackageParser.Package newPkg) {
16670        // Check parent shared user
16671        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16672            return newPkg.packageName;
16673        }
16674        // Check child shared users
16675        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16676        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16677        for (int i = 0; i < newChildCount; i++) {
16678            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16679            // If this child was present, did it have the same shared user?
16680            for (int j = 0; j < oldChildCount; j++) {
16681                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16682                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16683                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16684                    return newChildPkg.packageName;
16685                }
16686            }
16687        }
16688        return null;
16689    }
16690
16691    private void removeNativeBinariesLI(PackageSetting ps) {
16692        // Remove the lib path for the parent package
16693        if (ps != null) {
16694            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16695            // Remove the lib path for the child packages
16696            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16697            for (int i = 0; i < childCount; i++) {
16698                PackageSetting childPs = null;
16699                synchronized (mPackages) {
16700                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16701                }
16702                if (childPs != null) {
16703                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16704                            .legacyNativeLibraryPathString);
16705                }
16706            }
16707        }
16708    }
16709
16710    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16711        // Enable the parent package
16712        mSettings.enableSystemPackageLPw(pkg.packageName);
16713        // Enable the child packages
16714        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16715        for (int i = 0; i < childCount; i++) {
16716            PackageParser.Package childPkg = pkg.childPackages.get(i);
16717            mSettings.enableSystemPackageLPw(childPkg.packageName);
16718        }
16719    }
16720
16721    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16722            PackageParser.Package newPkg) {
16723        // Disable the parent package (parent always replaced)
16724        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16725        // Disable the child packages
16726        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16727        for (int i = 0; i < childCount; i++) {
16728            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16729            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16730            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16731        }
16732        return disabled;
16733    }
16734
16735    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16736            String installerPackageName) {
16737        // Enable the parent package
16738        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16739        // Enable the child packages
16740        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16741        for (int i = 0; i < childCount; i++) {
16742            PackageParser.Package childPkg = pkg.childPackages.get(i);
16743            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16744        }
16745    }
16746
16747    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16748            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16749        // Update the parent package setting
16750        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16751                res, user, installReason);
16752        // Update the child packages setting
16753        final int childCount = (newPackage.childPackages != null)
16754                ? newPackage.childPackages.size() : 0;
16755        for (int i = 0; i < childCount; i++) {
16756            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16757            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16758            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16759                    childRes.origUsers, childRes, user, installReason);
16760        }
16761    }
16762
16763    private void updateSettingsInternalLI(PackageParser.Package pkg,
16764            String installerPackageName, int[] allUsers, int[] installedForUsers,
16765            PackageInstalledInfo res, UserHandle user, int installReason) {
16766        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16767
16768        final String pkgName = pkg.packageName;
16769
16770        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16771        synchronized (mPackages) {
16772// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16773            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16774                    mPermissionCallback);
16775            // For system-bundled packages, we assume that installing an upgraded version
16776            // of the package implies that the user actually wants to run that new code,
16777            // so we enable the package.
16778            PackageSetting ps = mSettings.mPackages.get(pkgName);
16779            final int userId = user.getIdentifier();
16780            if (ps != null) {
16781                if (isSystemApp(pkg)) {
16782                    if (DEBUG_INSTALL) {
16783                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16784                    }
16785                    // Enable system package for requested users
16786                    if (res.origUsers != null) {
16787                        for (int origUserId : res.origUsers) {
16788                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16789                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16790                                        origUserId, installerPackageName);
16791                            }
16792                        }
16793                    }
16794                    // Also convey the prior install/uninstall state
16795                    if (allUsers != null && installedForUsers != null) {
16796                        for (int currentUserId : allUsers) {
16797                            final boolean installed = ArrayUtils.contains(
16798                                    installedForUsers, currentUserId);
16799                            if (DEBUG_INSTALL) {
16800                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16801                            }
16802                            ps.setInstalled(installed, currentUserId);
16803                        }
16804                        // these install state changes will be persisted in the
16805                        // upcoming call to mSettings.writeLPr().
16806                    }
16807                }
16808                // It's implied that when a user requests installation, they want the app to be
16809                // installed and enabled.
16810                if (userId != UserHandle.USER_ALL) {
16811                    ps.setInstalled(true, userId);
16812                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16813                } else {
16814                    for (int currentUserId : sUserManager.getUserIds()) {
16815                        ps.setInstalled(true, currentUserId);
16816                        ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, currentUserId,
16817                                installerPackageName);
16818                    }
16819                }
16820
16821                // When replacing an existing package, preserve the original install reason for all
16822                // users that had the package installed before.
16823                final Set<Integer> previousUserIds = new ArraySet<>();
16824                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16825                    final int installReasonCount = res.removedInfo.installReasons.size();
16826                    for (int i = 0; i < installReasonCount; i++) {
16827                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16828                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16829                        ps.setInstallReason(previousInstallReason, previousUserId);
16830                        previousUserIds.add(previousUserId);
16831                    }
16832                }
16833
16834                // Set install reason for users that are having the package newly installed.
16835                if (userId == UserHandle.USER_ALL) {
16836                    for (int currentUserId : sUserManager.getUserIds()) {
16837                        if (!previousUserIds.contains(currentUserId)) {
16838                            ps.setInstallReason(installReason, currentUserId);
16839                        }
16840                    }
16841                } else if (!previousUserIds.contains(userId)) {
16842                    ps.setInstallReason(installReason, userId);
16843                }
16844                mSettings.writeKernelMappingLPr(ps);
16845            }
16846            res.name = pkgName;
16847            res.uid = pkg.applicationInfo.uid;
16848            res.pkg = pkg;
16849            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16850            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16851            //to update install status
16852            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16853            mSettings.writeLPr();
16854            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16855        }
16856
16857        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16858    }
16859
16860    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16861        try {
16862            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16863            installPackageLI(args, res);
16864        } finally {
16865            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16866        }
16867    }
16868
16869    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16870        final int installFlags = args.installFlags;
16871        final String installerPackageName = args.installerPackageName;
16872        final String volumeUuid = args.volumeUuid;
16873        final File tmpPackageFile = new File(args.getCodePath());
16874        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16875        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16876                || (args.volumeUuid != null));
16877        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16878        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16879        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16880        final boolean virtualPreload =
16881                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16882        boolean replace = false;
16883        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16884        if (args.move != null) {
16885            // moving a complete application; perform an initial scan on the new install location
16886            scanFlags |= SCAN_INITIAL;
16887        }
16888        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16889            scanFlags |= SCAN_DONT_KILL_APP;
16890        }
16891        if (instantApp) {
16892            scanFlags |= SCAN_AS_INSTANT_APP;
16893        }
16894        if (fullApp) {
16895            scanFlags |= SCAN_AS_FULL_APP;
16896        }
16897        if (virtualPreload) {
16898            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16899        }
16900
16901        // Result object to be returned
16902        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16903        res.installerPackageName = installerPackageName;
16904
16905        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16906
16907        // Sanity check
16908        if (instantApp && (forwardLocked || onExternal)) {
16909            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16910                    + " external=" + onExternal);
16911            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16912            return;
16913        }
16914
16915        // Retrieve PackageSettings and parse package
16916        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16917                | PackageParser.PARSE_ENFORCE_CODE
16918                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16919                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16920                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16921        PackageParser pp = new PackageParser();
16922        pp.setSeparateProcesses(mSeparateProcesses);
16923        pp.setDisplayMetrics(mMetrics);
16924        pp.setCallback(mPackageParserCallback);
16925
16926        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16927        final PackageParser.Package pkg;
16928        try {
16929            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16930            DexMetadataHelper.validatePackageDexMetadata(pkg);
16931        } catch (PackageParserException e) {
16932            res.setError("Failed parse during installPackageLI", e);
16933            return;
16934        } finally {
16935            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16936        }
16937
16938        // Instant apps have several additional install-time checks.
16939        if (instantApp) {
16940            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16941                Slog.w(TAG,
16942                        "Instant app package " + pkg.packageName + " does not target at least O");
16943                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16944                        "Instant app package must target at least O");
16945                return;
16946            }
16947            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16948                Slog.w(TAG, "Instant app package " + pkg.packageName
16949                        + " does not target targetSandboxVersion 2");
16950                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16951                        "Instant app package must use targetSandboxVersion 2");
16952                return;
16953            }
16954            if (pkg.mSharedUserId != null) {
16955                Slog.w(TAG, "Instant app package " + pkg.packageName
16956                        + " may not declare sharedUserId.");
16957                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16958                        "Instant app package may not declare a sharedUserId");
16959                return;
16960            }
16961        }
16962
16963        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16964            // Static shared libraries have synthetic package names
16965            renameStaticSharedLibraryPackage(pkg);
16966
16967            // No static shared libs on external storage
16968            if (onExternal) {
16969                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16970                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16971                        "Packages declaring static-shared libs cannot be updated");
16972                return;
16973            }
16974        }
16975
16976        // If we are installing a clustered package add results for the children
16977        if (pkg.childPackages != null) {
16978            synchronized (mPackages) {
16979                final int childCount = pkg.childPackages.size();
16980                for (int i = 0; i < childCount; i++) {
16981                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16982                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16983                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16984                    childRes.pkg = childPkg;
16985                    childRes.name = childPkg.packageName;
16986                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16987                    if (childPs != null) {
16988                        childRes.origUsers = childPs.queryInstalledUsers(
16989                                sUserManager.getUserIds(), true);
16990                    }
16991                    if ((mPackages.containsKey(childPkg.packageName))) {
16992                        childRes.removedInfo = new PackageRemovedInfo(this);
16993                        childRes.removedInfo.removedPackage = childPkg.packageName;
16994                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16995                    }
16996                    if (res.addedChildPackages == null) {
16997                        res.addedChildPackages = new ArrayMap<>();
16998                    }
16999                    res.addedChildPackages.put(childPkg.packageName, childRes);
17000                }
17001            }
17002        }
17003
17004        // If package doesn't declare API override, mark that we have an install
17005        // time CPU ABI override.
17006        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17007            pkg.cpuAbiOverride = args.abiOverride;
17008        }
17009
17010        String pkgName = res.name = pkg.packageName;
17011        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17012            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17013                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17014                return;
17015            }
17016        }
17017
17018        try {
17019            // either use what we've been given or parse directly from the APK
17020            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
17021                pkg.setSigningDetails(args.signingDetails);
17022            } else {
17023                PackageParser.collectCertificates(pkg, false /* skipVerify */);
17024            }
17025        } catch (PackageParserException e) {
17026            res.setError("Failed collect during installPackageLI", e);
17027            return;
17028        }
17029
17030        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
17031                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
17032            Slog.w(TAG, "Instant app package " + pkg.packageName
17033                    + " is not signed with at least APK Signature Scheme v2");
17034            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17035                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
17036            return;
17037        }
17038
17039        // Get rid of all references to package scan path via parser.
17040        pp = null;
17041        String oldCodePath = null;
17042        boolean systemApp = false;
17043        synchronized (mPackages) {
17044            // Check if installing already existing package
17045            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17046                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17047                if (pkg.mOriginalPackages != null
17048                        && pkg.mOriginalPackages.contains(oldName)
17049                        && mPackages.containsKey(oldName)) {
17050                    // This package is derived from an original package,
17051                    // and this device has been updating from that original
17052                    // name.  We must continue using the original name, so
17053                    // rename the new package here.
17054                    pkg.setPackageName(oldName);
17055                    pkgName = pkg.packageName;
17056                    replace = true;
17057                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17058                            + oldName + " pkgName=" + pkgName);
17059                } else if (mPackages.containsKey(pkgName)) {
17060                    // This package, under its official name, already exists
17061                    // on the device; we should replace it.
17062                    replace = true;
17063                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17064                }
17065
17066                // Child packages are installed through the parent package
17067                if (pkg.parentPackage != null) {
17068                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17069                            "Package " + pkg.packageName + " is child of package "
17070                                    + pkg.parentPackage.parentPackage + ". Child packages "
17071                                    + "can be updated only through the parent package.");
17072                    return;
17073                }
17074
17075                if (replace) {
17076                    // Prevent apps opting out from runtime permissions
17077                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17078                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17079                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17080                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17081                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17082                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17083                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17084                                        + " doesn't support runtime permissions but the old"
17085                                        + " target SDK " + oldTargetSdk + " does.");
17086                        return;
17087                    }
17088                    // Prevent persistent apps from being updated
17089                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
17090                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
17091                                "Package " + oldPackage.packageName + " is a persistent app. "
17092                                        + "Persistent apps are not updateable.");
17093                        return;
17094                    }
17095                    // Prevent apps from downgrading their targetSandbox.
17096                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17097                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17098                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17099                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17100                                "Package " + pkg.packageName + " new target sandbox "
17101                                + newTargetSandbox + " is incompatible with the previous value of"
17102                                + oldTargetSandbox + ".");
17103                        return;
17104                    }
17105
17106                    // Prevent installing of child packages
17107                    if (oldPackage.parentPackage != null) {
17108                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17109                                "Package " + pkg.packageName + " is child of package "
17110                                        + oldPackage.parentPackage + ". Child packages "
17111                                        + "can be updated only through the parent package.");
17112                        return;
17113                    }
17114                }
17115            }
17116
17117            PackageSetting ps = mSettings.mPackages.get(pkgName);
17118            if (ps != null) {
17119                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17120
17121                // Static shared libs have same package with different versions where
17122                // we internally use a synthetic package name to allow multiple versions
17123                // of the same package, therefore we need to compare signatures against
17124                // the package setting for the latest library version.
17125                PackageSetting signatureCheckPs = ps;
17126                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17127                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17128                    if (libraryEntry != null) {
17129                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17130                    }
17131                }
17132
17133                // Quick sanity check that we're signed correctly if updating;
17134                // we'll check this again later when scanning, but we want to
17135                // bail early here before tripping over redefined permissions.
17136                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17137                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
17138                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
17139                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17140                                + pkg.packageName + " upgrade keys do not match the "
17141                                + "previously installed version");
17142                        return;
17143                    }
17144                } else {
17145                    try {
17146                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
17147                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
17148                        // We don't care about disabledPkgSetting on install for now.
17149                        final boolean compatMatch = verifySignatures(
17150                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
17151                                compareRecover);
17152                        // The new KeySets will be re-added later in the scanning process.
17153                        if (compatMatch) {
17154                            synchronized (mPackages) {
17155                                ksms.removeAppKeySetDataLPw(pkg.packageName);
17156                            }
17157                        }
17158                    } catch (PackageManagerException e) {
17159                        res.setError(e.error, e.getMessage());
17160                        return;
17161                    }
17162                }
17163
17164                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17165                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17166                    systemApp = (ps.pkg.applicationInfo.flags &
17167                            ApplicationInfo.FLAG_SYSTEM) != 0;
17168                }
17169                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17170            }
17171
17172            int N = pkg.permissions.size();
17173            for (int i = N-1; i >= 0; i--) {
17174                final PackageParser.Permission perm = pkg.permissions.get(i);
17175                final BasePermission bp =
17176                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17177
17178                // Don't allow anyone but the system to define ephemeral permissions.
17179                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17180                        && !systemApp) {
17181                    Slog.w(TAG, "Non-System package " + pkg.packageName
17182                            + " attempting to delcare ephemeral permission "
17183                            + perm.info.name + "; Removing ephemeral.");
17184                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17185                }
17186
17187                // Check whether the newly-scanned package wants to define an already-defined perm
17188                if (bp != null) {
17189                    // If the defining package is signed with our cert, it's okay.  This
17190                    // also includes the "updating the same package" case, of course.
17191                    // "updating same package" could also involve key-rotation.
17192                    final boolean sigsOk;
17193                    final String sourcePackageName = bp.getSourcePackageName();
17194                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17195                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17196                    if (sourcePackageName.equals(pkg.packageName)
17197                            && (ksms.shouldCheckUpgradeKeySetLocked(
17198                                    sourcePackageSetting, scanFlags))) {
17199                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17200                    } else {
17201
17202                        // in the event of signing certificate rotation, we need to see if the
17203                        // package's certificate has rotated from the current one, or if it is an
17204                        // older certificate with which the current is ok with sharing permissions
17205                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17206                                        pkg.mSigningDetails,
17207                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17208                            sigsOk = true;
17209                        } else if (pkg.mSigningDetails.checkCapability(
17210                                        sourcePackageSetting.signatures.mSigningDetails,
17211                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17212
17213                            // the scanned package checks out, has signing certificate rotation
17214                            // history, and is newer; bring it over
17215                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17216                            sigsOk = true;
17217                        } else {
17218                            sigsOk = false;
17219                        }
17220                    }
17221                    if (!sigsOk) {
17222                        // If the owning package is the system itself, we log but allow
17223                        // install to proceed; we fail the install on all other permission
17224                        // redefinitions.
17225                        if (!sourcePackageName.equals("android")) {
17226                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17227                                    + pkg.packageName + " attempting to redeclare permission "
17228                                    + perm.info.name + " already owned by " + sourcePackageName);
17229                            res.origPermission = perm.info.name;
17230                            res.origPackage = sourcePackageName;
17231                            return;
17232                        } else {
17233                            Slog.w(TAG, "Package " + pkg.packageName
17234                                    + " attempting to redeclare system permission "
17235                                    + perm.info.name + "; ignoring new declaration");
17236                            pkg.permissions.remove(i);
17237                        }
17238                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17239                        // Prevent apps to change protection level to dangerous from any other
17240                        // type as this would allow a privilege escalation where an app adds a
17241                        // normal/signature permission in other app's group and later redefines
17242                        // it as dangerous leading to the group auto-grant.
17243                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17244                                == PermissionInfo.PROTECTION_DANGEROUS) {
17245                            if (bp != null && !bp.isRuntime()) {
17246                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17247                                        + "non-runtime permission " + perm.info.name
17248                                        + " to runtime; keeping old protection level");
17249                                perm.info.protectionLevel = bp.getProtectionLevel();
17250                            }
17251                        }
17252                    }
17253                }
17254            }
17255        }
17256
17257        if (systemApp) {
17258            if (onExternal) {
17259                // Abort update; system app can't be replaced with app on sdcard
17260                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17261                        "Cannot install updates to system apps on sdcard");
17262                return;
17263            } else if (instantApp) {
17264                // Abort update; system app can't be replaced with an instant app
17265                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17266                        "Cannot update a system app with an instant app");
17267                return;
17268            }
17269        }
17270
17271        if (args.move != null) {
17272            // We did an in-place move, so dex is ready to roll
17273            scanFlags |= SCAN_NO_DEX;
17274            scanFlags |= SCAN_MOVE;
17275
17276            synchronized (mPackages) {
17277                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17278                if (ps == null) {
17279                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17280                            "Missing settings for moved package " + pkgName);
17281                }
17282
17283                // We moved the entire application as-is, so bring over the
17284                // previously derived ABI information.
17285                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17286                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17287            }
17288
17289        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17290            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17291            scanFlags |= SCAN_NO_DEX;
17292
17293            try {
17294                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17295                    args.abiOverride : pkg.cpuAbiOverride);
17296                final boolean extractNativeLibs = !pkg.isLibrary();
17297                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17298            } catch (PackageManagerException pme) {
17299                Slog.e(TAG, "Error deriving application ABI", pme);
17300                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17301                return;
17302            }
17303
17304            // Shared libraries for the package need to be updated.
17305            synchronized (mPackages) {
17306                try {
17307                    updateSharedLibrariesLPr(pkg, null);
17308                } catch (PackageManagerException e) {
17309                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17310                }
17311            }
17312        }
17313
17314        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17315            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17316            return;
17317        }
17318
17319        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17320            String apkPath = null;
17321            synchronized (mPackages) {
17322                // Note that if the attacker managed to skip verify setup, for example by tampering
17323                // with the package settings, upon reboot we will do full apk verification when
17324                // verity is not detected.
17325                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17326                if (ps != null && ps.isPrivileged()) {
17327                    apkPath = pkg.baseCodePath;
17328                }
17329            }
17330
17331            if (apkPath != null) {
17332                final VerityUtils.SetupResult result =
17333                        VerityUtils.generateApkVeritySetupData(apkPath);
17334                if (result.isOk()) {
17335                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17336                    FileDescriptor fd = result.getUnownedFileDescriptor();
17337                    try {
17338                        mInstaller.installApkVerity(apkPath, fd);
17339                    } catch (InstallerException e) {
17340                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17341                                "Failed to set up verity: " + e);
17342                        return;
17343                    } finally {
17344                        IoUtils.closeQuietly(fd);
17345                    }
17346                } else if (result.isFailed()) {
17347                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17348                    return;
17349                } else {
17350                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17351                    // reboot.
17352                }
17353            }
17354        }
17355
17356        if (!instantApp) {
17357            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17358        } else {
17359            if (DEBUG_DOMAIN_VERIFICATION) {
17360                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17361            }
17362        }
17363
17364        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17365                "installPackageLI")) {
17366            if (replace) {
17367                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17368                    // Static libs have a synthetic package name containing the version
17369                    // and cannot be updated as an update would get a new package name,
17370                    // unless this is the exact same version code which is useful for
17371                    // development.
17372                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17373                    if (existingPkg != null &&
17374                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17375                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17376                                + "static-shared libs cannot be updated");
17377                        return;
17378                    }
17379                }
17380                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17381                        installerPackageName, res, args.installReason);
17382            } else {
17383                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17384                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17385            }
17386        }
17387
17388        // Prepare the application profiles for the new code paths.
17389        // This needs to be done before invoking dexopt so that any install-time profile
17390        // can be used for optimizations.
17391        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17392
17393        // Check whether we need to dexopt the app.
17394        //
17395        // NOTE: it is IMPORTANT to call dexopt:
17396        //   - after doRename which will sync the package data from PackageParser.Package and its
17397        //     corresponding ApplicationInfo.
17398        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17399        //     uid of the application (pkg.applicationInfo.uid).
17400        //     This update happens in place!
17401        //
17402        // We only need to dexopt if the package meets ALL of the following conditions:
17403        //   1) it is not forward locked.
17404        //   2) it is not on on an external ASEC container.
17405        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17406        //
17407        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17408        // complete, so we skip this step during installation. Instead, we'll take extra time
17409        // the first time the instant app starts. It's preferred to do it this way to provide
17410        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17411        // middle of running an instant app. The default behaviour can be overridden
17412        // via gservices.
17413        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17414                && !forwardLocked
17415                && !pkg.applicationInfo.isExternalAsec()
17416                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17417                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17418
17419        if (performDexopt) {
17420            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17421            // Do not run PackageDexOptimizer through the local performDexOpt
17422            // method because `pkg` may not be in `mPackages` yet.
17423            //
17424            // Also, don't fail application installs if the dexopt step fails.
17425            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17426                    REASON_INSTALL,
17427                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17428                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17429            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17430                    null /* instructionSets */,
17431                    getOrCreateCompilerPackageStats(pkg),
17432                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17433                    dexoptOptions);
17434            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17435        }
17436
17437        // Notify BackgroundDexOptService that the package has been changed.
17438        // If this is an update of a package which used to fail to compile,
17439        // BackgroundDexOptService will remove it from its blacklist.
17440        // TODO: Layering violation
17441        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17442
17443        synchronized (mPackages) {
17444            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17445            if (ps != null) {
17446                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17447                ps.setUpdateAvailable(false /*updateAvailable*/);
17448            }
17449
17450            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17451            for (int i = 0; i < childCount; i++) {
17452                PackageParser.Package childPkg = pkg.childPackages.get(i);
17453                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17454                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17455                if (childPs != null) {
17456                    childRes.newUsers = childPs.queryInstalledUsers(
17457                            sUserManager.getUserIds(), true);
17458                }
17459            }
17460
17461            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17462                updateSequenceNumberLP(ps, res.newUsers);
17463                updateInstantAppInstallerLocked(pkgName);
17464            }
17465        }
17466    }
17467
17468    private void startIntentFilterVerifications(int userId, boolean replacing,
17469            PackageParser.Package pkg) {
17470        if (mIntentFilterVerifierComponent == null) {
17471            Slog.w(TAG, "No IntentFilter verification will not be done as "
17472                    + "there is no IntentFilterVerifier available!");
17473            return;
17474        }
17475
17476        final int verifierUid = getPackageUid(
17477                mIntentFilterVerifierComponent.getPackageName(),
17478                MATCH_DEBUG_TRIAGED_MISSING,
17479                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17480
17481        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17482        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17483        mHandler.sendMessage(msg);
17484
17485        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17486        for (int i = 0; i < childCount; i++) {
17487            PackageParser.Package childPkg = pkg.childPackages.get(i);
17488            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17489            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17490            mHandler.sendMessage(msg);
17491        }
17492    }
17493
17494    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17495            PackageParser.Package pkg) {
17496        int size = pkg.activities.size();
17497        if (size == 0) {
17498            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17499                    "No activity, so no need to verify any IntentFilter!");
17500            return;
17501        }
17502
17503        final boolean hasDomainURLs = hasDomainURLs(pkg);
17504        if (!hasDomainURLs) {
17505            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17506                    "No domain URLs, so no need to verify any IntentFilter!");
17507            return;
17508        }
17509
17510        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17511                + " if any IntentFilter from the " + size
17512                + " Activities needs verification ...");
17513
17514        int count = 0;
17515        final String packageName = pkg.packageName;
17516
17517        synchronized (mPackages) {
17518            // If this is a new install and we see that we've already run verification for this
17519            // package, we have nothing to do: it means the state was restored from backup.
17520            if (!replacing) {
17521                IntentFilterVerificationInfo ivi =
17522                        mSettings.getIntentFilterVerificationLPr(packageName);
17523                if (ivi != null) {
17524                    if (DEBUG_DOMAIN_VERIFICATION) {
17525                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17526                                + ivi.getStatusString());
17527                    }
17528                    return;
17529                }
17530            }
17531
17532            // If any filters need to be verified, then all need to be.
17533            boolean needToVerify = false;
17534            for (PackageParser.Activity a : pkg.activities) {
17535                for (ActivityIntentInfo filter : a.intents) {
17536                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17537                        if (DEBUG_DOMAIN_VERIFICATION) {
17538                            Slog.d(TAG,
17539                                    "Intent filter needs verification, so processing all filters");
17540                        }
17541                        needToVerify = true;
17542                        break;
17543                    }
17544                }
17545            }
17546
17547            if (needToVerify) {
17548                final int verificationId = mIntentFilterVerificationToken++;
17549                for (PackageParser.Activity a : pkg.activities) {
17550                    for (ActivityIntentInfo filter : a.intents) {
17551                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17552                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17553                                    "Verification needed for IntentFilter:" + filter.toString());
17554                            mIntentFilterVerifier.addOneIntentFilterVerification(
17555                                    verifierUid, userId, verificationId, filter, packageName);
17556                            count++;
17557                        }
17558                    }
17559                }
17560            }
17561        }
17562
17563        if (count > 0) {
17564            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17565                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17566                    +  " for userId:" + userId);
17567            mIntentFilterVerifier.startVerifications(userId);
17568        } else {
17569            if (DEBUG_DOMAIN_VERIFICATION) {
17570                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17571            }
17572        }
17573    }
17574
17575    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17576        final ComponentName cn  = filter.activity.getComponentName();
17577        final String packageName = cn.getPackageName();
17578
17579        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17580                packageName);
17581        if (ivi == null) {
17582            return true;
17583        }
17584        int status = ivi.getStatus();
17585        switch (status) {
17586            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17587            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17588                return true;
17589
17590            default:
17591                // Nothing to do
17592                return false;
17593        }
17594    }
17595
17596    private static boolean isMultiArch(ApplicationInfo info) {
17597        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17598    }
17599
17600    private static boolean isExternal(PackageParser.Package pkg) {
17601        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17602    }
17603
17604    private static boolean isExternal(PackageSetting ps) {
17605        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17606    }
17607
17608    private static boolean isSystemApp(PackageParser.Package pkg) {
17609        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17610    }
17611
17612    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17613        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17614    }
17615
17616    private static boolean isOemApp(PackageParser.Package pkg) {
17617        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17618    }
17619
17620    private static boolean isVendorApp(PackageParser.Package pkg) {
17621        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17622    }
17623
17624    private static boolean isProductApp(PackageParser.Package pkg) {
17625        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17626    }
17627
17628    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17629        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17630    }
17631
17632    private static boolean isSystemApp(PackageSetting ps) {
17633        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17634    }
17635
17636    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17637        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17638    }
17639
17640    private int packageFlagsToInstallFlags(PackageSetting ps) {
17641        int installFlags = 0;
17642        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17643            // This existing package was an external ASEC install when we have
17644            // the external flag without a UUID
17645            installFlags |= PackageManager.INSTALL_EXTERNAL;
17646        }
17647        if (ps.isForwardLocked()) {
17648            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17649        }
17650        return installFlags;
17651    }
17652
17653    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17654        if (isExternal(pkg)) {
17655            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17656                return mSettings.getExternalVersion();
17657            } else {
17658                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17659            }
17660        } else {
17661            return mSettings.getInternalVersion();
17662        }
17663    }
17664
17665    private void deleteTempPackageFiles() {
17666        final FilenameFilter filter = new FilenameFilter() {
17667            public boolean accept(File dir, String name) {
17668                return name.startsWith("vmdl") && name.endsWith(".tmp");
17669            }
17670        };
17671        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17672            file.delete();
17673        }
17674    }
17675
17676    @Override
17677    public void deletePackageAsUser(String packageName, int versionCode,
17678            IPackageDeleteObserver observer, int userId, int flags) {
17679        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17680                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17681    }
17682
17683    @Override
17684    public void deletePackageVersioned(VersionedPackage versionedPackage,
17685            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17686        final int callingUid = Binder.getCallingUid();
17687        mContext.enforceCallingOrSelfPermission(
17688                android.Manifest.permission.DELETE_PACKAGES, null);
17689        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17690        Preconditions.checkNotNull(versionedPackage);
17691        Preconditions.checkNotNull(observer);
17692        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17693                PackageManager.VERSION_CODE_HIGHEST,
17694                Long.MAX_VALUE, "versionCode must be >= -1");
17695
17696        final String packageName = versionedPackage.getPackageName();
17697        final long versionCode = versionedPackage.getLongVersionCode();
17698        final String internalPackageName;
17699        synchronized (mPackages) {
17700            // Normalize package name to handle renamed packages and static libs
17701            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17702        }
17703
17704        final int uid = Binder.getCallingUid();
17705        if (!isOrphaned(internalPackageName)
17706                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17707            try {
17708                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17709                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17710                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17711                observer.onUserActionRequired(intent);
17712            } catch (RemoteException re) {
17713            }
17714            return;
17715        }
17716        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17717        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17718        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17719            mContext.enforceCallingOrSelfPermission(
17720                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17721                    "deletePackage for user " + userId);
17722        }
17723
17724        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17725            try {
17726                observer.onPackageDeleted(packageName,
17727                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17728            } catch (RemoteException re) {
17729            }
17730            return;
17731        }
17732
17733        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17734            try {
17735                observer.onPackageDeleted(packageName,
17736                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17737            } catch (RemoteException re) {
17738            }
17739            return;
17740        }
17741
17742        if (DEBUG_REMOVE) {
17743            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17744                    + " deleteAllUsers: " + deleteAllUsers + " version="
17745                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17746                    ? "VERSION_CODE_HIGHEST" : versionCode));
17747        }
17748        // Queue up an async operation since the package deletion may take a little while.
17749        mHandler.post(new Runnable() {
17750            public void run() {
17751                mHandler.removeCallbacks(this);
17752                int returnCode;
17753                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17754                boolean doDeletePackage = true;
17755                if (ps != null) {
17756                    final boolean targetIsInstantApp =
17757                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17758                    doDeletePackage = !targetIsInstantApp
17759                            || canViewInstantApps;
17760                }
17761                if (doDeletePackage) {
17762                    if (!deleteAllUsers) {
17763                        returnCode = deletePackageX(internalPackageName, versionCode,
17764                                userId, deleteFlags);
17765                    } else {
17766                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17767                                internalPackageName, users);
17768                        // If nobody is blocking uninstall, proceed with delete for all users
17769                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17770                            returnCode = deletePackageX(internalPackageName, versionCode,
17771                                    userId, deleteFlags);
17772                        } else {
17773                            // Otherwise uninstall individually for users with blockUninstalls=false
17774                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17775                            for (int userId : users) {
17776                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17777                                    returnCode = deletePackageX(internalPackageName, versionCode,
17778                                            userId, userFlags);
17779                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17780                                        Slog.w(TAG, "Package delete failed for user " + userId
17781                                                + ", returnCode " + returnCode);
17782                                    }
17783                                }
17784                            }
17785                            // The app has only been marked uninstalled for certain users.
17786                            // We still need to report that delete was blocked
17787                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17788                        }
17789                    }
17790                } else {
17791                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17792                }
17793                try {
17794                    observer.onPackageDeleted(packageName, returnCode, null);
17795                } catch (RemoteException e) {
17796                    Log.i(TAG, "Observer no longer exists.");
17797                } //end catch
17798            } //end run
17799        });
17800    }
17801
17802    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17803        if (pkg.staticSharedLibName != null) {
17804            return pkg.manifestPackageName;
17805        }
17806        return pkg.packageName;
17807    }
17808
17809    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17810        // Handle renamed packages
17811        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17812        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17813
17814        // Is this a static library?
17815        LongSparseArray<SharedLibraryEntry> versionedLib =
17816                mStaticLibsByDeclaringPackage.get(packageName);
17817        if (versionedLib == null || versionedLib.size() <= 0) {
17818            return packageName;
17819        }
17820
17821        // Figure out which lib versions the caller can see
17822        LongSparseLongArray versionsCallerCanSee = null;
17823        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17824        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17825                && callingAppId != Process.ROOT_UID) {
17826            versionsCallerCanSee = new LongSparseLongArray();
17827            String libName = versionedLib.valueAt(0).info.getName();
17828            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17829            if (uidPackages != null) {
17830                for (String uidPackage : uidPackages) {
17831                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17832                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17833                    if (libIdx >= 0) {
17834                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17835                        versionsCallerCanSee.append(libVersion, libVersion);
17836                    }
17837                }
17838            }
17839        }
17840
17841        // Caller can see nothing - done
17842        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17843            return packageName;
17844        }
17845
17846        // Find the version the caller can see and the app version code
17847        SharedLibraryEntry highestVersion = null;
17848        final int versionCount = versionedLib.size();
17849        for (int i = 0; i < versionCount; i++) {
17850            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17851            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17852                    libEntry.info.getLongVersion()) < 0) {
17853                continue;
17854            }
17855            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17856            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17857                if (libVersionCode == versionCode) {
17858                    return libEntry.apk;
17859                }
17860            } else if (highestVersion == null) {
17861                highestVersion = libEntry;
17862            } else if (libVersionCode  > highestVersion.info
17863                    .getDeclaringPackage().getLongVersionCode()) {
17864                highestVersion = libEntry;
17865            }
17866        }
17867
17868        if (highestVersion != null) {
17869            return highestVersion.apk;
17870        }
17871
17872        return packageName;
17873    }
17874
17875    boolean isCallerVerifier(int callingUid) {
17876        final int callingUserId = UserHandle.getUserId(callingUid);
17877        return mRequiredVerifierPackage != null &&
17878                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17879    }
17880
17881    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17882        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17883              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17884            return true;
17885        }
17886        final int callingUserId = UserHandle.getUserId(callingUid);
17887        // If the caller installed the pkgName, then allow it to silently uninstall.
17888        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17889            return true;
17890        }
17891
17892        // Allow package verifier to silently uninstall.
17893        if (mRequiredVerifierPackage != null &&
17894                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17895            return true;
17896        }
17897
17898        // Allow package uninstaller to silently uninstall.
17899        if (mRequiredUninstallerPackage != null &&
17900                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17901            return true;
17902        }
17903
17904        // Allow storage manager to silently uninstall.
17905        if (mStorageManagerPackage != null &&
17906                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17907            return true;
17908        }
17909
17910        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17911        // uninstall for device owner provisioning.
17912        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17913                == PERMISSION_GRANTED) {
17914            return true;
17915        }
17916
17917        return false;
17918    }
17919
17920    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17921        int[] result = EMPTY_INT_ARRAY;
17922        for (int userId : userIds) {
17923            if (getBlockUninstallForUser(packageName, userId)) {
17924                result = ArrayUtils.appendInt(result, userId);
17925            }
17926        }
17927        return result;
17928    }
17929
17930    @Override
17931    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17932        final int callingUid = Binder.getCallingUid();
17933        if (getInstantAppPackageName(callingUid) != null
17934                && !isCallerSameApp(packageName, callingUid)) {
17935            return false;
17936        }
17937        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17938    }
17939
17940    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17941        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17942                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17943        try {
17944            if (dpm != null) {
17945                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17946                        /* callingUserOnly =*/ false);
17947                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17948                        : deviceOwnerComponentName.getPackageName();
17949                // Does the package contains the device owner?
17950                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17951                // this check is probably not needed, since DO should be registered as a device
17952                // admin on some user too. (Original bug for this: b/17657954)
17953                if (packageName.equals(deviceOwnerPackageName)) {
17954                    return true;
17955                }
17956                // Does it contain a device admin for any user?
17957                int[] users;
17958                if (userId == UserHandle.USER_ALL) {
17959                    users = sUserManager.getUserIds();
17960                } else {
17961                    users = new int[]{userId};
17962                }
17963                for (int i = 0; i < users.length; ++i) {
17964                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17965                        return true;
17966                    }
17967                }
17968            }
17969        } catch (RemoteException e) {
17970        }
17971        return false;
17972    }
17973
17974    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17975        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17976    }
17977
17978    /**
17979     *  This method is an internal method that could be get invoked either
17980     *  to delete an installed package or to clean up a failed installation.
17981     *  After deleting an installed package, a broadcast is sent to notify any
17982     *  listeners that the package has been removed. For cleaning up a failed
17983     *  installation, the broadcast is not necessary since the package's
17984     *  installation wouldn't have sent the initial broadcast either
17985     *  The key steps in deleting a package are
17986     *  deleting the package information in internal structures like mPackages,
17987     *  deleting the packages base directories through installd
17988     *  updating mSettings to reflect current status
17989     *  persisting settings for later use
17990     *  sending a broadcast if necessary
17991     */
17992    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17993        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17994        final boolean res;
17995
17996        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17997                ? UserHandle.USER_ALL : userId;
17998
17999        if (isPackageDeviceAdmin(packageName, removeUser)) {
18000            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18001            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18002        }
18003
18004        PackageSetting uninstalledPs = null;
18005        PackageParser.Package pkg = null;
18006
18007        // for the uninstall-updates case and restricted profiles, remember the per-
18008        // user handle installed state
18009        int[] allUsers;
18010        synchronized (mPackages) {
18011            uninstalledPs = mSettings.mPackages.get(packageName);
18012            if (uninstalledPs == null) {
18013                Slog.w(TAG, "Not removing non-existent package " + packageName);
18014                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18015            }
18016
18017            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18018                    && uninstalledPs.versionCode != versionCode) {
18019                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18020                        + uninstalledPs.versionCode + " != " + versionCode);
18021                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18022            }
18023
18024            // Static shared libs can be declared by any package, so let us not
18025            // allow removing a package if it provides a lib others depend on.
18026            pkg = mPackages.get(packageName);
18027
18028            allUsers = sUserManager.getUserIds();
18029
18030            if (pkg != null && pkg.staticSharedLibName != null) {
18031                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18032                        pkg.staticSharedLibVersion);
18033                if (libEntry != null) {
18034                    for (int currUserId : allUsers) {
18035                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18036                            continue;
18037                        }
18038                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18039                                libEntry.info, 0, currUserId);
18040                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18041                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18042                                    + " hosting lib " + libEntry.info.getName() + " version "
18043                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
18044                                    + " for user " + currUserId);
18045                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18046                        }
18047                    }
18048                }
18049            }
18050
18051            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18052        }
18053
18054        final int freezeUser;
18055        if (isUpdatedSystemApp(uninstalledPs)
18056                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18057            // We're downgrading a system app, which will apply to all users, so
18058            // freeze them all during the downgrade
18059            freezeUser = UserHandle.USER_ALL;
18060        } else {
18061            freezeUser = removeUser;
18062        }
18063
18064        synchronized (mInstallLock) {
18065            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18066            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18067                    deleteFlags, "deletePackageX")) {
18068                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18069                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
18070            }
18071            synchronized (mPackages) {
18072                if (res) {
18073                    if (pkg != null) {
18074                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18075                    }
18076                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18077                    updateInstantAppInstallerLocked(packageName);
18078                }
18079            }
18080        }
18081
18082        if (res) {
18083            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18084            info.sendPackageRemovedBroadcasts(killApp);
18085            info.sendSystemPackageUpdatedBroadcasts();
18086            info.sendSystemPackageAppearedBroadcasts();
18087        }
18088        // Force a gc here.
18089        Runtime.getRuntime().gc();
18090        // Delete the resources here after sending the broadcast to let
18091        // other processes clean up before deleting resources.
18092        if (info.args != null) {
18093            synchronized (mInstallLock) {
18094                info.args.doPostDeleteLI(true);
18095            }
18096        }
18097
18098        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18099    }
18100
18101    static class PackageRemovedInfo {
18102        final PackageSender packageSender;
18103        String removedPackage;
18104        String installerPackageName;
18105        int uid = -1;
18106        int removedAppId = -1;
18107        int[] origUsers;
18108        int[] removedUsers = null;
18109        int[] broadcastUsers = null;
18110        int[] instantUserIds = null;
18111        SparseArray<Integer> installReasons;
18112        boolean isRemovedPackageSystemUpdate = false;
18113        boolean isUpdate;
18114        boolean dataRemoved;
18115        boolean removedForAllUsers;
18116        boolean isStaticSharedLib;
18117        // Clean up resources deleted packages.
18118        InstallArgs args = null;
18119        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18120        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18121
18122        PackageRemovedInfo(PackageSender packageSender) {
18123            this.packageSender = packageSender;
18124        }
18125
18126        void sendPackageRemovedBroadcasts(boolean killApp) {
18127            sendPackageRemovedBroadcastInternal(killApp);
18128            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18129            for (int i = 0; i < childCount; i++) {
18130                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18131                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18132            }
18133        }
18134
18135        void sendSystemPackageUpdatedBroadcasts() {
18136            if (isRemovedPackageSystemUpdate) {
18137                sendSystemPackageUpdatedBroadcastsInternal();
18138                final int childCount = (removedChildPackages != null)
18139                        ? removedChildPackages.size() : 0;
18140                for (int i = 0; i < childCount; i++) {
18141                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18142                    if (childInfo.isRemovedPackageSystemUpdate) {
18143                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18144                    }
18145                }
18146            }
18147        }
18148
18149        void sendSystemPackageAppearedBroadcasts() {
18150            final int packageCount = (appearedChildPackages != null)
18151                    ? appearedChildPackages.size() : 0;
18152            for (int i = 0; i < packageCount; i++) {
18153                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18154                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18155                    true /*sendBootCompleted*/, false /*startReceiver*/,
18156                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
18157            }
18158        }
18159
18160        private void sendSystemPackageUpdatedBroadcastsInternal() {
18161            Bundle extras = new Bundle(2);
18162            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18163            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18164            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18165                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18166            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18167                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18168            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18169                null, null, 0, removedPackage, null, null, null);
18170            if (installerPackageName != null) {
18171                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18172                        removedPackage, extras, 0 /*flags*/,
18173                        installerPackageName, null, null, null);
18174                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18175                        removedPackage, extras, 0 /*flags*/,
18176                        installerPackageName, null, null, null);
18177            }
18178        }
18179
18180        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18181            // Don't send static shared library removal broadcasts as these
18182            // libs are visible only the the apps that depend on them an one
18183            // cannot remove the library if it has a dependency.
18184            if (isStaticSharedLib) {
18185                return;
18186            }
18187            Bundle extras = new Bundle(2);
18188            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18189            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18190            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18191            if (isUpdate || isRemovedPackageSystemUpdate) {
18192                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18193            }
18194            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18195            if (removedPackage != null) {
18196                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18197                    removedPackage, extras, 0, null /*targetPackage*/, null,
18198                    broadcastUsers, instantUserIds);
18199                if (installerPackageName != null) {
18200                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18201                            removedPackage, extras, 0 /*flags*/,
18202                            installerPackageName, null, broadcastUsers, instantUserIds);
18203                }
18204                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18205                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18206                        removedPackage, extras,
18207                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18208                        null, null, broadcastUsers, instantUserIds);
18209                    packageSender.notifyPackageRemoved(removedPackage);
18210                }
18211            }
18212            if (removedAppId >= 0) {
18213                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18214                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18215                    null, null, broadcastUsers, instantUserIds);
18216            }
18217        }
18218
18219        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18220            removedUsers = userIds;
18221            if (removedUsers == null) {
18222                broadcastUsers = null;
18223                return;
18224            }
18225
18226            broadcastUsers = EMPTY_INT_ARRAY;
18227            instantUserIds = EMPTY_INT_ARRAY;
18228            for (int i = userIds.length - 1; i >= 0; --i) {
18229                final int userId = userIds[i];
18230                if (deletedPackageSetting.getInstantApp(userId)) {
18231                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18232                } else {
18233                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18234                }
18235            }
18236        }
18237    }
18238
18239    /*
18240     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18241     * flag is not set, the data directory is removed as well.
18242     * make sure this flag is set for partially installed apps. If not its meaningless to
18243     * delete a partially installed application.
18244     */
18245    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18246            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18247        String packageName = ps.name;
18248        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18249        // Retrieve object to delete permissions for shared user later on
18250        final PackageParser.Package deletedPkg;
18251        final PackageSetting deletedPs;
18252        // reader
18253        synchronized (mPackages) {
18254            deletedPkg = mPackages.get(packageName);
18255            deletedPs = mSettings.mPackages.get(packageName);
18256            if (outInfo != null) {
18257                outInfo.removedPackage = packageName;
18258                outInfo.installerPackageName = ps.installerPackageName;
18259                outInfo.isStaticSharedLib = deletedPkg != null
18260                        && deletedPkg.staticSharedLibName != null;
18261                outInfo.populateUsers(deletedPs == null ? null
18262                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18263            }
18264        }
18265
18266        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18267
18268        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18269            final PackageParser.Package resolvedPkg;
18270            if (deletedPkg != null) {
18271                resolvedPkg = deletedPkg;
18272            } else {
18273                // We don't have a parsed package when it lives on an ejected
18274                // adopted storage device, so fake something together
18275                resolvedPkg = new PackageParser.Package(ps.name);
18276                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18277            }
18278            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18279                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18280            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18281            if (outInfo != null) {
18282                outInfo.dataRemoved = true;
18283            }
18284            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18285        }
18286
18287        int removedAppId = -1;
18288
18289        // writer
18290        synchronized (mPackages) {
18291            boolean installedStateChanged = false;
18292            if (deletedPs != null) {
18293                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18294                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18295                    clearDefaultBrowserIfNeeded(packageName);
18296                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18297                    removedAppId = mSettings.removePackageLPw(packageName);
18298                    if (outInfo != null) {
18299                        outInfo.removedAppId = removedAppId;
18300                    }
18301                    mPermissionManager.updatePermissions(
18302                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18303                    if (deletedPs.sharedUser != null) {
18304                        // Remove permissions associated with package. Since runtime
18305                        // permissions are per user we have to kill the removed package
18306                        // or packages running under the shared user of the removed
18307                        // package if revoking the permissions requested only by the removed
18308                        // package is successful and this causes a change in gids.
18309                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18310                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18311                                    userId);
18312                            if (userIdToKill == UserHandle.USER_ALL
18313                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18314                                // If gids changed for this user, kill all affected packages.
18315                                mHandler.post(new Runnable() {
18316                                    @Override
18317                                    public void run() {
18318                                        // This has to happen with no lock held.
18319                                        killApplication(deletedPs.name, deletedPs.appId,
18320                                                KILL_APP_REASON_GIDS_CHANGED);
18321                                    }
18322                                });
18323                                break;
18324                            }
18325                        }
18326                    }
18327                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18328                }
18329                // make sure to preserve per-user disabled state if this removal was just
18330                // a downgrade of a system app to the factory package
18331                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18332                    if (DEBUG_REMOVE) {
18333                        Slog.d(TAG, "Propagating install state across downgrade");
18334                    }
18335                    for (int userId : allUserHandles) {
18336                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18337                        if (DEBUG_REMOVE) {
18338                            Slog.d(TAG, "    user " + userId + " => " + installed);
18339                        }
18340                        if (installed != ps.getInstalled(userId)) {
18341                            installedStateChanged = true;
18342                        }
18343                        ps.setInstalled(installed, userId);
18344                    }
18345                }
18346            }
18347            // can downgrade to reader
18348            if (writeSettings) {
18349                // Save settings now
18350                mSettings.writeLPr();
18351            }
18352            if (installedStateChanged) {
18353                mSettings.writeKernelMappingLPr(ps);
18354            }
18355        }
18356        if (removedAppId != -1) {
18357            // A user ID was deleted here. Go through all users and remove it
18358            // from KeyStore.
18359            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18360        }
18361    }
18362
18363    static boolean locationIsPrivileged(String path) {
18364        try {
18365            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18366            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18367            final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app");
18368            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18369            return path.startsWith(privilegedAppDir.getCanonicalPath())
18370                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18371                    || path.startsWith(privilegedOdmAppDir.getCanonicalPath())
18372                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18373        } catch (IOException e) {
18374            Slog.e(TAG, "Unable to access code path " + path);
18375        }
18376        return false;
18377    }
18378
18379    static boolean locationIsOem(String path) {
18380        try {
18381            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18382        } catch (IOException e) {
18383            Slog.e(TAG, "Unable to access code path " + path);
18384        }
18385        return false;
18386    }
18387
18388    static boolean locationIsVendor(String path) {
18389        try {
18390            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath())
18391                    || path.startsWith(Environment.getOdmDirectory().getCanonicalPath());
18392        } catch (IOException e) {
18393            Slog.e(TAG, "Unable to access code path " + path);
18394        }
18395        return false;
18396    }
18397
18398    static boolean locationIsProduct(String path) {
18399        try {
18400            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18401        } catch (IOException e) {
18402            Slog.e(TAG, "Unable to access code path " + path);
18403        }
18404        return false;
18405    }
18406
18407    /*
18408     * Tries to delete system package.
18409     */
18410    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18411            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18412            boolean writeSettings) {
18413        if (deletedPs.parentPackageName != null) {
18414            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18415            return false;
18416        }
18417
18418        final boolean applyUserRestrictions
18419                = (allUserHandles != null) && (outInfo.origUsers != null);
18420        final PackageSetting disabledPs;
18421        // Confirm if the system package has been updated
18422        // An updated system app can be deleted. This will also have to restore
18423        // the system pkg from system partition
18424        // reader
18425        synchronized (mPackages) {
18426            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18427        }
18428
18429        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18430                + " disabledPs=" + disabledPs);
18431
18432        if (disabledPs == null) {
18433            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18434            return false;
18435        } else if (DEBUG_REMOVE) {
18436            Slog.d(TAG, "Deleting system pkg from data partition");
18437        }
18438
18439        if (DEBUG_REMOVE) {
18440            if (applyUserRestrictions) {
18441                Slog.d(TAG, "Remembering install states:");
18442                for (int userId : allUserHandles) {
18443                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18444                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18445                }
18446            }
18447        }
18448
18449        // Delete the updated package
18450        outInfo.isRemovedPackageSystemUpdate = true;
18451        if (outInfo.removedChildPackages != null) {
18452            final int childCount = (deletedPs.childPackageNames != null)
18453                    ? deletedPs.childPackageNames.size() : 0;
18454            for (int i = 0; i < childCount; i++) {
18455                String childPackageName = deletedPs.childPackageNames.get(i);
18456                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18457                        .contains(childPackageName)) {
18458                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18459                            childPackageName);
18460                    if (childInfo != null) {
18461                        childInfo.isRemovedPackageSystemUpdate = true;
18462                    }
18463                }
18464            }
18465        }
18466
18467        if (disabledPs.versionCode < deletedPs.versionCode) {
18468            // Delete data for downgrades
18469            flags &= ~PackageManager.DELETE_KEEP_DATA;
18470        } else {
18471            // Preserve data by setting flag
18472            flags |= PackageManager.DELETE_KEEP_DATA;
18473        }
18474
18475        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18476                outInfo, writeSettings, disabledPs.pkg);
18477        if (!ret) {
18478            return false;
18479        }
18480
18481        // writer
18482        synchronized (mPackages) {
18483            // NOTE: The system package always needs to be enabled; even if it's for
18484            // a compressed stub. If we don't, installing the system package fails
18485            // during scan [scanning checks the disabled packages]. We will reverse
18486            // this later, after we've "installed" the stub.
18487            // Reinstate the old system package
18488            enableSystemPackageLPw(disabledPs.pkg);
18489            // Remove any native libraries from the upgraded package.
18490            removeNativeBinariesLI(deletedPs);
18491        }
18492
18493        // Install the system package
18494        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18495        try {
18496            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18497                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18498        } catch (PackageManagerException e) {
18499            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18500                    + e.getMessage());
18501            return false;
18502        } finally {
18503            if (disabledPs.pkg.isStub) {
18504                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18505            }
18506        }
18507        return true;
18508    }
18509
18510    /**
18511     * Installs a package that's already on the system partition.
18512     */
18513    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18514            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18515            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18516                    throws PackageManagerException {
18517        @ParseFlags int parseFlags =
18518                mDefParseFlags
18519                | PackageParser.PARSE_MUST_BE_APK
18520                | PackageParser.PARSE_IS_SYSTEM_DIR;
18521        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18522        if (isPrivileged || locationIsPrivileged(codePathString)) {
18523            scanFlags |= SCAN_AS_PRIVILEGED;
18524        }
18525        if (locationIsOem(codePathString)) {
18526            scanFlags |= SCAN_AS_OEM;
18527        }
18528        if (locationIsVendor(codePathString)) {
18529            scanFlags |= SCAN_AS_VENDOR;
18530        }
18531        if (locationIsProduct(codePathString)) {
18532            scanFlags |= SCAN_AS_PRODUCT;
18533        }
18534
18535        final File codePath = new File(codePathString);
18536        final PackageParser.Package pkg =
18537                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18538
18539        try {
18540            // update shared libraries for the newly re-installed system package
18541            updateSharedLibrariesLPr(pkg, null);
18542        } catch (PackageManagerException e) {
18543            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18544        }
18545
18546        prepareAppDataAfterInstallLIF(pkg);
18547
18548        // writer
18549        synchronized (mPackages) {
18550            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18551
18552            // Propagate the permissions state as we do not want to drop on the floor
18553            // runtime permissions. The update permissions method below will take
18554            // care of removing obsolete permissions and grant install permissions.
18555            if (origPermissionState != null) {
18556                ps.getPermissionsState().copyFrom(origPermissionState);
18557            }
18558            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18559                    mPermissionCallback);
18560
18561            final boolean applyUserRestrictions
18562                    = (allUserHandles != null) && (origUserHandles != null);
18563            if (applyUserRestrictions) {
18564                boolean installedStateChanged = false;
18565                if (DEBUG_REMOVE) {
18566                    Slog.d(TAG, "Propagating install state across reinstall");
18567                }
18568                for (int userId : allUserHandles) {
18569                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18570                    if (DEBUG_REMOVE) {
18571                        Slog.d(TAG, "    user " + userId + " => " + installed);
18572                    }
18573                    if (installed != ps.getInstalled(userId)) {
18574                        installedStateChanged = true;
18575                    }
18576                    ps.setInstalled(installed, userId);
18577
18578                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18579                }
18580                // Regardless of writeSettings we need to ensure that this restriction
18581                // state propagation is persisted
18582                mSettings.writeAllUsersPackageRestrictionsLPr();
18583                if (installedStateChanged) {
18584                    mSettings.writeKernelMappingLPr(ps);
18585                }
18586            }
18587            // can downgrade to reader here
18588            if (writeSettings) {
18589                mSettings.writeLPr();
18590            }
18591        }
18592        return pkg;
18593    }
18594
18595    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18596            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18597            PackageRemovedInfo outInfo, boolean writeSettings,
18598            PackageParser.Package replacingPackage) {
18599        synchronized (mPackages) {
18600            if (outInfo != null) {
18601                outInfo.uid = ps.appId;
18602            }
18603
18604            if (outInfo != null && outInfo.removedChildPackages != null) {
18605                final int childCount = (ps.childPackageNames != null)
18606                        ? ps.childPackageNames.size() : 0;
18607                for (int i = 0; i < childCount; i++) {
18608                    String childPackageName = ps.childPackageNames.get(i);
18609                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18610                    if (childPs == null) {
18611                        return false;
18612                    }
18613                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18614                            childPackageName);
18615                    if (childInfo != null) {
18616                        childInfo.uid = childPs.appId;
18617                    }
18618                }
18619            }
18620        }
18621
18622        // Delete package data from internal structures and also remove data if flag is set
18623        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18624
18625        // Delete the child packages data
18626        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18627        for (int i = 0; i < childCount; i++) {
18628            PackageSetting childPs;
18629            synchronized (mPackages) {
18630                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18631            }
18632            if (childPs != null) {
18633                PackageRemovedInfo childOutInfo = (outInfo != null
18634                        && outInfo.removedChildPackages != null)
18635                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18636                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18637                        && (replacingPackage != null
18638                        && !replacingPackage.hasChildPackage(childPs.name))
18639                        ? flags & ~DELETE_KEEP_DATA : flags;
18640                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18641                        deleteFlags, writeSettings);
18642            }
18643        }
18644
18645        // Delete application code and resources only for parent packages
18646        if (ps.parentPackageName == null) {
18647            if (deleteCodeAndResources && (outInfo != null)) {
18648                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18649                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18650                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18651            }
18652        }
18653
18654        return true;
18655    }
18656
18657    @Override
18658    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18659            int userId) {
18660        mContext.enforceCallingOrSelfPermission(
18661                android.Manifest.permission.DELETE_PACKAGES, null);
18662        synchronized (mPackages) {
18663            // Cannot block uninstall of static shared libs as they are
18664            // considered a part of the using app (emulating static linking).
18665            // Also static libs are installed always on internal storage.
18666            PackageParser.Package pkg = mPackages.get(packageName);
18667            if (pkg != null && pkg.staticSharedLibName != null) {
18668                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18669                        + " providing static shared library: " + pkg.staticSharedLibName);
18670                return false;
18671            }
18672            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18673            mSettings.writePackageRestrictionsLPr(userId);
18674        }
18675        return true;
18676    }
18677
18678    @Override
18679    public boolean getBlockUninstallForUser(String packageName, int userId) {
18680        synchronized (mPackages) {
18681            final PackageSetting ps = mSettings.mPackages.get(packageName);
18682            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18683                return false;
18684            }
18685            return mSettings.getBlockUninstallLPr(userId, packageName);
18686        }
18687    }
18688
18689    @Override
18690    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18691        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18692        synchronized (mPackages) {
18693            PackageSetting ps = mSettings.mPackages.get(packageName);
18694            if (ps == null) {
18695                Log.w(TAG, "Package doesn't exist: " + packageName);
18696                return false;
18697            }
18698            if (systemUserApp) {
18699                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18700            } else {
18701                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18702            }
18703            mSettings.writeLPr();
18704        }
18705        return true;
18706    }
18707
18708    /*
18709     * This method handles package deletion in general
18710     */
18711    private boolean deletePackageLIF(String packageName, UserHandle user,
18712            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18713            PackageRemovedInfo outInfo, boolean writeSettings,
18714            PackageParser.Package replacingPackage) {
18715        if (packageName == null) {
18716            Slog.w(TAG, "Attempt to delete null packageName.");
18717            return false;
18718        }
18719
18720        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18721
18722        PackageSetting ps;
18723        synchronized (mPackages) {
18724            ps = mSettings.mPackages.get(packageName);
18725            if (ps == null) {
18726                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18727                return false;
18728            }
18729
18730            if (ps.parentPackageName != null && (!isSystemApp(ps)
18731                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18732                if (DEBUG_REMOVE) {
18733                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18734                            + ((user == null) ? UserHandle.USER_ALL : user));
18735                }
18736                final int removedUserId = (user != null) ? user.getIdentifier()
18737                        : UserHandle.USER_ALL;
18738
18739                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18740                    return false;
18741                }
18742                markPackageUninstalledForUserLPw(ps, user);
18743                scheduleWritePackageRestrictionsLocked(user);
18744                return true;
18745            }
18746        }
18747
18748        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
18749        if (ps.getPermissionsState().hasPermission(Manifest.permission.SUSPEND_APPS, userId)) {
18750            onSuspendingPackageRemoved(packageName, userId);
18751        }
18752
18753
18754        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18755                && user.getIdentifier() != UserHandle.USER_ALL)) {
18756            // The caller is asking that the package only be deleted for a single
18757            // user.  To do this, we just mark its uninstalled state and delete
18758            // its data. If this is a system app, we only allow this to happen if
18759            // they have set the special DELETE_SYSTEM_APP which requests different
18760            // semantics than normal for uninstalling system apps.
18761            markPackageUninstalledForUserLPw(ps, user);
18762
18763            if (!isSystemApp(ps)) {
18764                // Do not uninstall the APK if an app should be cached
18765                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18766                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18767                    // Other user still have this package installed, so all
18768                    // we need to do is clear this user's data and save that
18769                    // it is uninstalled.
18770                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18771                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18772                        return false;
18773                    }
18774                    scheduleWritePackageRestrictionsLocked(user);
18775                    return true;
18776                } else {
18777                    // We need to set it back to 'installed' so the uninstall
18778                    // broadcasts will be sent correctly.
18779                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18780                    ps.setInstalled(true, user.getIdentifier());
18781                    mSettings.writeKernelMappingLPr(ps);
18782                }
18783            } else {
18784                // This is a system app, so we assume that the
18785                // other users still have this package installed, so all
18786                // we need to do is clear this user's data and save that
18787                // it is uninstalled.
18788                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18789                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18790                    return false;
18791                }
18792                scheduleWritePackageRestrictionsLocked(user);
18793                return true;
18794            }
18795        }
18796
18797        // If we are deleting a composite package for all users, keep track
18798        // of result for each child.
18799        if (ps.childPackageNames != null && outInfo != null) {
18800            synchronized (mPackages) {
18801                final int childCount = ps.childPackageNames.size();
18802                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18803                for (int i = 0; i < childCount; i++) {
18804                    String childPackageName = ps.childPackageNames.get(i);
18805                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18806                    childInfo.removedPackage = childPackageName;
18807                    childInfo.installerPackageName = ps.installerPackageName;
18808                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18809                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18810                    if (childPs != null) {
18811                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18812                    }
18813                }
18814            }
18815        }
18816
18817        boolean ret = false;
18818        if (isSystemApp(ps)) {
18819            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18820            // When an updated system application is deleted we delete the existing resources
18821            // as well and fall back to existing code in system partition
18822            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18823        } else {
18824            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18825            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18826                    outInfo, writeSettings, replacingPackage);
18827        }
18828
18829        // Take a note whether we deleted the package for all users
18830        if (outInfo != null) {
18831            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18832            if (outInfo.removedChildPackages != null) {
18833                synchronized (mPackages) {
18834                    final int childCount = outInfo.removedChildPackages.size();
18835                    for (int i = 0; i < childCount; i++) {
18836                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18837                        if (childInfo != null) {
18838                            childInfo.removedForAllUsers = mPackages.get(
18839                                    childInfo.removedPackage) == null;
18840                        }
18841                    }
18842                }
18843            }
18844            // If we uninstalled an update to a system app there may be some
18845            // child packages that appeared as they are declared in the system
18846            // app but were not declared in the update.
18847            if (isSystemApp(ps)) {
18848                synchronized (mPackages) {
18849                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18850                    final int childCount = (updatedPs.childPackageNames != null)
18851                            ? updatedPs.childPackageNames.size() : 0;
18852                    for (int i = 0; i < childCount; i++) {
18853                        String childPackageName = updatedPs.childPackageNames.get(i);
18854                        if (outInfo.removedChildPackages == null
18855                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18856                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18857                            if (childPs == null) {
18858                                continue;
18859                            }
18860                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18861                            installRes.name = childPackageName;
18862                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18863                            installRes.pkg = mPackages.get(childPackageName);
18864                            installRes.uid = childPs.pkg.applicationInfo.uid;
18865                            if (outInfo.appearedChildPackages == null) {
18866                                outInfo.appearedChildPackages = new ArrayMap<>();
18867                            }
18868                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18869                        }
18870                    }
18871                }
18872            }
18873        }
18874
18875        return ret;
18876    }
18877
18878    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18879        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18880                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18881        for (int nextUserId : userIds) {
18882            if (DEBUG_REMOVE) {
18883                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18884            }
18885            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18886                    false /*installed*/,
18887                    true /*stopped*/,
18888                    true /*notLaunched*/,
18889                    false /*hidden*/,
18890                    false /*suspended*/,
18891                    null, /*suspendingPackage*/
18892                    null, /*suspendedAppExtras*/
18893                    null, /*suspendedLauncherExtras*/
18894                    false /*instantApp*/,
18895                    false /*virtualPreload*/,
18896                    null /*lastDisableAppCaller*/,
18897                    null /*enabledComponents*/,
18898                    null /*disabledComponents*/,
18899                    ps.readUserState(nextUserId).domainVerificationStatus,
18900                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18901                    null /*harmfulAppWarning*/);
18902        }
18903        mSettings.writeKernelMappingLPr(ps);
18904    }
18905
18906    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18907            PackageRemovedInfo outInfo) {
18908        final PackageParser.Package pkg;
18909        synchronized (mPackages) {
18910            pkg = mPackages.get(ps.name);
18911        }
18912
18913        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18914                : new int[] {userId};
18915        for (int nextUserId : userIds) {
18916            if (DEBUG_REMOVE) {
18917                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18918                        + nextUserId);
18919            }
18920
18921            destroyAppDataLIF(pkg, userId,
18922                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18923            destroyAppProfilesLIF(pkg, userId);
18924            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18925            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18926            schedulePackageCleaning(ps.name, nextUserId, false);
18927            synchronized (mPackages) {
18928                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18929                    scheduleWritePackageRestrictionsLocked(nextUserId);
18930                }
18931                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18932            }
18933        }
18934
18935        if (outInfo != null) {
18936            outInfo.removedPackage = ps.name;
18937            outInfo.installerPackageName = ps.installerPackageName;
18938            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18939            outInfo.removedAppId = ps.appId;
18940            outInfo.removedUsers = userIds;
18941            outInfo.broadcastUsers = userIds;
18942        }
18943
18944        return true;
18945    }
18946
18947    private final class ClearStorageConnection implements ServiceConnection {
18948        IMediaContainerService mContainerService;
18949
18950        @Override
18951        public void onServiceConnected(ComponentName name, IBinder service) {
18952            synchronized (this) {
18953                mContainerService = IMediaContainerService.Stub
18954                        .asInterface(Binder.allowBlocking(service));
18955                notifyAll();
18956            }
18957        }
18958
18959        @Override
18960        public void onServiceDisconnected(ComponentName name) {
18961        }
18962    }
18963
18964    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18965        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18966
18967        final boolean mounted;
18968        if (Environment.isExternalStorageEmulated()) {
18969            mounted = true;
18970        } else {
18971            final String status = Environment.getExternalStorageState();
18972
18973            mounted = status.equals(Environment.MEDIA_MOUNTED)
18974                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18975        }
18976
18977        if (!mounted) {
18978            return;
18979        }
18980
18981        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18982        int[] users;
18983        if (userId == UserHandle.USER_ALL) {
18984            users = sUserManager.getUserIds();
18985        } else {
18986            users = new int[] { userId };
18987        }
18988        final ClearStorageConnection conn = new ClearStorageConnection();
18989        if (mContext.bindServiceAsUser(
18990                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18991            try {
18992                for (int curUser : users) {
18993                    long timeout = SystemClock.uptimeMillis() + 5000;
18994                    synchronized (conn) {
18995                        long now;
18996                        while (conn.mContainerService == null &&
18997                                (now = SystemClock.uptimeMillis()) < timeout) {
18998                            try {
18999                                conn.wait(timeout - now);
19000                            } catch (InterruptedException e) {
19001                            }
19002                        }
19003                    }
19004                    if (conn.mContainerService == null) {
19005                        return;
19006                    }
19007
19008                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19009                    clearDirectory(conn.mContainerService,
19010                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19011                    if (allData) {
19012                        clearDirectory(conn.mContainerService,
19013                                userEnv.buildExternalStorageAppDataDirs(packageName));
19014                        clearDirectory(conn.mContainerService,
19015                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19016                    }
19017                }
19018            } finally {
19019                mContext.unbindService(conn);
19020            }
19021        }
19022    }
19023
19024    @Override
19025    public void clearApplicationProfileData(String packageName) {
19026        enforceSystemOrRoot("Only the system can clear all profile data");
19027
19028        final PackageParser.Package pkg;
19029        synchronized (mPackages) {
19030            pkg = mPackages.get(packageName);
19031        }
19032
19033        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19034            synchronized (mInstallLock) {
19035                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19036            }
19037        }
19038    }
19039
19040    @Override
19041    public void clearApplicationUserData(final String packageName,
19042            final IPackageDataObserver observer, final int userId) {
19043        mContext.enforceCallingOrSelfPermission(
19044                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19045
19046        final int callingUid = Binder.getCallingUid();
19047        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19048                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19049
19050        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19051        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
19052        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19053            throw new SecurityException("Cannot clear data for a protected package: "
19054                    + packageName);
19055        }
19056        // Queue up an async operation since the package deletion may take a little while.
19057        mHandler.post(new Runnable() {
19058            public void run() {
19059                mHandler.removeCallbacks(this);
19060                final boolean succeeded;
19061                if (!filterApp) {
19062                    try (PackageFreezer freezer = freezePackage(packageName,
19063                            "clearApplicationUserData")) {
19064                        synchronized (mInstallLock) {
19065                            succeeded = clearApplicationUserDataLIF(packageName, userId);
19066                        }
19067                        clearExternalStorageDataSync(packageName, userId, true);
19068                        synchronized (mPackages) {
19069                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19070                                    packageName, userId);
19071                        }
19072                    }
19073                    if (succeeded) {
19074                        // invoke DeviceStorageMonitor's update method to clear any notifications
19075                        DeviceStorageMonitorInternal dsm = LocalServices
19076                                .getService(DeviceStorageMonitorInternal.class);
19077                        if (dsm != null) {
19078                            dsm.checkMemory();
19079                        }
19080                    }
19081                } else {
19082                    succeeded = false;
19083                }
19084                if (observer != null) {
19085                    try {
19086                        observer.onRemoveCompleted(packageName, succeeded);
19087                    } catch (RemoteException e) {
19088                        Log.i(TAG, "Observer no longer exists.");
19089                    }
19090                } //end if observer
19091            } //end run
19092        });
19093    }
19094
19095    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19096        if (packageName == null) {
19097            Slog.w(TAG, "Attempt to delete null packageName.");
19098            return false;
19099        }
19100
19101        // Try finding details about the requested package
19102        PackageParser.Package pkg;
19103        synchronized (mPackages) {
19104            pkg = mPackages.get(packageName);
19105            if (pkg == null) {
19106                final PackageSetting ps = mSettings.mPackages.get(packageName);
19107                if (ps != null) {
19108                    pkg = ps.pkg;
19109                }
19110            }
19111
19112            if (pkg == null) {
19113                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19114                return false;
19115            }
19116
19117            PackageSetting ps = (PackageSetting) pkg.mExtras;
19118            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19119        }
19120
19121        clearAppDataLIF(pkg, userId,
19122                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19123
19124        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19125        removeKeystoreDataIfNeeded(userId, appId);
19126
19127        UserManagerInternal umInternal = getUserManagerInternal();
19128        final int flags;
19129        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19130            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19131        } else if (umInternal.isUserRunning(userId)) {
19132            flags = StorageManager.FLAG_STORAGE_DE;
19133        } else {
19134            flags = 0;
19135        }
19136        prepareAppDataContentsLIF(pkg, userId, flags);
19137
19138        return true;
19139    }
19140
19141    /**
19142     * Reverts user permission state changes (permissions and flags) in
19143     * all packages for a given user.
19144     *
19145     * @param userId The device user for which to do a reset.
19146     */
19147    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19148        final int packageCount = mPackages.size();
19149        for (int i = 0; i < packageCount; i++) {
19150            PackageParser.Package pkg = mPackages.valueAt(i);
19151            PackageSetting ps = (PackageSetting) pkg.mExtras;
19152            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19153        }
19154    }
19155
19156    private void resetNetworkPolicies(int userId) {
19157        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19158    }
19159
19160    /**
19161     * Reverts user permission state changes (permissions and flags).
19162     *
19163     * @param ps The package for which to reset.
19164     * @param userId The device user for which to do a reset.
19165     */
19166    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19167            final PackageSetting ps, final int userId) {
19168        if (ps.pkg == null) {
19169            return;
19170        }
19171
19172        // These are flags that can change base on user actions.
19173        final int userSettableMask = FLAG_PERMISSION_USER_SET
19174                | FLAG_PERMISSION_USER_FIXED
19175                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19176                | FLAG_PERMISSION_REVIEW_REQUIRED;
19177
19178        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19179                | FLAG_PERMISSION_POLICY_FIXED;
19180
19181        boolean writeInstallPermissions = false;
19182        boolean writeRuntimePermissions = false;
19183
19184        final int permissionCount = ps.pkg.requestedPermissions.size();
19185        for (int i = 0; i < permissionCount; i++) {
19186            final String permName = ps.pkg.requestedPermissions.get(i);
19187            final BasePermission bp =
19188                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19189            if (bp == null) {
19190                continue;
19191            }
19192
19193            // If shared user we just reset the state to which only this app contributed.
19194            if (ps.sharedUser != null) {
19195                boolean used = false;
19196                final int packageCount = ps.sharedUser.packages.size();
19197                for (int j = 0; j < packageCount; j++) {
19198                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19199                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19200                            && pkg.pkg.requestedPermissions.contains(permName)) {
19201                        used = true;
19202                        break;
19203                    }
19204                }
19205                if (used) {
19206                    continue;
19207                }
19208            }
19209
19210            final PermissionsState permissionsState = ps.getPermissionsState();
19211
19212            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19213
19214            // Always clear the user settable flags.
19215            final boolean hasInstallState =
19216                    permissionsState.getInstallPermissionState(permName) != null;
19217            // If permission review is enabled and this is a legacy app, mark the
19218            // permission as requiring a review as this is the initial state.
19219            int flags = 0;
19220            if (mSettings.mPermissions.mPermissionReviewRequired
19221                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19222                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19223            }
19224            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19225                if (hasInstallState) {
19226                    writeInstallPermissions = true;
19227                } else {
19228                    writeRuntimePermissions = true;
19229                }
19230            }
19231
19232            // Below is only runtime permission handling.
19233            if (!bp.isRuntime()) {
19234                continue;
19235            }
19236
19237            // Never clobber system or policy.
19238            if ((oldFlags & policyOrSystemFlags) != 0) {
19239                continue;
19240            }
19241
19242            // If this permission was granted by default, make sure it is.
19243            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19244                if (permissionsState.grantRuntimePermission(bp, userId)
19245                        != PERMISSION_OPERATION_FAILURE) {
19246                    writeRuntimePermissions = true;
19247                }
19248            // If permission review is enabled the permissions for a legacy apps
19249            // are represented as constantly granted runtime ones, so don't revoke.
19250            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19251                // Otherwise, reset the permission.
19252                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19253                switch (revokeResult) {
19254                    case PERMISSION_OPERATION_SUCCESS:
19255                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19256                        writeRuntimePermissions = true;
19257                        final int appId = ps.appId;
19258                        mHandler.post(new Runnable() {
19259                            @Override
19260                            public void run() {
19261                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19262                            }
19263                        });
19264                    } break;
19265                }
19266            }
19267        }
19268
19269        // Synchronously write as we are taking permissions away.
19270        if (writeRuntimePermissions) {
19271            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19272        }
19273
19274        // Synchronously write as we are taking permissions away.
19275        if (writeInstallPermissions) {
19276            mSettings.writeLPr();
19277        }
19278    }
19279
19280    /**
19281     * Remove entries from the keystore daemon. Will only remove it if the
19282     * {@code appId} is valid.
19283     */
19284    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19285        if (appId < 0) {
19286            return;
19287        }
19288
19289        final KeyStore keyStore = KeyStore.getInstance();
19290        if (keyStore != null) {
19291            if (userId == UserHandle.USER_ALL) {
19292                for (final int individual : sUserManager.getUserIds()) {
19293                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19294                }
19295            } else {
19296                keyStore.clearUid(UserHandle.getUid(userId, appId));
19297            }
19298        } else {
19299            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19300        }
19301    }
19302
19303    @Override
19304    public void deleteApplicationCacheFiles(final String packageName,
19305            final IPackageDataObserver observer) {
19306        final int userId = UserHandle.getCallingUserId();
19307        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19308    }
19309
19310    @Override
19311    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19312            final IPackageDataObserver observer) {
19313        final int callingUid = Binder.getCallingUid();
19314        if (mContext.checkCallingOrSelfPermission(
19315                android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
19316                != PackageManager.PERMISSION_GRANTED) {
19317            // If the caller has the old delete cache permission, silently ignore.  Else throw.
19318            if (mContext.checkCallingOrSelfPermission(
19319                    android.Manifest.permission.DELETE_CACHE_FILES)
19320                    == PackageManager.PERMISSION_GRANTED) {
19321                Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
19322                        android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
19323                        ", silently ignoring");
19324                return;
19325            }
19326            mContext.enforceCallingOrSelfPermission(
19327                    android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
19328        }
19329        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19330                /* requireFullPermission= */ true, /* checkShell= */ false,
19331                "delete application cache files");
19332        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19333                android.Manifest.permission.ACCESS_INSTANT_APPS);
19334
19335        final PackageParser.Package pkg;
19336        synchronized (mPackages) {
19337            pkg = mPackages.get(packageName);
19338        }
19339
19340        // Queue up an async operation since the package deletion may take a little while.
19341        mHandler.post(new Runnable() {
19342            public void run() {
19343                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19344                boolean doClearData = true;
19345                if (ps != null) {
19346                    final boolean targetIsInstantApp =
19347                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19348                    doClearData = !targetIsInstantApp
19349                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19350                }
19351                if (doClearData) {
19352                    synchronized (mInstallLock) {
19353                        final int flags = StorageManager.FLAG_STORAGE_DE
19354                                | StorageManager.FLAG_STORAGE_CE;
19355                        // We're only clearing cache files, so we don't care if the
19356                        // app is unfrozen and still able to run
19357                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19358                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19359                    }
19360                    clearExternalStorageDataSync(packageName, userId, false);
19361                }
19362                if (observer != null) {
19363                    try {
19364                        observer.onRemoveCompleted(packageName, true);
19365                    } catch (RemoteException e) {
19366                        Log.i(TAG, "Observer no longer exists.");
19367                    }
19368                }
19369            }
19370        });
19371    }
19372
19373    @Override
19374    public void getPackageSizeInfo(final String packageName, int userHandle,
19375            final IPackageStatsObserver observer) {
19376        throw new UnsupportedOperationException(
19377                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19378    }
19379
19380    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19381        final PackageSetting ps;
19382        synchronized (mPackages) {
19383            ps = mSettings.mPackages.get(packageName);
19384            if (ps == null) {
19385                Slog.w(TAG, "Failed to find settings for " + packageName);
19386                return false;
19387            }
19388        }
19389
19390        final String[] packageNames = { packageName };
19391        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19392        final String[] codePaths = { ps.codePathString };
19393
19394        try {
19395            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19396                    ps.appId, ceDataInodes, codePaths, stats);
19397
19398            // For now, ignore code size of packages on system partition
19399            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19400                stats.codeSize = 0;
19401            }
19402
19403            // External clients expect these to be tracked separately
19404            stats.dataSize -= stats.cacheSize;
19405
19406        } catch (InstallerException e) {
19407            Slog.w(TAG, String.valueOf(e));
19408            return false;
19409        }
19410
19411        return true;
19412    }
19413
19414    private int getUidTargetSdkVersionLockedLPr(int uid) {
19415        Object obj = mSettings.getUserIdLPr(uid);
19416        if (obj instanceof SharedUserSetting) {
19417            final SharedUserSetting sus = (SharedUserSetting) obj;
19418            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19419            final Iterator<PackageSetting> it = sus.packages.iterator();
19420            while (it.hasNext()) {
19421                final PackageSetting ps = it.next();
19422                if (ps.pkg != null) {
19423                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19424                    if (v < vers) vers = v;
19425                }
19426            }
19427            return vers;
19428        } else if (obj instanceof PackageSetting) {
19429            final PackageSetting ps = (PackageSetting) obj;
19430            if (ps.pkg != null) {
19431                return ps.pkg.applicationInfo.targetSdkVersion;
19432            }
19433        }
19434        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19435    }
19436
19437    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19438        final PackageParser.Package p = mPackages.get(packageName);
19439        if (p != null) {
19440            return p.applicationInfo.targetSdkVersion;
19441        }
19442        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19443    }
19444
19445    @Override
19446    public void addPreferredActivity(IntentFilter filter, int match,
19447            ComponentName[] set, ComponentName activity, int userId) {
19448        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19449                "Adding preferred");
19450    }
19451
19452    private void addPreferredActivityInternal(IntentFilter filter, int match,
19453            ComponentName[] set, ComponentName activity, boolean always, int userId,
19454            String opname) {
19455        // writer
19456        int callingUid = Binder.getCallingUid();
19457        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19458                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19459        if (filter.countActions() == 0) {
19460            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19461            return;
19462        }
19463        synchronized (mPackages) {
19464            if (mContext.checkCallingOrSelfPermission(
19465                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19466                    != PackageManager.PERMISSION_GRANTED) {
19467                if (getUidTargetSdkVersionLockedLPr(callingUid)
19468                        < Build.VERSION_CODES.FROYO) {
19469                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19470                            + callingUid);
19471                    return;
19472                }
19473                mContext.enforceCallingOrSelfPermission(
19474                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19475            }
19476
19477            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19478            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19479                    + userId + ":");
19480            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19481            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19482            scheduleWritePackageRestrictionsLocked(userId);
19483            postPreferredActivityChangedBroadcast(userId);
19484        }
19485    }
19486
19487    private void postPreferredActivityChangedBroadcast(int userId) {
19488        mHandler.post(() -> {
19489            final IActivityManager am = ActivityManager.getService();
19490            if (am == null) {
19491                return;
19492            }
19493
19494            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19495            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19496            try {
19497                am.broadcastIntent(null, intent, null, null,
19498                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19499                        null, false, false, userId);
19500            } catch (RemoteException e) {
19501            }
19502        });
19503    }
19504
19505    @Override
19506    public void replacePreferredActivity(IntentFilter filter, int match,
19507            ComponentName[] set, ComponentName activity, int userId) {
19508        if (filter.countActions() != 1) {
19509            throw new IllegalArgumentException(
19510                    "replacePreferredActivity expects filter to have only 1 action.");
19511        }
19512        if (filter.countDataAuthorities() != 0
19513                || filter.countDataPaths() != 0
19514                || filter.countDataSchemes() > 1
19515                || filter.countDataTypes() != 0) {
19516            throw new IllegalArgumentException(
19517                    "replacePreferredActivity expects filter to have no data authorities, " +
19518                    "paths, or types; and at most one scheme.");
19519        }
19520
19521        final int callingUid = Binder.getCallingUid();
19522        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19523                true /* requireFullPermission */, false /* checkShell */,
19524                "replace preferred activity");
19525        synchronized (mPackages) {
19526            if (mContext.checkCallingOrSelfPermission(
19527                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19528                    != PackageManager.PERMISSION_GRANTED) {
19529                if (getUidTargetSdkVersionLockedLPr(callingUid)
19530                        < Build.VERSION_CODES.FROYO) {
19531                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19532                            + Binder.getCallingUid());
19533                    return;
19534                }
19535                mContext.enforceCallingOrSelfPermission(
19536                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19537            }
19538
19539            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19540            if (pir != null) {
19541                // Get all of the existing entries that exactly match this filter.
19542                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19543                if (existing != null && existing.size() == 1) {
19544                    PreferredActivity cur = existing.get(0);
19545                    if (DEBUG_PREFERRED) {
19546                        Slog.i(TAG, "Checking replace of preferred:");
19547                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19548                        if (!cur.mPref.mAlways) {
19549                            Slog.i(TAG, "  -- CUR; not mAlways!");
19550                        } else {
19551                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19552                            Slog.i(TAG, "  -- CUR: mSet="
19553                                    + Arrays.toString(cur.mPref.mSetComponents));
19554                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19555                            Slog.i(TAG, "  -- NEW: mMatch="
19556                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19557                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19558                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19559                        }
19560                    }
19561                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19562                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19563                            && cur.mPref.sameSet(set)) {
19564                        // Setting the preferred activity to what it happens to be already
19565                        if (DEBUG_PREFERRED) {
19566                            Slog.i(TAG, "Replacing with same preferred activity "
19567                                    + cur.mPref.mShortComponent + " for user "
19568                                    + userId + ":");
19569                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19570                        }
19571                        return;
19572                    }
19573                }
19574
19575                if (existing != null) {
19576                    if (DEBUG_PREFERRED) {
19577                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19578                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19579                    }
19580                    for (int i = 0; i < existing.size(); i++) {
19581                        PreferredActivity pa = existing.get(i);
19582                        if (DEBUG_PREFERRED) {
19583                            Slog.i(TAG, "Removing existing preferred activity "
19584                                    + pa.mPref.mComponent + ":");
19585                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19586                        }
19587                        pir.removeFilter(pa);
19588                    }
19589                }
19590            }
19591            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19592                    "Replacing preferred");
19593        }
19594    }
19595
19596    @Override
19597    public void clearPackagePreferredActivities(String packageName) {
19598        final int callingUid = Binder.getCallingUid();
19599        if (getInstantAppPackageName(callingUid) != null) {
19600            return;
19601        }
19602        // writer
19603        synchronized (mPackages) {
19604            PackageParser.Package pkg = mPackages.get(packageName);
19605            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19606                if (mContext.checkCallingOrSelfPermission(
19607                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19608                        != PackageManager.PERMISSION_GRANTED) {
19609                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19610                            < Build.VERSION_CODES.FROYO) {
19611                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19612                                + callingUid);
19613                        return;
19614                    }
19615                    mContext.enforceCallingOrSelfPermission(
19616                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19617                }
19618            }
19619            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19620            if (ps != null
19621                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19622                return;
19623            }
19624            int user = UserHandle.getCallingUserId();
19625            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19626                scheduleWritePackageRestrictionsLocked(user);
19627            }
19628        }
19629    }
19630
19631    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19632    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19633        ArrayList<PreferredActivity> removed = null;
19634        boolean changed = false;
19635        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19636            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19637            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19638            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19639                continue;
19640            }
19641            Iterator<PreferredActivity> it = pir.filterIterator();
19642            while (it.hasNext()) {
19643                PreferredActivity pa = it.next();
19644                // Mark entry for removal only if it matches the package name
19645                // and the entry is of type "always".
19646                if (packageName == null ||
19647                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19648                                && pa.mPref.mAlways)) {
19649                    if (removed == null) {
19650                        removed = new ArrayList<PreferredActivity>();
19651                    }
19652                    removed.add(pa);
19653                }
19654            }
19655            if (removed != null) {
19656                for (int j=0; j<removed.size(); j++) {
19657                    PreferredActivity pa = removed.get(j);
19658                    pir.removeFilter(pa);
19659                }
19660                changed = true;
19661            }
19662        }
19663        if (changed) {
19664            postPreferredActivityChangedBroadcast(userId);
19665        }
19666        return changed;
19667    }
19668
19669    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19670    private void clearIntentFilterVerificationsLPw(int userId) {
19671        final int packageCount = mPackages.size();
19672        for (int i = 0; i < packageCount; i++) {
19673            PackageParser.Package pkg = mPackages.valueAt(i);
19674            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19675        }
19676    }
19677
19678    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19679    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19680        if (userId == UserHandle.USER_ALL) {
19681            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19682                    sUserManager.getUserIds())) {
19683                for (int oneUserId : sUserManager.getUserIds()) {
19684                    scheduleWritePackageRestrictionsLocked(oneUserId);
19685                }
19686            }
19687        } else {
19688            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19689                scheduleWritePackageRestrictionsLocked(userId);
19690            }
19691        }
19692    }
19693
19694    /** Clears state for all users, and touches intent filter verification policy */
19695    void clearDefaultBrowserIfNeeded(String packageName) {
19696        for (int oneUserId : sUserManager.getUserIds()) {
19697            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19698        }
19699    }
19700
19701    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19702        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19703        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19704            if (packageName.equals(defaultBrowserPackageName)) {
19705                setDefaultBrowserPackageName(null, userId);
19706            }
19707        }
19708    }
19709
19710    @Override
19711    public void resetApplicationPreferences(int userId) {
19712        mContext.enforceCallingOrSelfPermission(
19713                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19714        final long identity = Binder.clearCallingIdentity();
19715        // writer
19716        try {
19717            synchronized (mPackages) {
19718                clearPackagePreferredActivitiesLPw(null, userId);
19719                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19720                // TODO: We have to reset the default SMS and Phone. This requires
19721                // significant refactoring to keep all default apps in the package
19722                // manager (cleaner but more work) or have the services provide
19723                // callbacks to the package manager to request a default app reset.
19724                applyFactoryDefaultBrowserLPw(userId);
19725                clearIntentFilterVerificationsLPw(userId);
19726                primeDomainVerificationsLPw(userId);
19727                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19728                scheduleWritePackageRestrictionsLocked(userId);
19729            }
19730            resetNetworkPolicies(userId);
19731        } finally {
19732            Binder.restoreCallingIdentity(identity);
19733        }
19734    }
19735
19736    @Override
19737    public int getPreferredActivities(List<IntentFilter> outFilters,
19738            List<ComponentName> outActivities, String packageName) {
19739        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19740            return 0;
19741        }
19742        int num = 0;
19743        final int userId = UserHandle.getCallingUserId();
19744        // reader
19745        synchronized (mPackages) {
19746            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19747            if (pir != null) {
19748                final Iterator<PreferredActivity> it = pir.filterIterator();
19749                while (it.hasNext()) {
19750                    final PreferredActivity pa = it.next();
19751                    if (packageName == null
19752                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19753                                    && pa.mPref.mAlways)) {
19754                        if (outFilters != null) {
19755                            outFilters.add(new IntentFilter(pa));
19756                        }
19757                        if (outActivities != null) {
19758                            outActivities.add(pa.mPref.mComponent);
19759                        }
19760                    }
19761                }
19762            }
19763        }
19764
19765        return num;
19766    }
19767
19768    @Override
19769    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19770            int userId) {
19771        int callingUid = Binder.getCallingUid();
19772        if (callingUid != Process.SYSTEM_UID) {
19773            throw new SecurityException(
19774                    "addPersistentPreferredActivity can only be run by the system");
19775        }
19776        if (filter.countActions() == 0) {
19777            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19778            return;
19779        }
19780        synchronized (mPackages) {
19781            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19782                    ":");
19783            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19784            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19785                    new PersistentPreferredActivity(filter, activity));
19786            scheduleWritePackageRestrictionsLocked(userId);
19787            postPreferredActivityChangedBroadcast(userId);
19788        }
19789    }
19790
19791    @Override
19792    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19793        int callingUid = Binder.getCallingUid();
19794        if (callingUid != Process.SYSTEM_UID) {
19795            throw new SecurityException(
19796                    "clearPackagePersistentPreferredActivities can only be run by the system");
19797        }
19798        ArrayList<PersistentPreferredActivity> removed = null;
19799        boolean changed = false;
19800        synchronized (mPackages) {
19801            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19802                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19803                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19804                        .valueAt(i);
19805                if (userId != thisUserId) {
19806                    continue;
19807                }
19808                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19809                while (it.hasNext()) {
19810                    PersistentPreferredActivity ppa = it.next();
19811                    // Mark entry for removal only if it matches the package name.
19812                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19813                        if (removed == null) {
19814                            removed = new ArrayList<PersistentPreferredActivity>();
19815                        }
19816                        removed.add(ppa);
19817                    }
19818                }
19819                if (removed != null) {
19820                    for (int j=0; j<removed.size(); j++) {
19821                        PersistentPreferredActivity ppa = removed.get(j);
19822                        ppir.removeFilter(ppa);
19823                    }
19824                    changed = true;
19825                }
19826            }
19827
19828            if (changed) {
19829                scheduleWritePackageRestrictionsLocked(userId);
19830                postPreferredActivityChangedBroadcast(userId);
19831            }
19832        }
19833    }
19834
19835    /**
19836     * Common machinery for picking apart a restored XML blob and passing
19837     * it to a caller-supplied functor to be applied to the running system.
19838     */
19839    private void restoreFromXml(XmlPullParser parser, int userId,
19840            String expectedStartTag, BlobXmlRestorer functor)
19841            throws IOException, XmlPullParserException {
19842        int type;
19843        while ((type = parser.next()) != XmlPullParser.START_TAG
19844                && type != XmlPullParser.END_DOCUMENT) {
19845        }
19846        if (type != XmlPullParser.START_TAG) {
19847            // oops didn't find a start tag?!
19848            if (DEBUG_BACKUP) {
19849                Slog.e(TAG, "Didn't find start tag during restore");
19850            }
19851            return;
19852        }
19853Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19854        // this is supposed to be TAG_PREFERRED_BACKUP
19855        if (!expectedStartTag.equals(parser.getName())) {
19856            if (DEBUG_BACKUP) {
19857                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19858            }
19859            return;
19860        }
19861
19862        // skip interfering stuff, then we're aligned with the backing implementation
19863        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19864Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19865        functor.apply(parser, userId);
19866    }
19867
19868    private interface BlobXmlRestorer {
19869        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19870    }
19871
19872    /**
19873     * Non-Binder method, support for the backup/restore mechanism: write the
19874     * full set of preferred activities in its canonical XML format.  Returns the
19875     * XML output as a byte array, or null if there is none.
19876     */
19877    @Override
19878    public byte[] getPreferredActivityBackup(int userId) {
19879        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19880            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19881        }
19882
19883        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19884        try {
19885            final XmlSerializer serializer = new FastXmlSerializer();
19886            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19887            serializer.startDocument(null, true);
19888            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19889
19890            synchronized (mPackages) {
19891                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19892            }
19893
19894            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19895            serializer.endDocument();
19896            serializer.flush();
19897        } catch (Exception e) {
19898            if (DEBUG_BACKUP) {
19899                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19900            }
19901            return null;
19902        }
19903
19904        return dataStream.toByteArray();
19905    }
19906
19907    @Override
19908    public void restorePreferredActivities(byte[] backup, int userId) {
19909        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19910            throw new SecurityException("Only the system may call restorePreferredActivities()");
19911        }
19912
19913        try {
19914            final XmlPullParser parser = Xml.newPullParser();
19915            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19916            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19917                    new BlobXmlRestorer() {
19918                        @Override
19919                        public void apply(XmlPullParser parser, int userId)
19920                                throws XmlPullParserException, IOException {
19921                            synchronized (mPackages) {
19922                                mSettings.readPreferredActivitiesLPw(parser, userId);
19923                            }
19924                        }
19925                    } );
19926        } catch (Exception e) {
19927            if (DEBUG_BACKUP) {
19928                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19929            }
19930        }
19931    }
19932
19933    /**
19934     * Non-Binder method, support for the backup/restore mechanism: write the
19935     * default browser (etc) settings in its canonical XML format.  Returns the default
19936     * browser XML representation as a byte array, or null if there is none.
19937     */
19938    @Override
19939    public byte[] getDefaultAppsBackup(int userId) {
19940        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19941            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
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_DEFAULT_APPS);
19950
19951            synchronized (mPackages) {
19952                mSettings.writeDefaultAppsLPr(serializer, userId);
19953            }
19954
19955            serializer.endTag(null, TAG_DEFAULT_APPS);
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 restoreDefaultApps(byte[] backup, int userId) {
19970        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19971            throw new SecurityException("Only the system may call restoreDefaultApps()");
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_DEFAULT_APPS,
19978                    new BlobXmlRestorer() {
19979                        @Override
19980                        public void apply(XmlPullParser parser, int userId)
19981                                throws XmlPullParserException, IOException {
19982                            synchronized (mPackages) {
19983                                mSettings.readDefaultAppsLPw(parser, userId);
19984                            }
19985                        }
19986                    } );
19987        } catch (Exception e) {
19988            if (DEBUG_BACKUP) {
19989                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19990            }
19991        }
19992    }
19993
19994    @Override
19995    public byte[] getIntentFilterVerificationBackup(int userId) {
19996        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19997            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19998        }
19999
20000        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20001        try {
20002            final XmlSerializer serializer = new FastXmlSerializer();
20003            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20004            serializer.startDocument(null, true);
20005            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20006
20007            synchronized (mPackages) {
20008                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20009            }
20010
20011            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20012            serializer.endDocument();
20013            serializer.flush();
20014        } catch (Exception e) {
20015            if (DEBUG_BACKUP) {
20016                Slog.e(TAG, "Unable to write default apps for backup", e);
20017            }
20018            return null;
20019        }
20020
20021        return dataStream.toByteArray();
20022    }
20023
20024    @Override
20025    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20026        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20027            throw new SecurityException("Only the system may call restorePreferredActivities()");
20028        }
20029
20030        try {
20031            final XmlPullParser parser = Xml.newPullParser();
20032            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20033            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20034                    new BlobXmlRestorer() {
20035                        @Override
20036                        public void apply(XmlPullParser parser, int userId)
20037                                throws XmlPullParserException, IOException {
20038                            synchronized (mPackages) {
20039                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20040                                mSettings.writeLPr();
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    @Override
20052    public byte[] getPermissionGrantBackup(int userId) {
20053        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20054            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20055        }
20056
20057        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20058        try {
20059            final XmlSerializer serializer = new FastXmlSerializer();
20060            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20061            serializer.startDocument(null, true);
20062            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20063
20064            synchronized (mPackages) {
20065                serializeRuntimePermissionGrantsLPr(serializer, userId);
20066            }
20067
20068            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20069            serializer.endDocument();
20070            serializer.flush();
20071        } catch (Exception e) {
20072            if (DEBUG_BACKUP) {
20073                Slog.e(TAG, "Unable to write default apps for backup", e);
20074            }
20075            return null;
20076        }
20077
20078        return dataStream.toByteArray();
20079    }
20080
20081    @Override
20082    public void restorePermissionGrants(byte[] backup, int userId) {
20083        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20084            throw new SecurityException("Only the system may call restorePermissionGrants()");
20085        }
20086
20087        try {
20088            final XmlPullParser parser = Xml.newPullParser();
20089            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20090            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20091                    new BlobXmlRestorer() {
20092                        @Override
20093                        public void apply(XmlPullParser parser, int userId)
20094                                throws XmlPullParserException, IOException {
20095                            synchronized (mPackages) {
20096                                processRestoredPermissionGrantsLPr(parser, userId);
20097                            }
20098                        }
20099                    } );
20100        } catch (Exception e) {
20101            if (DEBUG_BACKUP) {
20102                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20103            }
20104        }
20105    }
20106
20107    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20108            throws IOException {
20109        serializer.startTag(null, TAG_ALL_GRANTS);
20110
20111        final int N = mSettings.mPackages.size();
20112        for (int i = 0; i < N; i++) {
20113            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20114            boolean pkgGrantsKnown = false;
20115
20116            PermissionsState packagePerms = ps.getPermissionsState();
20117
20118            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20119                final int grantFlags = state.getFlags();
20120                // only look at grants that are not system/policy fixed
20121                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20122                    final boolean isGranted = state.isGranted();
20123                    // And only back up the user-twiddled state bits
20124                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20125                        final String packageName = mSettings.mPackages.keyAt(i);
20126                        if (!pkgGrantsKnown) {
20127                            serializer.startTag(null, TAG_GRANT);
20128                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20129                            pkgGrantsKnown = true;
20130                        }
20131
20132                        final boolean userSet =
20133                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20134                        final boolean userFixed =
20135                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20136                        final boolean revoke =
20137                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20138
20139                        serializer.startTag(null, TAG_PERMISSION);
20140                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20141                        if (isGranted) {
20142                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20143                        }
20144                        if (userSet) {
20145                            serializer.attribute(null, ATTR_USER_SET, "true");
20146                        }
20147                        if (userFixed) {
20148                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20149                        }
20150                        if (revoke) {
20151                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20152                        }
20153                        serializer.endTag(null, TAG_PERMISSION);
20154                    }
20155                }
20156            }
20157
20158            if (pkgGrantsKnown) {
20159                serializer.endTag(null, TAG_GRANT);
20160            }
20161        }
20162
20163        serializer.endTag(null, TAG_ALL_GRANTS);
20164    }
20165
20166    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20167            throws XmlPullParserException, IOException {
20168        String pkgName = null;
20169        int outerDepth = parser.getDepth();
20170        int type;
20171        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20172                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20173            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20174                continue;
20175            }
20176
20177            final String tagName = parser.getName();
20178            if (tagName.equals(TAG_GRANT)) {
20179                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20180                if (DEBUG_BACKUP) {
20181                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20182                }
20183            } else if (tagName.equals(TAG_PERMISSION)) {
20184
20185                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20186                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20187
20188                int newFlagSet = 0;
20189                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20190                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20191                }
20192                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20193                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20194                }
20195                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20196                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20197                }
20198                if (DEBUG_BACKUP) {
20199                    Slog.v(TAG, "  + Restoring grant:"
20200                            + " pkg=" + pkgName
20201                            + " perm=" + permName
20202                            + " granted=" + isGranted
20203                            + " bits=0x" + Integer.toHexString(newFlagSet));
20204                }
20205                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20206                if (ps != null) {
20207                    // Already installed so we apply the grant immediately
20208                    if (DEBUG_BACKUP) {
20209                        Slog.v(TAG, "        + already installed; applying");
20210                    }
20211                    PermissionsState perms = ps.getPermissionsState();
20212                    BasePermission bp =
20213                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20214                    if (bp != null) {
20215                        if (isGranted) {
20216                            perms.grantRuntimePermission(bp, userId);
20217                        }
20218                        if (newFlagSet != 0) {
20219                            perms.updatePermissionFlags(
20220                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20221                        }
20222                    }
20223                } else {
20224                    // Need to wait for post-restore install to apply the grant
20225                    if (DEBUG_BACKUP) {
20226                        Slog.v(TAG, "        - not yet installed; saving for later");
20227                    }
20228                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20229                            isGranted, newFlagSet, userId);
20230                }
20231            } else {
20232                PackageManagerService.reportSettingsProblem(Log.WARN,
20233                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20234                XmlUtils.skipCurrentTag(parser);
20235            }
20236        }
20237
20238        scheduleWriteSettingsLocked();
20239        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20240    }
20241
20242    @Override
20243    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20244            int sourceUserId, int targetUserId, int flags) {
20245        mContext.enforceCallingOrSelfPermission(
20246                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20247        int callingUid = Binder.getCallingUid();
20248        enforceOwnerRights(ownerPackage, callingUid);
20249        PackageManagerServiceUtils.enforceShellRestriction(
20250                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20251        if (intentFilter.countActions() == 0) {
20252            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20253            return;
20254        }
20255        synchronized (mPackages) {
20256            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20257                    ownerPackage, targetUserId, flags);
20258            CrossProfileIntentResolver resolver =
20259                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20260            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20261            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20262            if (existing != null) {
20263                int size = existing.size();
20264                for (int i = 0; i < size; i++) {
20265                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20266                        return;
20267                    }
20268                }
20269            }
20270            resolver.addFilter(newFilter);
20271            scheduleWritePackageRestrictionsLocked(sourceUserId);
20272        }
20273    }
20274
20275    @Override
20276    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20277        mContext.enforceCallingOrSelfPermission(
20278                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20279        final int callingUid = Binder.getCallingUid();
20280        enforceOwnerRights(ownerPackage, callingUid);
20281        PackageManagerServiceUtils.enforceShellRestriction(
20282                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20283        synchronized (mPackages) {
20284            CrossProfileIntentResolver resolver =
20285                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20286            ArraySet<CrossProfileIntentFilter> set =
20287                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20288            for (CrossProfileIntentFilter filter : set) {
20289                if (filter.getOwnerPackage().equals(ownerPackage)) {
20290                    resolver.removeFilter(filter);
20291                }
20292            }
20293            scheduleWritePackageRestrictionsLocked(sourceUserId);
20294        }
20295    }
20296
20297    // Enforcing that callingUid is owning pkg on userId
20298    private void enforceOwnerRights(String pkg, int callingUid) {
20299        // The system owns everything.
20300        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20301            return;
20302        }
20303        final int callingUserId = UserHandle.getUserId(callingUid);
20304        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20305        if (pi == null) {
20306            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20307                    + callingUserId);
20308        }
20309        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20310            throw new SecurityException("Calling uid " + callingUid
20311                    + " does not own package " + pkg);
20312        }
20313    }
20314
20315    @Override
20316    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20317        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20318            return null;
20319        }
20320        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20321    }
20322
20323    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20324        UserManagerService ums = UserManagerService.getInstance();
20325        if (ums != null) {
20326            final UserInfo parent = ums.getProfileParent(userId);
20327            final int launcherUid = (parent != null) ? parent.id : userId;
20328            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20329            if (launcherComponent != null) {
20330                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20331                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20332                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20333                        .setPackage(launcherComponent.getPackageName());
20334                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20335            }
20336        }
20337    }
20338
20339    /**
20340     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20341     * then reports the most likely home activity or null if there are more than one.
20342     */
20343    private ComponentName getDefaultHomeActivity(int userId) {
20344        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20345        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20346        if (cn != null) {
20347            return cn;
20348        }
20349
20350        // Find the launcher with the highest priority and return that component if there are no
20351        // other home activity with the same priority.
20352        int lastPriority = Integer.MIN_VALUE;
20353        ComponentName lastComponent = null;
20354        final int size = allHomeCandidates.size();
20355        for (int i = 0; i < size; i++) {
20356            final ResolveInfo ri = allHomeCandidates.get(i);
20357            if (ri.priority > lastPriority) {
20358                lastComponent = ri.activityInfo.getComponentName();
20359                lastPriority = ri.priority;
20360            } else if (ri.priority == lastPriority) {
20361                // Two components found with same priority.
20362                lastComponent = null;
20363            }
20364        }
20365        return lastComponent;
20366    }
20367
20368    private Intent getHomeIntent() {
20369        Intent intent = new Intent(Intent.ACTION_MAIN);
20370        intent.addCategory(Intent.CATEGORY_HOME);
20371        intent.addCategory(Intent.CATEGORY_DEFAULT);
20372        return intent;
20373    }
20374
20375    private IntentFilter getHomeFilter() {
20376        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20377        filter.addCategory(Intent.CATEGORY_HOME);
20378        filter.addCategory(Intent.CATEGORY_DEFAULT);
20379        return filter;
20380    }
20381
20382    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20383            int userId) {
20384        Intent intent  = getHomeIntent();
20385        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20386                PackageManager.GET_META_DATA, userId);
20387        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20388                true, false, false, userId);
20389
20390        allHomeCandidates.clear();
20391        if (list != null) {
20392            for (ResolveInfo ri : list) {
20393                allHomeCandidates.add(ri);
20394            }
20395        }
20396        return (preferred == null || preferred.activityInfo == null)
20397                ? null
20398                : new ComponentName(preferred.activityInfo.packageName,
20399                        preferred.activityInfo.name);
20400    }
20401
20402    @Override
20403    public void setHomeActivity(ComponentName comp, int userId) {
20404        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20405            return;
20406        }
20407        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20408        getHomeActivitiesAsUser(homeActivities, userId);
20409
20410        boolean found = false;
20411
20412        final int size = homeActivities.size();
20413        final ComponentName[] set = new ComponentName[size];
20414        for (int i = 0; i < size; i++) {
20415            final ResolveInfo candidate = homeActivities.get(i);
20416            final ActivityInfo info = candidate.activityInfo;
20417            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20418            set[i] = activityName;
20419            if (!found && activityName.equals(comp)) {
20420                found = true;
20421            }
20422        }
20423        if (!found) {
20424            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20425                    + userId);
20426        }
20427        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20428                set, comp, userId);
20429    }
20430
20431    private @Nullable String getSetupWizardPackageName() {
20432        final Intent intent = new Intent(Intent.ACTION_MAIN);
20433        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20434
20435        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20436                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20437                        | MATCH_DISABLED_COMPONENTS,
20438                UserHandle.myUserId());
20439        if (matches.size() == 1) {
20440            return matches.get(0).getComponentInfo().packageName;
20441        } else {
20442            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20443                    + ": matches=" + matches);
20444            return null;
20445        }
20446    }
20447
20448    private @Nullable String getStorageManagerPackageName() {
20449        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20450
20451        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20452                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20453                        | MATCH_DISABLED_COMPONENTS,
20454                UserHandle.myUserId());
20455        if (matches.size() == 1) {
20456            return matches.get(0).getComponentInfo().packageName;
20457        } else {
20458            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20459                    + matches.size() + ": matches=" + matches);
20460            return null;
20461        }
20462    }
20463
20464    @Override
20465    public String getSystemTextClassifierPackageName() {
20466        return mContext.getString(R.string.config_defaultTextClassifierPackage);
20467    }
20468
20469    @Override
20470    public void setApplicationEnabledSetting(String appPackageName,
20471            int newState, int flags, int userId, String callingPackage) {
20472        if (!sUserManager.exists(userId)) return;
20473        if (callingPackage == null) {
20474            callingPackage = Integer.toString(Binder.getCallingUid());
20475        }
20476        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20477    }
20478
20479    @Override
20480    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20481        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20482        synchronized (mPackages) {
20483            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20484            if (pkgSetting != null) {
20485                pkgSetting.setUpdateAvailable(updateAvailable);
20486            }
20487        }
20488    }
20489
20490    @Override
20491    public void setComponentEnabledSetting(ComponentName componentName,
20492            int newState, int flags, int userId) {
20493        if (!sUserManager.exists(userId)) return;
20494        setEnabledSetting(componentName.getPackageName(),
20495                componentName.getClassName(), newState, flags, userId, null);
20496    }
20497
20498    private void setEnabledSetting(final String packageName, String className, int newState,
20499            final int flags, int userId, String callingPackage) {
20500        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20501              || newState == COMPONENT_ENABLED_STATE_ENABLED
20502              || newState == COMPONENT_ENABLED_STATE_DISABLED
20503              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20504              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20505            throw new IllegalArgumentException("Invalid new component state: "
20506                    + newState);
20507        }
20508        PackageSetting pkgSetting;
20509        final int callingUid = Binder.getCallingUid();
20510        final int permission;
20511        if (callingUid == Process.SYSTEM_UID) {
20512            permission = PackageManager.PERMISSION_GRANTED;
20513        } else {
20514            permission = mContext.checkCallingOrSelfPermission(
20515                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20516        }
20517        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20518                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20519        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20520        boolean sendNow = false;
20521        boolean isApp = (className == null);
20522        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20523        String componentName = isApp ? packageName : className;
20524        int packageUid = -1;
20525        ArrayList<String> components;
20526
20527        // reader
20528        synchronized (mPackages) {
20529            pkgSetting = mSettings.mPackages.get(packageName);
20530            if (pkgSetting == null) {
20531                if (!isCallerInstantApp) {
20532                    if (className == null) {
20533                        throw new IllegalArgumentException("Unknown package: " + packageName);
20534                    }
20535                    throw new IllegalArgumentException(
20536                            "Unknown component: " + packageName + "/" + className);
20537                } else {
20538                    // throw SecurityException to prevent leaking package information
20539                    throw new SecurityException(
20540                            "Attempt to change component state; "
20541                            + "pid=" + Binder.getCallingPid()
20542                            + ", uid=" + callingUid
20543                            + (className == null
20544                                    ? ", package=" + packageName
20545                                    : ", component=" + packageName + "/" + className));
20546                }
20547            }
20548        }
20549
20550        // Limit who can change which apps
20551        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20552            // Don't allow apps that don't have permission to modify other apps
20553            if (!allowedByPermission
20554                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20555                throw new SecurityException(
20556                        "Attempt to change component state; "
20557                        + "pid=" + Binder.getCallingPid()
20558                        + ", uid=" + callingUid
20559                        + (className == null
20560                                ? ", package=" + packageName
20561                                : ", component=" + packageName + "/" + className));
20562            }
20563            // Don't allow changing protected packages.
20564            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20565                throw new SecurityException("Cannot disable a protected package: " + packageName);
20566            }
20567        }
20568
20569        synchronized (mPackages) {
20570            if (callingUid == Process.SHELL_UID
20571                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20572                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20573                // unless it is a test package.
20574                int oldState = pkgSetting.getEnabled(userId);
20575                if (className == null
20576                        &&
20577                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20578                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20579                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20580                        &&
20581                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20582                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20583                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20584                    // ok
20585                } else {
20586                    throw new SecurityException(
20587                            "Shell cannot change component state for " + packageName + "/"
20588                                    + className + " to " + newState);
20589                }
20590            }
20591        }
20592        if (className == null) {
20593            // We're dealing with an application/package level state change
20594            synchronized (mPackages) {
20595                if (pkgSetting.getEnabled(userId) == newState) {
20596                    // Nothing to do
20597                    return;
20598                }
20599            }
20600            // If we're enabling a system stub, there's a little more work to do.
20601            // Prior to enabling the package, we need to decompress the APK(s) to the
20602            // data partition and then replace the version on the system partition.
20603            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20604            final boolean isSystemStub = deletedPkg.isStub
20605                    && deletedPkg.isSystem();
20606            if (isSystemStub
20607                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20608                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20609                final File codePath = decompressPackage(deletedPkg);
20610                if (codePath == null) {
20611                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20612                    return;
20613                }
20614                // TODO remove direct parsing of the package object during internal cleanup
20615                // of scan package
20616                // We need to call parse directly here for no other reason than we need
20617                // the new package in order to disable the old one [we use the information
20618                // for some internal optimization to optionally create a new package setting
20619                // object on replace]. However, we can't get the package from the scan
20620                // because the scan modifies live structures and we need to remove the
20621                // old [system] package from the system before a scan can be attempted.
20622                // Once scan is indempotent we can remove this parse and use the package
20623                // object we scanned, prior to adding it to package settings.
20624                final PackageParser pp = new PackageParser();
20625                pp.setSeparateProcesses(mSeparateProcesses);
20626                pp.setDisplayMetrics(mMetrics);
20627                pp.setCallback(mPackageParserCallback);
20628                final PackageParser.Package tmpPkg;
20629                try {
20630                    final @ParseFlags int parseFlags = mDefParseFlags
20631                            | PackageParser.PARSE_MUST_BE_APK
20632                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20633                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20634                } catch (PackageParserException e) {
20635                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20636                    return;
20637                }
20638                synchronized (mInstallLock) {
20639                    // Disable the stub and remove any package entries
20640                    removePackageLI(deletedPkg, true);
20641                    synchronized (mPackages) {
20642                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20643                    }
20644                    final PackageParser.Package pkg;
20645                    try (PackageFreezer freezer =
20646                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20647                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20648                                | PackageParser.PARSE_ENFORCE_CODE;
20649                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20650                                0 /*currentTime*/, null /*user*/);
20651                        prepareAppDataAfterInstallLIF(pkg);
20652                        synchronized (mPackages) {
20653                            try {
20654                                updateSharedLibrariesLPr(pkg, null);
20655                            } catch (PackageManagerException e) {
20656                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20657                            }
20658                            mPermissionManager.updatePermissions(
20659                                    pkg.packageName, pkg, true, mPackages.values(),
20660                                    mPermissionCallback);
20661                            mSettings.writeLPr();
20662                        }
20663                    } catch (PackageManagerException e) {
20664                        // Whoops! Something went wrong; try to roll back to the stub
20665                        Slog.w(TAG, "Failed to install compressed system package:"
20666                                + pkgSetting.name, e);
20667                        // Remove the failed install
20668                        removeCodePathLI(codePath);
20669
20670                        // Install the system package
20671                        try (PackageFreezer freezer =
20672                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20673                            synchronized (mPackages) {
20674                                // NOTE: The system package always needs to be enabled; even
20675                                // if it's for a compressed stub. If we don't, installing the
20676                                // system package fails during scan [scanning checks the disabled
20677                                // packages]. We will reverse this later, after we've "installed"
20678                                // the stub.
20679                                // This leaves us in a fragile state; the stub should never be
20680                                // enabled, so, cross your fingers and hope nothing goes wrong
20681                                // until we can disable the package later.
20682                                enableSystemPackageLPw(deletedPkg);
20683                            }
20684                            installPackageFromSystemLIF(deletedPkg.codePath,
20685                                    false /*isPrivileged*/, null /*allUserHandles*/,
20686                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20687                                    true /*writeSettings*/);
20688                        } catch (PackageManagerException pme) {
20689                            Slog.w(TAG, "Failed to restore system package:"
20690                                    + deletedPkg.packageName, pme);
20691                        } finally {
20692                            synchronized (mPackages) {
20693                                mSettings.disableSystemPackageLPw(
20694                                        deletedPkg.packageName, true /*replaced*/);
20695                                mSettings.writeLPr();
20696                            }
20697                        }
20698                        return;
20699                    }
20700                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20701                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20702                    mDexManager.notifyPackageUpdated(pkg.packageName,
20703                            pkg.baseCodePath, pkg.splitCodePaths);
20704                }
20705            }
20706            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20707                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20708                // Don't care about who enables an app.
20709                callingPackage = null;
20710            }
20711            synchronized (mPackages) {
20712                pkgSetting.setEnabled(newState, userId, callingPackage);
20713            }
20714        } else {
20715            synchronized (mPackages) {
20716                // We're dealing with a component level state change
20717                // First, verify that this is a valid class name.
20718                PackageParser.Package pkg = pkgSetting.pkg;
20719                if (pkg == null || !pkg.hasComponentClassName(className)) {
20720                    if (pkg != null &&
20721                            pkg.applicationInfo.targetSdkVersion >=
20722                                    Build.VERSION_CODES.JELLY_BEAN) {
20723                        throw new IllegalArgumentException("Component class " + className
20724                                + " does not exist in " + packageName);
20725                    } else {
20726                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20727                                + className + " does not exist in " + packageName);
20728                    }
20729                }
20730                switch (newState) {
20731                    case COMPONENT_ENABLED_STATE_ENABLED:
20732                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20733                            return;
20734                        }
20735                        break;
20736                    case COMPONENT_ENABLED_STATE_DISABLED:
20737                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20738                            return;
20739                        }
20740                        break;
20741                    case COMPONENT_ENABLED_STATE_DEFAULT:
20742                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20743                            return;
20744                        }
20745                        break;
20746                    default:
20747                        Slog.e(TAG, "Invalid new component state: " + newState);
20748                        return;
20749                }
20750            }
20751        }
20752        synchronized (mPackages) {
20753            scheduleWritePackageRestrictionsLocked(userId);
20754            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20755            final long callingId = Binder.clearCallingIdentity();
20756            try {
20757                updateInstantAppInstallerLocked(packageName);
20758            } finally {
20759                Binder.restoreCallingIdentity(callingId);
20760            }
20761            components = mPendingBroadcasts.get(userId, packageName);
20762            final boolean newPackage = components == null;
20763            if (newPackage) {
20764                components = new ArrayList<String>();
20765            }
20766            if (!components.contains(componentName)) {
20767                components.add(componentName);
20768            }
20769            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20770                sendNow = true;
20771                // Purge entry from pending broadcast list if another one exists already
20772                // since we are sending one right away.
20773                mPendingBroadcasts.remove(userId, packageName);
20774            } else {
20775                if (newPackage) {
20776                    mPendingBroadcasts.put(userId, packageName, components);
20777                }
20778                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20779                    // Schedule a message
20780                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20781                }
20782            }
20783        }
20784
20785        long callingId = Binder.clearCallingIdentity();
20786        try {
20787            if (sendNow) {
20788                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20789                sendPackageChangedBroadcast(packageName,
20790                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20791            }
20792        } finally {
20793            Binder.restoreCallingIdentity(callingId);
20794        }
20795    }
20796
20797    @Override
20798    public void flushPackageRestrictionsAsUser(int userId) {
20799        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20800            return;
20801        }
20802        if (!sUserManager.exists(userId)) {
20803            return;
20804        }
20805        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20806                false /* checkShell */, "flushPackageRestrictions");
20807        synchronized (mPackages) {
20808            mSettings.writePackageRestrictionsLPr(userId);
20809            mDirtyUsers.remove(userId);
20810            if (mDirtyUsers.isEmpty()) {
20811                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20812            }
20813        }
20814    }
20815
20816    private void sendPackageChangedBroadcast(String packageName,
20817            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20818        if (DEBUG_INSTALL)
20819            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20820                    + componentNames);
20821        Bundle extras = new Bundle(4);
20822        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20823        String nameList[] = new String[componentNames.size()];
20824        componentNames.toArray(nameList);
20825        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20826        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20827        extras.putInt(Intent.EXTRA_UID, packageUid);
20828        // If this is not reporting a change of the overall package, then only send it
20829        // to registered receivers.  We don't want to launch a swath of apps for every
20830        // little component state change.
20831        final int flags = !componentNames.contains(packageName)
20832                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20833        final int userId = UserHandle.getUserId(packageUid);
20834        final boolean isInstantApp = isInstantApp(packageName, userId);
20835        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20836        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20837        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20838                userIds, instantUserIds);
20839    }
20840
20841    @Override
20842    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20843        if (!sUserManager.exists(userId)) return;
20844        final int callingUid = Binder.getCallingUid();
20845        if (getInstantAppPackageName(callingUid) != null) {
20846            return;
20847        }
20848        final int permission = mContext.checkCallingOrSelfPermission(
20849                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20850        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20851        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20852                true /* requireFullPermission */, true /* checkShell */, "stop package");
20853        // writer
20854        synchronized (mPackages) {
20855            final PackageSetting ps = mSettings.mPackages.get(packageName);
20856            if (!filterAppAccessLPr(ps, callingUid, userId)
20857                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20858                            allowedByPermission, callingUid, userId)) {
20859                scheduleWritePackageRestrictionsLocked(userId);
20860            }
20861        }
20862    }
20863
20864    @Override
20865    public String getInstallerPackageName(String packageName) {
20866        final int callingUid = Binder.getCallingUid();
20867        synchronized (mPackages) {
20868            final PackageSetting ps = mSettings.mPackages.get(packageName);
20869            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20870                return null;
20871            }
20872            return mSettings.getInstallerPackageNameLPr(packageName);
20873        }
20874    }
20875
20876    public boolean isOrphaned(String packageName) {
20877        // reader
20878        synchronized (mPackages) {
20879            return mSettings.isOrphaned(packageName);
20880        }
20881    }
20882
20883    @Override
20884    public int getApplicationEnabledSetting(String packageName, int userId) {
20885        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20886        int callingUid = Binder.getCallingUid();
20887        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20888                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20889        // reader
20890        synchronized (mPackages) {
20891            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20892                return COMPONENT_ENABLED_STATE_DISABLED;
20893            }
20894            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20895        }
20896    }
20897
20898    @Override
20899    public int getComponentEnabledSetting(ComponentName component, int userId) {
20900        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20901        int callingUid = Binder.getCallingUid();
20902        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20903                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20904        synchronized (mPackages) {
20905            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20906                    component, TYPE_UNKNOWN, userId)) {
20907                return COMPONENT_ENABLED_STATE_DISABLED;
20908            }
20909            return mSettings.getComponentEnabledSettingLPr(component, userId);
20910        }
20911    }
20912
20913    @Override
20914    public void enterSafeMode() {
20915        enforceSystemOrRoot("Only the system can request entering safe mode");
20916
20917        if (!mSystemReady) {
20918            mSafeMode = true;
20919        }
20920    }
20921
20922    @Override
20923    public void systemReady() {
20924        enforceSystemOrRoot("Only the system can claim the system is ready");
20925
20926        mSystemReady = true;
20927        final ContentResolver resolver = mContext.getContentResolver();
20928        ContentObserver co = new ContentObserver(mHandler) {
20929            @Override
20930            public void onChange(boolean selfChange) {
20931                mWebInstantAppsDisabled =
20932                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20933                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20934            }
20935        };
20936        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20937                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20938                false, co, UserHandle.USER_SYSTEM);
20939        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
20940                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20941        co.onChange(true);
20942
20943        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20944        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20945        // it is done.
20946        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20947            @Override
20948            public void onChange(boolean selfChange) {
20949                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20950                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20951                        oobEnabled == 1 ? "true" : "false");
20952            }
20953        };
20954        mContext.getContentResolver().registerContentObserver(
20955                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20956                UserHandle.USER_SYSTEM);
20957        // At boot, restore the value from the setting, which persists across reboot.
20958        privAppOobObserver.onChange(true);
20959
20960        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20961        // disabled after already being started.
20962        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20963                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20964
20965        // Read the compatibilty setting when the system is ready.
20966        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20967                mContext.getContentResolver(),
20968                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20969        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20970        if (DEBUG_SETTINGS) {
20971            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20972        }
20973
20974        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20975
20976        synchronized (mPackages) {
20977            // Verify that all of the preferred activity components actually
20978            // exist.  It is possible for applications to be updated and at
20979            // that point remove a previously declared activity component that
20980            // had been set as a preferred activity.  We try to clean this up
20981            // the next time we encounter that preferred activity, but it is
20982            // possible for the user flow to never be able to return to that
20983            // situation so here we do a sanity check to make sure we haven't
20984            // left any junk around.
20985            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20986            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20987                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20988                removed.clear();
20989                for (PreferredActivity pa : pir.filterSet()) {
20990                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20991                        removed.add(pa);
20992                    }
20993                }
20994                if (removed.size() > 0) {
20995                    for (int r=0; r<removed.size(); r++) {
20996                        PreferredActivity pa = removed.get(r);
20997                        Slog.w(TAG, "Removing dangling preferred activity: "
20998                                + pa.mPref.mComponent);
20999                        pir.removeFilter(pa);
21000                    }
21001                    mSettings.writePackageRestrictionsLPr(
21002                            mSettings.mPreferredActivities.keyAt(i));
21003                }
21004            }
21005
21006            for (int userId : UserManagerService.getInstance().getUserIds()) {
21007                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21008                    grantPermissionsUserIds = ArrayUtils.appendInt(
21009                            grantPermissionsUserIds, userId);
21010                }
21011            }
21012        }
21013        sUserManager.systemReady();
21014        // If we upgraded grant all default permissions before kicking off.
21015        for (int userId : grantPermissionsUserIds) {
21016            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21017        }
21018
21019        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21020            // If we did not grant default permissions, we preload from this the
21021            // default permission exceptions lazily to ensure we don't hit the
21022            // disk on a new user creation.
21023            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21024        }
21025
21026        // Now that we've scanned all packages, and granted any default
21027        // permissions, ensure permissions are updated. Beware of dragons if you
21028        // try optimizing this.
21029        synchronized (mPackages) {
21030            mPermissionManager.updateAllPermissions(
21031                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
21032                    mPermissionCallback);
21033        }
21034
21035        // Kick off any messages waiting for system ready
21036        if (mPostSystemReadyMessages != null) {
21037            for (Message msg : mPostSystemReadyMessages) {
21038                msg.sendToTarget();
21039            }
21040            mPostSystemReadyMessages = null;
21041        }
21042
21043        // Watch for external volumes that come and go over time
21044        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21045        storage.registerListener(mStorageListener);
21046
21047        mInstallerService.systemReady();
21048        mPackageDexOptimizer.systemReady();
21049
21050        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21051                StorageManagerInternal.class);
21052        StorageManagerInternal.addExternalStoragePolicy(
21053                new StorageManagerInternal.ExternalStorageMountPolicy() {
21054            @Override
21055            public int getMountMode(int uid, String packageName) {
21056                if (Process.isIsolated(uid)) {
21057                    return Zygote.MOUNT_EXTERNAL_NONE;
21058                }
21059                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21060                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21061                }
21062                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21063                    return Zygote.MOUNT_EXTERNAL_READ;
21064                }
21065                return Zygote.MOUNT_EXTERNAL_WRITE;
21066            }
21067
21068            @Override
21069            public boolean hasExternalStorage(int uid, String packageName) {
21070                return true;
21071            }
21072        });
21073
21074        // Now that we're mostly running, clean up stale users and apps
21075        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21076        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21077
21078        mPermissionManager.systemReady();
21079
21080        if (mInstantAppResolverConnection != null) {
21081            mContext.registerReceiver(new BroadcastReceiver() {
21082                @Override
21083                public void onReceive(Context context, Intent intent) {
21084                    mInstantAppResolverConnection.optimisticBind();
21085                    mContext.unregisterReceiver(this);
21086                }
21087            }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
21088        }
21089    }
21090
21091    public void waitForAppDataPrepared() {
21092        if (mPrepareAppDataFuture == null) {
21093            return;
21094        }
21095        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21096        mPrepareAppDataFuture = null;
21097    }
21098
21099    @Override
21100    public boolean isSafeMode() {
21101        // allow instant applications
21102        return mSafeMode;
21103    }
21104
21105    @Override
21106    public boolean hasSystemUidErrors() {
21107        // allow instant applications
21108        return mHasSystemUidErrors;
21109    }
21110
21111    static String arrayToString(int[] array) {
21112        StringBuffer buf = new StringBuffer(128);
21113        buf.append('[');
21114        if (array != null) {
21115            for (int i=0; i<array.length; i++) {
21116                if (i > 0) buf.append(", ");
21117                buf.append(array[i]);
21118            }
21119        }
21120        buf.append(']');
21121        return buf.toString();
21122    }
21123
21124    @Override
21125    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21126            FileDescriptor err, String[] args, ShellCallback callback,
21127            ResultReceiver resultReceiver) {
21128        (new PackageManagerShellCommand(this)).exec(
21129                this, in, out, err, args, callback, resultReceiver);
21130    }
21131
21132    @Override
21133    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21134        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21135
21136        DumpState dumpState = new DumpState();
21137        boolean fullPreferred = false;
21138        boolean checkin = false;
21139
21140        String packageName = null;
21141        ArraySet<String> permissionNames = null;
21142
21143        int opti = 0;
21144        while (opti < args.length) {
21145            String opt = args[opti];
21146            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21147                break;
21148            }
21149            opti++;
21150
21151            if ("-a".equals(opt)) {
21152                // Right now we only know how to print all.
21153            } else if ("-h".equals(opt)) {
21154                pw.println("Package manager dump options:");
21155                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21156                pw.println("    --checkin: dump for a checkin");
21157                pw.println("    -f: print details of intent filters");
21158                pw.println("    -h: print this help");
21159                pw.println("  cmd may be one of:");
21160                pw.println("    l[ibraries]: list known shared libraries");
21161                pw.println("    f[eatures]: list device features");
21162                pw.println("    k[eysets]: print known keysets");
21163                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21164                pw.println("    perm[issions]: dump permissions");
21165                pw.println("    permission [name ...]: dump declaration and use of given permission");
21166                pw.println("    pref[erred]: print preferred package settings");
21167                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21168                pw.println("    prov[iders]: dump content providers");
21169                pw.println("    p[ackages]: dump installed packages");
21170                pw.println("    s[hared-users]: dump shared user IDs");
21171                pw.println("    m[essages]: print collected runtime messages");
21172                pw.println("    v[erifiers]: print package verifier info");
21173                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21174                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21175                pw.println("    version: print database version info");
21176                pw.println("    write: write current settings now");
21177                pw.println("    installs: details about install sessions");
21178                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21179                pw.println("    dexopt: dump dexopt state");
21180                pw.println("    compiler-stats: dump compiler statistics");
21181                pw.println("    service-permissions: dump permissions required by services");
21182                pw.println("    <package.name>: info about given package");
21183                return;
21184            } else if ("--checkin".equals(opt)) {
21185                checkin = true;
21186            } else if ("-f".equals(opt)) {
21187                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21188            } else if ("--proto".equals(opt)) {
21189                dumpProto(fd);
21190                return;
21191            } else {
21192                pw.println("Unknown argument: " + opt + "; use -h for help");
21193            }
21194        }
21195
21196        // Is the caller requesting to dump a particular piece of data?
21197        if (opti < args.length) {
21198            String cmd = args[opti];
21199            opti++;
21200            // Is this a package name?
21201            if ("android".equals(cmd) || cmd.contains(".")) {
21202                packageName = cmd;
21203                // When dumping a single package, we always dump all of its
21204                // filter information since the amount of data will be reasonable.
21205                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21206            } else if ("check-permission".equals(cmd)) {
21207                if (opti >= args.length) {
21208                    pw.println("Error: check-permission missing permission argument");
21209                    return;
21210                }
21211                String perm = args[opti];
21212                opti++;
21213                if (opti >= args.length) {
21214                    pw.println("Error: check-permission missing package argument");
21215                    return;
21216                }
21217
21218                String pkg = args[opti];
21219                opti++;
21220                int user = UserHandle.getUserId(Binder.getCallingUid());
21221                if (opti < args.length) {
21222                    try {
21223                        user = Integer.parseInt(args[opti]);
21224                    } catch (NumberFormatException e) {
21225                        pw.println("Error: check-permission user argument is not a number: "
21226                                + args[opti]);
21227                        return;
21228                    }
21229                }
21230
21231                // Normalize package name to handle renamed packages and static libs
21232                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21233
21234                pw.println(checkPermission(perm, pkg, user));
21235                return;
21236            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21237                dumpState.setDump(DumpState.DUMP_LIBS);
21238            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21239                dumpState.setDump(DumpState.DUMP_FEATURES);
21240            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21241                if (opti >= args.length) {
21242                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21243                            | DumpState.DUMP_SERVICE_RESOLVERS
21244                            | DumpState.DUMP_RECEIVER_RESOLVERS
21245                            | DumpState.DUMP_CONTENT_RESOLVERS);
21246                } else {
21247                    while (opti < args.length) {
21248                        String name = args[opti];
21249                        if ("a".equals(name) || "activity".equals(name)) {
21250                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21251                        } else if ("s".equals(name) || "service".equals(name)) {
21252                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21253                        } else if ("r".equals(name) || "receiver".equals(name)) {
21254                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21255                        } else if ("c".equals(name) || "content".equals(name)) {
21256                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21257                        } else {
21258                            pw.println("Error: unknown resolver table type: " + name);
21259                            return;
21260                        }
21261                        opti++;
21262                    }
21263                }
21264            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21265                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21266            } else if ("permission".equals(cmd)) {
21267                if (opti >= args.length) {
21268                    pw.println("Error: permission requires permission name");
21269                    return;
21270                }
21271                permissionNames = new ArraySet<>();
21272                while (opti < args.length) {
21273                    permissionNames.add(args[opti]);
21274                    opti++;
21275                }
21276                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21277                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21278            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21279                dumpState.setDump(DumpState.DUMP_PREFERRED);
21280            } else if ("preferred-xml".equals(cmd)) {
21281                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21282                if (opti < args.length && "--full".equals(args[opti])) {
21283                    fullPreferred = true;
21284                    opti++;
21285                }
21286            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21287                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21288            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21289                dumpState.setDump(DumpState.DUMP_PACKAGES);
21290            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21291                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21292            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21293                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21294            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21295                dumpState.setDump(DumpState.DUMP_MESSAGES);
21296            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21297                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21298            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21299                    || "intent-filter-verifiers".equals(cmd)) {
21300                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21301            } else if ("version".equals(cmd)) {
21302                dumpState.setDump(DumpState.DUMP_VERSION);
21303            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21304                dumpState.setDump(DumpState.DUMP_KEYSETS);
21305            } else if ("installs".equals(cmd)) {
21306                dumpState.setDump(DumpState.DUMP_INSTALLS);
21307            } else if ("frozen".equals(cmd)) {
21308                dumpState.setDump(DumpState.DUMP_FROZEN);
21309            } else if ("volumes".equals(cmd)) {
21310                dumpState.setDump(DumpState.DUMP_VOLUMES);
21311            } else if ("dexopt".equals(cmd)) {
21312                dumpState.setDump(DumpState.DUMP_DEXOPT);
21313            } else if ("compiler-stats".equals(cmd)) {
21314                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21315            } else if ("changes".equals(cmd)) {
21316                dumpState.setDump(DumpState.DUMP_CHANGES);
21317            } else if ("service-permissions".equals(cmd)) {
21318                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21319            } else if ("write".equals(cmd)) {
21320                synchronized (mPackages) {
21321                    mSettings.writeLPr();
21322                    pw.println("Settings written.");
21323                    return;
21324                }
21325            }
21326        }
21327
21328        if (checkin) {
21329            pw.println("vers,1");
21330        }
21331
21332        // reader
21333        synchronized (mPackages) {
21334            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21335                if (!checkin) {
21336                    if (dumpState.onTitlePrinted())
21337                        pw.println();
21338                    pw.println("Database versions:");
21339                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21340                }
21341            }
21342
21343            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21344                if (!checkin) {
21345                    if (dumpState.onTitlePrinted())
21346                        pw.println();
21347                    pw.println("Verifiers:");
21348                    pw.print("  Required: ");
21349                    pw.print(mRequiredVerifierPackage);
21350                    pw.print(" (uid=");
21351                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21352                            UserHandle.USER_SYSTEM));
21353                    pw.println(")");
21354                } else if (mRequiredVerifierPackage != null) {
21355                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21356                    pw.print(",");
21357                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21358                            UserHandle.USER_SYSTEM));
21359                }
21360            }
21361
21362            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21363                    packageName == null) {
21364                if (mIntentFilterVerifierComponent != null) {
21365                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21366                    if (!checkin) {
21367                        if (dumpState.onTitlePrinted())
21368                            pw.println();
21369                        pw.println("Intent Filter Verifier:");
21370                        pw.print("  Using: ");
21371                        pw.print(verifierPackageName);
21372                        pw.print(" (uid=");
21373                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21374                                UserHandle.USER_SYSTEM));
21375                        pw.println(")");
21376                    } else if (verifierPackageName != null) {
21377                        pw.print("ifv,"); pw.print(verifierPackageName);
21378                        pw.print(",");
21379                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21380                                UserHandle.USER_SYSTEM));
21381                    }
21382                } else {
21383                    pw.println();
21384                    pw.println("No Intent Filter Verifier available!");
21385                }
21386            }
21387
21388            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21389                boolean printedHeader = false;
21390                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21391                while (it.hasNext()) {
21392                    String libName = it.next();
21393                    LongSparseArray<SharedLibraryEntry> versionedLib
21394                            = mSharedLibraries.get(libName);
21395                    if (versionedLib == null) {
21396                        continue;
21397                    }
21398                    final int versionCount = versionedLib.size();
21399                    for (int i = 0; i < versionCount; i++) {
21400                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21401                        if (!checkin) {
21402                            if (!printedHeader) {
21403                                if (dumpState.onTitlePrinted())
21404                                    pw.println();
21405                                pw.println("Libraries:");
21406                                printedHeader = true;
21407                            }
21408                            pw.print("  ");
21409                        } else {
21410                            pw.print("lib,");
21411                        }
21412                        pw.print(libEntry.info.getName());
21413                        if (libEntry.info.isStatic()) {
21414                            pw.print(" version=" + libEntry.info.getLongVersion());
21415                        }
21416                        if (!checkin) {
21417                            pw.print(" -> ");
21418                        }
21419                        if (libEntry.path != null) {
21420                            pw.print(" (jar) ");
21421                            pw.print(libEntry.path);
21422                        } else {
21423                            pw.print(" (apk) ");
21424                            pw.print(libEntry.apk);
21425                        }
21426                        pw.println();
21427                    }
21428                }
21429            }
21430
21431            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21432                if (dumpState.onTitlePrinted())
21433                    pw.println();
21434                if (!checkin) {
21435                    pw.println("Features:");
21436                }
21437
21438                synchronized (mAvailableFeatures) {
21439                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21440                        if (checkin) {
21441                            pw.print("feat,");
21442                            pw.print(feat.name);
21443                            pw.print(",");
21444                            pw.println(feat.version);
21445                        } else {
21446                            pw.print("  ");
21447                            pw.print(feat.name);
21448                            if (feat.version > 0) {
21449                                pw.print(" version=");
21450                                pw.print(feat.version);
21451                            }
21452                            pw.println();
21453                        }
21454                    }
21455                }
21456            }
21457
21458            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21459                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21460                        : "Activity Resolver Table:", "  ", packageName,
21461                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21462                    dumpState.setTitlePrinted(true);
21463                }
21464            }
21465            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21466                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21467                        : "Receiver Resolver Table:", "  ", packageName,
21468                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21469                    dumpState.setTitlePrinted(true);
21470                }
21471            }
21472            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21473                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21474                        : "Service Resolver Table:", "  ", packageName,
21475                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21476                    dumpState.setTitlePrinted(true);
21477                }
21478            }
21479            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21480                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21481                        : "Provider Resolver Table:", "  ", packageName,
21482                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21483                    dumpState.setTitlePrinted(true);
21484                }
21485            }
21486
21487            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21488                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21489                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21490                    int user = mSettings.mPreferredActivities.keyAt(i);
21491                    if (pir.dump(pw,
21492                            dumpState.getTitlePrinted()
21493                                ? "\nPreferred Activities User " + user + ":"
21494                                : "Preferred Activities User " + user + ":", "  ",
21495                            packageName, true, false)) {
21496                        dumpState.setTitlePrinted(true);
21497                    }
21498                }
21499            }
21500
21501            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21502                pw.flush();
21503                FileOutputStream fout = new FileOutputStream(fd);
21504                BufferedOutputStream str = new BufferedOutputStream(fout);
21505                XmlSerializer serializer = new FastXmlSerializer();
21506                try {
21507                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21508                    serializer.startDocument(null, true);
21509                    serializer.setFeature(
21510                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21511                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21512                    serializer.endDocument();
21513                    serializer.flush();
21514                } catch (IllegalArgumentException e) {
21515                    pw.println("Failed writing: " + e);
21516                } catch (IllegalStateException e) {
21517                    pw.println("Failed writing: " + e);
21518                } catch (IOException e) {
21519                    pw.println("Failed writing: " + e);
21520                }
21521            }
21522
21523            if (!checkin
21524                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21525                    && packageName == null) {
21526                pw.println();
21527                int count = mSettings.mPackages.size();
21528                if (count == 0) {
21529                    pw.println("No applications!");
21530                    pw.println();
21531                } else {
21532                    final String prefix = "  ";
21533                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21534                    if (allPackageSettings.size() == 0) {
21535                        pw.println("No domain preferred apps!");
21536                        pw.println();
21537                    } else {
21538                        pw.println("App verification status:");
21539                        pw.println();
21540                        count = 0;
21541                        for (PackageSetting ps : allPackageSettings) {
21542                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21543                            if (ivi == null || ivi.getPackageName() == null) continue;
21544                            pw.println(prefix + "Package: " + ivi.getPackageName());
21545                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21546                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21547                            pw.println();
21548                            count++;
21549                        }
21550                        if (count == 0) {
21551                            pw.println(prefix + "No app verification established.");
21552                            pw.println();
21553                        }
21554                        for (int userId : sUserManager.getUserIds()) {
21555                            pw.println("App linkages for user " + userId + ":");
21556                            pw.println();
21557                            count = 0;
21558                            for (PackageSetting ps : allPackageSettings) {
21559                                final long status = ps.getDomainVerificationStatusForUser(userId);
21560                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21561                                        && !DEBUG_DOMAIN_VERIFICATION) {
21562                                    continue;
21563                                }
21564                                pw.println(prefix + "Package: " + ps.name);
21565                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21566                                String statusStr = IntentFilterVerificationInfo.
21567                                        getStatusStringFromValue(status);
21568                                pw.println(prefix + "Status:  " + statusStr);
21569                                pw.println();
21570                                count++;
21571                            }
21572                            if (count == 0) {
21573                                pw.println(prefix + "No configured app linkages.");
21574                                pw.println();
21575                            }
21576                        }
21577                    }
21578                }
21579            }
21580
21581            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21582                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21583            }
21584
21585            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21586                boolean printedSomething = false;
21587                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21588                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21589                        continue;
21590                    }
21591                    if (!printedSomething) {
21592                        if (dumpState.onTitlePrinted())
21593                            pw.println();
21594                        pw.println("Registered ContentProviders:");
21595                        printedSomething = true;
21596                    }
21597                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21598                    pw.print("    "); pw.println(p.toString());
21599                }
21600                printedSomething = false;
21601                for (Map.Entry<String, PackageParser.Provider> entry :
21602                        mProvidersByAuthority.entrySet()) {
21603                    PackageParser.Provider p = entry.getValue();
21604                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21605                        continue;
21606                    }
21607                    if (!printedSomething) {
21608                        if (dumpState.onTitlePrinted())
21609                            pw.println();
21610                        pw.println("ContentProvider Authorities:");
21611                        printedSomething = true;
21612                    }
21613                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21614                    pw.print("    "); pw.println(p.toString());
21615                    if (p.info != null && p.info.applicationInfo != null) {
21616                        final String appInfo = p.info.applicationInfo.toString();
21617                        pw.print("      applicationInfo="); pw.println(appInfo);
21618                    }
21619                }
21620            }
21621
21622            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21623                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21624            }
21625
21626            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21627                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21628            }
21629
21630            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21631                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21632            }
21633
21634            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21635                if (dumpState.onTitlePrinted()) pw.println();
21636                pw.println("Package Changes:");
21637                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21638                final int K = mChangedPackages.size();
21639                for (int i = 0; i < K; i++) {
21640                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21641                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21642                    final int N = changes.size();
21643                    if (N == 0) {
21644                        pw.print("    "); pw.println("No packages changed");
21645                    } else {
21646                        for (int j = 0; j < N; j++) {
21647                            final String pkgName = changes.valueAt(j);
21648                            final int sequenceNumber = changes.keyAt(j);
21649                            pw.print("    ");
21650                            pw.print("seq=");
21651                            pw.print(sequenceNumber);
21652                            pw.print(", package=");
21653                            pw.println(pkgName);
21654                        }
21655                    }
21656                }
21657            }
21658
21659            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21660                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21661            }
21662
21663            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21664                // XXX should handle packageName != null by dumping only install data that
21665                // the given package is involved with.
21666                if (dumpState.onTitlePrinted()) pw.println();
21667
21668                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21669                ipw.println();
21670                ipw.println("Frozen packages:");
21671                ipw.increaseIndent();
21672                if (mFrozenPackages.size() == 0) {
21673                    ipw.println("(none)");
21674                } else {
21675                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21676                        ipw.println(mFrozenPackages.valueAt(i));
21677                    }
21678                }
21679                ipw.decreaseIndent();
21680            }
21681
21682            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21683                if (dumpState.onTitlePrinted()) pw.println();
21684
21685                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21686                ipw.println();
21687                ipw.println("Loaded volumes:");
21688                ipw.increaseIndent();
21689                if (mLoadedVolumes.size() == 0) {
21690                    ipw.println("(none)");
21691                } else {
21692                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21693                        ipw.println(mLoadedVolumes.valueAt(i));
21694                    }
21695                }
21696                ipw.decreaseIndent();
21697            }
21698
21699            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21700                    && packageName == null) {
21701                if (dumpState.onTitlePrinted()) pw.println();
21702                pw.println("Service permissions:");
21703
21704                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21705                while (filterIterator.hasNext()) {
21706                    final ServiceIntentInfo info = filterIterator.next();
21707                    final ServiceInfo serviceInfo = info.service.info;
21708                    final String permission = serviceInfo.permission;
21709                    if (permission != null) {
21710                        pw.print("    ");
21711                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21712                        pw.print(": ");
21713                        pw.println(permission);
21714                    }
21715                }
21716            }
21717
21718            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21719                if (dumpState.onTitlePrinted()) pw.println();
21720                dumpDexoptStateLPr(pw, packageName);
21721            }
21722
21723            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21724                if (dumpState.onTitlePrinted()) pw.println();
21725                dumpCompilerStatsLPr(pw, packageName);
21726            }
21727
21728            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21729                if (dumpState.onTitlePrinted()) pw.println();
21730                mSettings.dumpReadMessagesLPr(pw, dumpState);
21731
21732                pw.println();
21733                pw.println("Package warning messages:");
21734                dumpCriticalInfo(pw, null);
21735            }
21736
21737            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21738                dumpCriticalInfo(pw, "msg,");
21739            }
21740        }
21741
21742        // PackageInstaller should be called outside of mPackages lock
21743        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21744            // XXX should handle packageName != null by dumping only install data that
21745            // the given package is involved with.
21746            if (dumpState.onTitlePrinted()) pw.println();
21747            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21748        }
21749    }
21750
21751    private void dumpProto(FileDescriptor fd) {
21752        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21753
21754        synchronized (mPackages) {
21755            final long requiredVerifierPackageToken =
21756                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21757            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21758            proto.write(
21759                    PackageServiceDumpProto.PackageShortProto.UID,
21760                    getPackageUid(
21761                            mRequiredVerifierPackage,
21762                            MATCH_DEBUG_TRIAGED_MISSING,
21763                            UserHandle.USER_SYSTEM));
21764            proto.end(requiredVerifierPackageToken);
21765
21766            if (mIntentFilterVerifierComponent != null) {
21767                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21768                final long verifierPackageToken =
21769                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21770                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21771                proto.write(
21772                        PackageServiceDumpProto.PackageShortProto.UID,
21773                        getPackageUid(
21774                                verifierPackageName,
21775                                MATCH_DEBUG_TRIAGED_MISSING,
21776                                UserHandle.USER_SYSTEM));
21777                proto.end(verifierPackageToken);
21778            }
21779
21780            dumpSharedLibrariesProto(proto);
21781            dumpFeaturesProto(proto);
21782            mSettings.dumpPackagesProto(proto);
21783            mSettings.dumpSharedUsersProto(proto);
21784            dumpCriticalInfo(proto);
21785        }
21786        proto.flush();
21787    }
21788
21789    private void dumpFeaturesProto(ProtoOutputStream proto) {
21790        synchronized (mAvailableFeatures) {
21791            final int count = mAvailableFeatures.size();
21792            for (int i = 0; i < count; i++) {
21793                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21794            }
21795        }
21796    }
21797
21798    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21799        final int count = mSharedLibraries.size();
21800        for (int i = 0; i < count; i++) {
21801            final String libName = mSharedLibraries.keyAt(i);
21802            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21803            if (versionedLib == null) {
21804                continue;
21805            }
21806            final int versionCount = versionedLib.size();
21807            for (int j = 0; j < versionCount; j++) {
21808                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21809                final long sharedLibraryToken =
21810                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21811                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21812                final boolean isJar = (libEntry.path != null);
21813                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21814                if (isJar) {
21815                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21816                } else {
21817                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21818                }
21819                proto.end(sharedLibraryToken);
21820            }
21821        }
21822    }
21823
21824    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21825        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21826        ipw.println();
21827        ipw.println("Dexopt state:");
21828        ipw.increaseIndent();
21829        Collection<PackageParser.Package> packages = null;
21830        if (packageName != null) {
21831            PackageParser.Package targetPackage = mPackages.get(packageName);
21832            if (targetPackage != null) {
21833                packages = Collections.singletonList(targetPackage);
21834            } else {
21835                ipw.println("Unable to find package: " + packageName);
21836                return;
21837            }
21838        } else {
21839            packages = mPackages.values();
21840        }
21841
21842        for (PackageParser.Package pkg : packages) {
21843            ipw.println("[" + pkg.packageName + "]");
21844            ipw.increaseIndent();
21845            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21846                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21847            ipw.decreaseIndent();
21848        }
21849    }
21850
21851    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21852        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21853        ipw.println();
21854        ipw.println("Compiler stats:");
21855        ipw.increaseIndent();
21856        Collection<PackageParser.Package> packages = null;
21857        if (packageName != null) {
21858            PackageParser.Package targetPackage = mPackages.get(packageName);
21859            if (targetPackage != null) {
21860                packages = Collections.singletonList(targetPackage);
21861            } else {
21862                ipw.println("Unable to find package: " + packageName);
21863                return;
21864            }
21865        } else {
21866            packages = mPackages.values();
21867        }
21868
21869        for (PackageParser.Package pkg : packages) {
21870            ipw.println("[" + pkg.packageName + "]");
21871            ipw.increaseIndent();
21872
21873            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21874            if (stats == null) {
21875                ipw.println("(No recorded stats)");
21876            } else {
21877                stats.dump(ipw);
21878            }
21879            ipw.decreaseIndent();
21880        }
21881    }
21882
21883    private String dumpDomainString(String packageName) {
21884        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21885                .getList();
21886        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21887
21888        ArraySet<String> result = new ArraySet<>();
21889        if (iviList.size() > 0) {
21890            for (IntentFilterVerificationInfo ivi : iviList) {
21891                for (String host : ivi.getDomains()) {
21892                    result.add(host);
21893                }
21894            }
21895        }
21896        if (filters != null && filters.size() > 0) {
21897            for (IntentFilter filter : filters) {
21898                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21899                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21900                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21901                    result.addAll(filter.getHostsList());
21902                }
21903            }
21904        }
21905
21906        StringBuilder sb = new StringBuilder(result.size() * 16);
21907        for (String domain : result) {
21908            if (sb.length() > 0) sb.append(" ");
21909            sb.append(domain);
21910        }
21911        return sb.toString();
21912    }
21913
21914    // ------- apps on sdcard specific code -------
21915    static final boolean DEBUG_SD_INSTALL = false;
21916
21917    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21918
21919    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21920
21921    private boolean mMediaMounted = false;
21922
21923    static String getEncryptKey() {
21924        try {
21925            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21926                    SD_ENCRYPTION_KEYSTORE_NAME);
21927            if (sdEncKey == null) {
21928                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21929                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21930                if (sdEncKey == null) {
21931                    Slog.e(TAG, "Failed to create encryption keys");
21932                    return null;
21933                }
21934            }
21935            return sdEncKey;
21936        } catch (NoSuchAlgorithmException nsae) {
21937            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21938            return null;
21939        } catch (IOException ioe) {
21940            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21941            return null;
21942        }
21943    }
21944
21945    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21946            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21947        final int size = infos.size();
21948        final String[] packageNames = new String[size];
21949        final int[] packageUids = new int[size];
21950        for (int i = 0; i < size; i++) {
21951            final ApplicationInfo info = infos.get(i);
21952            packageNames[i] = info.packageName;
21953            packageUids[i] = info.uid;
21954        }
21955        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21956                finishedReceiver);
21957    }
21958
21959    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21960            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21961        sendResourcesChangedBroadcast(mediaStatus, replacing,
21962                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21963    }
21964
21965    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21966            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21967        int size = pkgList.length;
21968        if (size > 0) {
21969            // Send broadcasts here
21970            Bundle extras = new Bundle();
21971            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21972            if (uidArr != null) {
21973                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21974            }
21975            if (replacing) {
21976                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21977            }
21978            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21979                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21980            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
21981        }
21982    }
21983
21984    private void loadPrivatePackages(final VolumeInfo vol) {
21985        mHandler.post(new Runnable() {
21986            @Override
21987            public void run() {
21988                loadPrivatePackagesInner(vol);
21989            }
21990        });
21991    }
21992
21993    private void loadPrivatePackagesInner(VolumeInfo vol) {
21994        final String volumeUuid = vol.fsUuid;
21995        if (TextUtils.isEmpty(volumeUuid)) {
21996            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21997            return;
21998        }
21999
22000        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22001        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22002        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22003
22004        final VersionInfo ver;
22005        final List<PackageSetting> packages;
22006        synchronized (mPackages) {
22007            ver = mSettings.findOrCreateVersion(volumeUuid);
22008            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22009        }
22010
22011        for (PackageSetting ps : packages) {
22012            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22013            synchronized (mInstallLock) {
22014                final PackageParser.Package pkg;
22015                try {
22016                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22017                    loaded.add(pkg.applicationInfo);
22018
22019                } catch (PackageManagerException e) {
22020                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22021                }
22022
22023                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22024                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22025                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22026                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22027                }
22028            }
22029        }
22030
22031        // Reconcile app data for all started/unlocked users
22032        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22033        final UserManager um = mContext.getSystemService(UserManager.class);
22034        UserManagerInternal umInternal = getUserManagerInternal();
22035        for (UserInfo user : um.getUsers()) {
22036            final int flags;
22037            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22038                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22039            } else if (umInternal.isUserRunning(user.id)) {
22040                flags = StorageManager.FLAG_STORAGE_DE;
22041            } else {
22042                continue;
22043            }
22044
22045            try {
22046                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22047                synchronized (mInstallLock) {
22048                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22049                }
22050            } catch (IllegalStateException e) {
22051                // Device was probably ejected, and we'll process that event momentarily
22052                Slog.w(TAG, "Failed to prepare storage: " + e);
22053            }
22054        }
22055
22056        synchronized (mPackages) {
22057            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
22058            if (sdkUpdated) {
22059                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22060                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22061            }
22062            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
22063                    mPermissionCallback);
22064
22065            // Yay, everything is now upgraded
22066            ver.forceCurrent();
22067
22068            mSettings.writeLPr();
22069        }
22070
22071        for (PackageFreezer freezer : freezers) {
22072            freezer.close();
22073        }
22074
22075        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22076        sendResourcesChangedBroadcast(true, false, loaded, null);
22077        mLoadedVolumes.add(vol.getId());
22078    }
22079
22080    private void unloadPrivatePackages(final VolumeInfo vol) {
22081        mHandler.post(new Runnable() {
22082            @Override
22083            public void run() {
22084                unloadPrivatePackagesInner(vol);
22085            }
22086        });
22087    }
22088
22089    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22090        final String volumeUuid = vol.fsUuid;
22091        if (TextUtils.isEmpty(volumeUuid)) {
22092            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22093            return;
22094        }
22095
22096        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22097        synchronized (mInstallLock) {
22098        synchronized (mPackages) {
22099            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22100            for (PackageSetting ps : packages) {
22101                if (ps.pkg == null) continue;
22102
22103                final ApplicationInfo info = ps.pkg.applicationInfo;
22104                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22105                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22106
22107                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22108                        "unloadPrivatePackagesInner")) {
22109                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22110                            false, null)) {
22111                        unloaded.add(info);
22112                    } else {
22113                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22114                    }
22115                }
22116
22117                // Try very hard to release any references to this package
22118                // so we don't risk the system server being killed due to
22119                // open FDs
22120                AttributeCache.instance().removePackage(ps.name);
22121            }
22122
22123            mSettings.writeLPr();
22124        }
22125        }
22126
22127        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22128        sendResourcesChangedBroadcast(false, false, unloaded, null);
22129        mLoadedVolumes.remove(vol.getId());
22130
22131        // Try very hard to release any references to this path so we don't risk
22132        // the system server being killed due to open FDs
22133        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22134
22135        for (int i = 0; i < 3; i++) {
22136            System.gc();
22137            System.runFinalization();
22138        }
22139    }
22140
22141    private void assertPackageKnown(String volumeUuid, String packageName)
22142            throws PackageManagerException {
22143        synchronized (mPackages) {
22144            // Normalize package name to handle renamed packages
22145            packageName = normalizePackageNameLPr(packageName);
22146
22147            final PackageSetting ps = mSettings.mPackages.get(packageName);
22148            if (ps == null) {
22149                throw new PackageManagerException("Package " + packageName + " is unknown");
22150            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22151                throw new PackageManagerException(
22152                        "Package " + packageName + " found on unknown volume " + volumeUuid
22153                                + "; expected volume " + ps.volumeUuid);
22154            }
22155        }
22156    }
22157
22158    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22159            throws PackageManagerException {
22160        synchronized (mPackages) {
22161            // Normalize package name to handle renamed packages
22162            packageName = normalizePackageNameLPr(packageName);
22163
22164            final PackageSetting ps = mSettings.mPackages.get(packageName);
22165            if (ps == null) {
22166                throw new PackageManagerException("Package " + packageName + " is unknown");
22167            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22168                throw new PackageManagerException(
22169                        "Package " + packageName + " found on unknown volume " + volumeUuid
22170                                + "; expected volume " + ps.volumeUuid);
22171            } else if (!ps.getInstalled(userId)) {
22172                throw new PackageManagerException(
22173                        "Package " + packageName + " not installed for user " + userId);
22174            }
22175        }
22176    }
22177
22178    private List<String> collectAbsoluteCodePaths() {
22179        synchronized (mPackages) {
22180            List<String> codePaths = new ArrayList<>();
22181            final int packageCount = mSettings.mPackages.size();
22182            for (int i = 0; i < packageCount; i++) {
22183                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22184                codePaths.add(ps.codePath.getAbsolutePath());
22185            }
22186            return codePaths;
22187        }
22188    }
22189
22190    /**
22191     * Examine all apps present on given mounted volume, and destroy apps that
22192     * aren't expected, either due to uninstallation or reinstallation on
22193     * another volume.
22194     */
22195    private void reconcileApps(String volumeUuid) {
22196        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22197        List<File> filesToDelete = null;
22198
22199        final File[] files = FileUtils.listFilesOrEmpty(
22200                Environment.getDataAppDirectory(volumeUuid));
22201        for (File file : files) {
22202            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22203                    && !PackageInstallerService.isStageName(file.getName());
22204            if (!isPackage) {
22205                // Ignore entries which are not packages
22206                continue;
22207            }
22208
22209            String absolutePath = file.getAbsolutePath();
22210
22211            boolean pathValid = false;
22212            final int absoluteCodePathCount = absoluteCodePaths.size();
22213            for (int i = 0; i < absoluteCodePathCount; i++) {
22214                String absoluteCodePath = absoluteCodePaths.get(i);
22215                if (absolutePath.startsWith(absoluteCodePath)) {
22216                    pathValid = true;
22217                    break;
22218                }
22219            }
22220
22221            if (!pathValid) {
22222                if (filesToDelete == null) {
22223                    filesToDelete = new ArrayList<>();
22224                }
22225                filesToDelete.add(file);
22226            }
22227        }
22228
22229        if (filesToDelete != null) {
22230            final int fileToDeleteCount = filesToDelete.size();
22231            for (int i = 0; i < fileToDeleteCount; i++) {
22232                File fileToDelete = filesToDelete.get(i);
22233                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22234                synchronized (mInstallLock) {
22235                    removeCodePathLI(fileToDelete);
22236                }
22237            }
22238        }
22239    }
22240
22241    /**
22242     * Reconcile all app data for the given user.
22243     * <p>
22244     * Verifies that directories exist and that ownership and labeling is
22245     * correct for all installed apps on all mounted volumes.
22246     */
22247    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22248        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22249        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22250            final String volumeUuid = vol.getFsUuid();
22251            synchronized (mInstallLock) {
22252                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22253            }
22254        }
22255    }
22256
22257    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22258            boolean migrateAppData) {
22259        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22260    }
22261
22262    /**
22263     * Reconcile all app data on given mounted volume.
22264     * <p>
22265     * Destroys app data that isn't expected, either due to uninstallation or
22266     * reinstallation on another volume.
22267     * <p>
22268     * Verifies that directories exist and that ownership and labeling is
22269     * correct for all installed apps.
22270     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22271     */
22272    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22273            boolean migrateAppData, boolean onlyCoreApps) {
22274        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22275                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22276        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22277
22278        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22279        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22280
22281        // First look for stale data that doesn't belong, and check if things
22282        // have changed since we did our last restorecon
22283        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22284            if (StorageManager.isFileEncryptedNativeOrEmulated()
22285                    && !StorageManager.isUserKeyUnlocked(userId)) {
22286                throw new RuntimeException(
22287                        "Yikes, someone asked us to reconcile CE storage while " + userId
22288                                + " was still locked; this would have caused massive data loss!");
22289            }
22290
22291            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22292            for (File file : files) {
22293                final String packageName = file.getName();
22294                try {
22295                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22296                } catch (PackageManagerException e) {
22297                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22298                    try {
22299                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22300                                StorageManager.FLAG_STORAGE_CE, 0);
22301                    } catch (InstallerException e2) {
22302                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22303                    }
22304                }
22305            }
22306        }
22307        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22308            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22309            for (File file : files) {
22310                final String packageName = file.getName();
22311                try {
22312                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22313                } catch (PackageManagerException e) {
22314                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22315                    try {
22316                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22317                                StorageManager.FLAG_STORAGE_DE, 0);
22318                    } catch (InstallerException e2) {
22319                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22320                    }
22321                }
22322            }
22323        }
22324
22325        // Ensure that data directories are ready to roll for all packages
22326        // installed for this volume and user
22327        final List<PackageSetting> packages;
22328        synchronized (mPackages) {
22329            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22330        }
22331        int preparedCount = 0;
22332        for (PackageSetting ps : packages) {
22333            final String packageName = ps.name;
22334            if (ps.pkg == null) {
22335                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22336                // TODO: might be due to legacy ASEC apps; we should circle back
22337                // and reconcile again once they're scanned
22338                continue;
22339            }
22340            // Skip non-core apps if requested
22341            if (onlyCoreApps && !ps.pkg.coreApp) {
22342                result.add(packageName);
22343                continue;
22344            }
22345
22346            if (ps.getInstalled(userId)) {
22347                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22348                preparedCount++;
22349            }
22350        }
22351
22352        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22353        return result;
22354    }
22355
22356    /**
22357     * Prepare app data for the given app just after it was installed or
22358     * upgraded. This method carefully only touches users that it's installed
22359     * for, and it forces a restorecon to handle any seinfo changes.
22360     * <p>
22361     * Verifies that directories exist and that ownership and labeling is
22362     * correct for all installed apps. If there is an ownership mismatch, it
22363     * will try recovering system apps by wiping data; third-party app data is
22364     * left intact.
22365     * <p>
22366     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22367     */
22368    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22369        final PackageSetting ps;
22370        synchronized (mPackages) {
22371            ps = mSettings.mPackages.get(pkg.packageName);
22372            mSettings.writeKernelMappingLPr(ps);
22373        }
22374
22375        final UserManager um = mContext.getSystemService(UserManager.class);
22376        UserManagerInternal umInternal = getUserManagerInternal();
22377        for (UserInfo user : um.getUsers()) {
22378            final int flags;
22379            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22380                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22381            } else if (umInternal.isUserRunning(user.id)) {
22382                flags = StorageManager.FLAG_STORAGE_DE;
22383            } else {
22384                continue;
22385            }
22386
22387            if (ps.getInstalled(user.id)) {
22388                // TODO: when user data is locked, mark that we're still dirty
22389                prepareAppDataLIF(pkg, user.id, flags);
22390            }
22391        }
22392    }
22393
22394    /**
22395     * Prepare app data for the given app.
22396     * <p>
22397     * Verifies that directories exist and that ownership and labeling is
22398     * correct for all installed apps. If there is an ownership mismatch, this
22399     * will try recovering system apps by wiping data; third-party app data is
22400     * left intact.
22401     */
22402    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22403        if (pkg == null) {
22404            Slog.wtf(TAG, "Package was null!", new Throwable());
22405            return;
22406        }
22407        prepareAppDataLeafLIF(pkg, userId, flags);
22408        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22409        for (int i = 0; i < childCount; i++) {
22410            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22411        }
22412    }
22413
22414    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22415            boolean maybeMigrateAppData) {
22416        prepareAppDataLIF(pkg, userId, flags);
22417
22418        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22419            // We may have just shuffled around app data directories, so
22420            // prepare them one more time
22421            prepareAppDataLIF(pkg, userId, flags);
22422        }
22423    }
22424
22425    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22426        if (DEBUG_APP_DATA) {
22427            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22428                    + Integer.toHexString(flags));
22429        }
22430
22431        final String volumeUuid = pkg.volumeUuid;
22432        final String packageName = pkg.packageName;
22433        final ApplicationInfo app = pkg.applicationInfo;
22434        final int appId = UserHandle.getAppId(app.uid);
22435
22436        Preconditions.checkNotNull(app.seInfo);
22437
22438        long ceDataInode = -1;
22439        try {
22440            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22441                    appId, app.seInfo, app.targetSdkVersion);
22442        } catch (InstallerException e) {
22443            if (app.isSystemApp()) {
22444                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22445                        + ", but trying to recover: " + e);
22446                destroyAppDataLeafLIF(pkg, userId, flags);
22447                try {
22448                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22449                            appId, app.seInfo, app.targetSdkVersion);
22450                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22451                } catch (InstallerException e2) {
22452                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22453                }
22454            } else {
22455                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22456            }
22457        }
22458        // Prepare the application profiles only for upgrades and first boot (so that we don't
22459        // repeat the same operation at each boot).
22460        // We only have to cover the upgrade and first boot here because for app installs we
22461        // prepare the profiles before invoking dexopt (in installPackageLI).
22462        //
22463        // We also have to cover non system users because we do not call the usual install package
22464        // methods for them.
22465        if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) {
22466            mArtManagerService.prepareAppProfiles(pkg, userId);
22467        }
22468
22469        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22470            // TODO: mark this structure as dirty so we persist it!
22471            synchronized (mPackages) {
22472                final PackageSetting ps = mSettings.mPackages.get(packageName);
22473                if (ps != null) {
22474                    ps.setCeDataInode(ceDataInode, userId);
22475                }
22476            }
22477        }
22478
22479        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22480    }
22481
22482    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22483        if (pkg == null) {
22484            Slog.wtf(TAG, "Package was null!", new Throwable());
22485            return;
22486        }
22487        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22488        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22489        for (int i = 0; i < childCount; i++) {
22490            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22491        }
22492    }
22493
22494    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22495        final String volumeUuid = pkg.volumeUuid;
22496        final String packageName = pkg.packageName;
22497        final ApplicationInfo app = pkg.applicationInfo;
22498
22499        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22500            // Create a native library symlink only if we have native libraries
22501            // and if the native libraries are 32 bit libraries. We do not provide
22502            // this symlink for 64 bit libraries.
22503            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22504                final String nativeLibPath = app.nativeLibraryDir;
22505                try {
22506                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22507                            nativeLibPath, userId);
22508                } catch (InstallerException e) {
22509                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22510                }
22511            }
22512        }
22513    }
22514
22515    /**
22516     * For system apps on non-FBE devices, this method migrates any existing
22517     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22518     * requested by the app.
22519     */
22520    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22521        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22522                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22523            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22524                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22525            try {
22526                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22527                        storageTarget);
22528            } catch (InstallerException e) {
22529                logCriticalInfo(Log.WARN,
22530                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22531            }
22532            return true;
22533        } else {
22534            return false;
22535        }
22536    }
22537
22538    public PackageFreezer freezePackage(String packageName, String killReason) {
22539        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22540    }
22541
22542    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22543        return new PackageFreezer(packageName, userId, killReason);
22544    }
22545
22546    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22547            String killReason) {
22548        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22549    }
22550
22551    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22552            String killReason) {
22553        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22554            return new PackageFreezer();
22555        } else {
22556            return freezePackage(packageName, userId, killReason);
22557        }
22558    }
22559
22560    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22561            String killReason) {
22562        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22563    }
22564
22565    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22566            String killReason) {
22567        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22568            return new PackageFreezer();
22569        } else {
22570            return freezePackage(packageName, userId, killReason);
22571        }
22572    }
22573
22574    /**
22575     * Class that freezes and kills the given package upon creation, and
22576     * unfreezes it upon closing. This is typically used when doing surgery on
22577     * app code/data to prevent the app from running while you're working.
22578     */
22579    private class PackageFreezer implements AutoCloseable {
22580        private final String mPackageName;
22581        private final PackageFreezer[] mChildren;
22582
22583        private final boolean mWeFroze;
22584
22585        private final AtomicBoolean mClosed = new AtomicBoolean();
22586        private final CloseGuard mCloseGuard = CloseGuard.get();
22587
22588        /**
22589         * Create and return a stub freezer that doesn't actually do anything,
22590         * typically used when someone requested
22591         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22592         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22593         */
22594        public PackageFreezer() {
22595            mPackageName = null;
22596            mChildren = null;
22597            mWeFroze = false;
22598            mCloseGuard.open("close");
22599        }
22600
22601        public PackageFreezer(String packageName, int userId, String killReason) {
22602            synchronized (mPackages) {
22603                mPackageName = packageName;
22604                mWeFroze = mFrozenPackages.add(mPackageName);
22605
22606                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22607                if (ps != null) {
22608                    killApplication(ps.name, ps.appId, userId, killReason);
22609                }
22610
22611                final PackageParser.Package p = mPackages.get(packageName);
22612                if (p != null && p.childPackages != null) {
22613                    final int N = p.childPackages.size();
22614                    mChildren = new PackageFreezer[N];
22615                    for (int i = 0; i < N; i++) {
22616                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22617                                userId, killReason);
22618                    }
22619                } else {
22620                    mChildren = null;
22621                }
22622            }
22623            mCloseGuard.open("close");
22624        }
22625
22626        @Override
22627        protected void finalize() throws Throwable {
22628            try {
22629                if (mCloseGuard != null) {
22630                    mCloseGuard.warnIfOpen();
22631                }
22632
22633                close();
22634            } finally {
22635                super.finalize();
22636            }
22637        }
22638
22639        @Override
22640        public void close() {
22641            mCloseGuard.close();
22642            if (mClosed.compareAndSet(false, true)) {
22643                synchronized (mPackages) {
22644                    if (mWeFroze) {
22645                        mFrozenPackages.remove(mPackageName);
22646                    }
22647
22648                    if (mChildren != null) {
22649                        for (PackageFreezer freezer : mChildren) {
22650                            freezer.close();
22651                        }
22652                    }
22653                }
22654            }
22655        }
22656    }
22657
22658    /**
22659     * Verify that given package is currently frozen.
22660     */
22661    private void checkPackageFrozen(String packageName) {
22662        synchronized (mPackages) {
22663            if (!mFrozenPackages.contains(packageName)) {
22664                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22665            }
22666        }
22667    }
22668
22669    @Override
22670    public int movePackage(final String packageName, final String volumeUuid) {
22671        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22672
22673        final int callingUid = Binder.getCallingUid();
22674        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22675        final int moveId = mNextMoveId.getAndIncrement();
22676        mHandler.post(new Runnable() {
22677            @Override
22678            public void run() {
22679                try {
22680                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22681                } catch (PackageManagerException e) {
22682                    Slog.w(TAG, "Failed to move " + packageName, e);
22683                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22684                }
22685            }
22686        });
22687        return moveId;
22688    }
22689
22690    private void movePackageInternal(final String packageName, final String volumeUuid,
22691            final int moveId, final int callingUid, UserHandle user)
22692                    throws PackageManagerException {
22693        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22694        final PackageManager pm = mContext.getPackageManager();
22695
22696        final boolean currentAsec;
22697        final String currentVolumeUuid;
22698        final File codeFile;
22699        final String installerPackageName;
22700        final String packageAbiOverride;
22701        final int appId;
22702        final String seinfo;
22703        final String label;
22704        final int targetSdkVersion;
22705        final PackageFreezer freezer;
22706        final int[] installedUserIds;
22707
22708        // reader
22709        synchronized (mPackages) {
22710            final PackageParser.Package pkg = mPackages.get(packageName);
22711            final PackageSetting ps = mSettings.mPackages.get(packageName);
22712            if (pkg == null
22713                    || ps == null
22714                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22715                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22716            }
22717            if (pkg.applicationInfo.isSystemApp()) {
22718                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22719                        "Cannot move system application");
22720            }
22721
22722            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22723            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22724                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22725            if (isInternalStorage && !allow3rdPartyOnInternal) {
22726                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22727                        "3rd party apps are not allowed on internal storage");
22728            }
22729
22730            if (pkg.applicationInfo.isExternalAsec()) {
22731                currentAsec = true;
22732                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22733            } else if (pkg.applicationInfo.isForwardLocked()) {
22734                currentAsec = true;
22735                currentVolumeUuid = "forward_locked";
22736            } else {
22737                currentAsec = false;
22738                currentVolumeUuid = ps.volumeUuid;
22739
22740                final File probe = new File(pkg.codePath);
22741                final File probeOat = new File(probe, "oat");
22742                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22743                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22744                            "Move only supported for modern cluster style installs");
22745                }
22746            }
22747
22748            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22749                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22750                        "Package already moved to " + volumeUuid);
22751            }
22752            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22753                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22754                        "Device admin cannot be moved");
22755            }
22756
22757            if (mFrozenPackages.contains(packageName)) {
22758                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22759                        "Failed to move already frozen package");
22760            }
22761
22762            codeFile = new File(pkg.codePath);
22763            installerPackageName = ps.installerPackageName;
22764            packageAbiOverride = ps.cpuAbiOverrideString;
22765            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22766            seinfo = pkg.applicationInfo.seInfo;
22767            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22768            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22769            freezer = freezePackage(packageName, "movePackageInternal");
22770            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22771        }
22772
22773        final Bundle extras = new Bundle();
22774        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22775        extras.putString(Intent.EXTRA_TITLE, label);
22776        mMoveCallbacks.notifyCreated(moveId, extras);
22777
22778        int installFlags;
22779        final boolean moveCompleteApp;
22780        final File measurePath;
22781
22782        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22783            installFlags = INSTALL_INTERNAL;
22784            moveCompleteApp = !currentAsec;
22785            measurePath = Environment.getDataAppDirectory(volumeUuid);
22786        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22787            installFlags = INSTALL_EXTERNAL;
22788            moveCompleteApp = false;
22789            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22790        } else {
22791            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22792            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22793                    || !volume.isMountedWritable()) {
22794                freezer.close();
22795                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22796                        "Move location not mounted private volume");
22797            }
22798
22799            Preconditions.checkState(!currentAsec);
22800
22801            installFlags = INSTALL_INTERNAL;
22802            moveCompleteApp = true;
22803            measurePath = Environment.getDataAppDirectory(volumeUuid);
22804        }
22805
22806        // If we're moving app data around, we need all the users unlocked
22807        if (moveCompleteApp) {
22808            for (int userId : installedUserIds) {
22809                if (StorageManager.isFileEncryptedNativeOrEmulated()
22810                        && !StorageManager.isUserKeyUnlocked(userId)) {
22811                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22812                            "User " + userId + " must be unlocked");
22813                }
22814            }
22815        }
22816
22817        final PackageStats stats = new PackageStats(null, -1);
22818        synchronized (mInstaller) {
22819            for (int userId : installedUserIds) {
22820                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22821                    freezer.close();
22822                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22823                            "Failed to measure package size");
22824                }
22825            }
22826        }
22827
22828        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22829                + stats.dataSize);
22830
22831        final long startFreeBytes = measurePath.getUsableSpace();
22832        final long sizeBytes;
22833        if (moveCompleteApp) {
22834            sizeBytes = stats.codeSize + stats.dataSize;
22835        } else {
22836            sizeBytes = stats.codeSize;
22837        }
22838
22839        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22840            freezer.close();
22841            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22842                    "Not enough free space to move");
22843        }
22844
22845        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22846
22847        final CountDownLatch installedLatch = new CountDownLatch(1);
22848        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22849            @Override
22850            public void onUserActionRequired(Intent intent) throws RemoteException {
22851                throw new IllegalStateException();
22852            }
22853
22854            @Override
22855            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22856                    Bundle extras) throws RemoteException {
22857                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22858                        + PackageManager.installStatusToString(returnCode, msg));
22859
22860                installedLatch.countDown();
22861                freezer.close();
22862
22863                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22864                switch (status) {
22865                    case PackageInstaller.STATUS_SUCCESS:
22866                        mMoveCallbacks.notifyStatusChanged(moveId,
22867                                PackageManager.MOVE_SUCCEEDED);
22868                        break;
22869                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22870                        mMoveCallbacks.notifyStatusChanged(moveId,
22871                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22872                        break;
22873                    default:
22874                        mMoveCallbacks.notifyStatusChanged(moveId,
22875                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22876                        break;
22877                }
22878            }
22879        };
22880
22881        final MoveInfo move;
22882        if (moveCompleteApp) {
22883            // Kick off a thread to report progress estimates
22884            new Thread() {
22885                @Override
22886                public void run() {
22887                    while (true) {
22888                        try {
22889                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22890                                break;
22891                            }
22892                        } catch (InterruptedException ignored) {
22893                        }
22894
22895                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22896                        final int progress = 10 + (int) MathUtils.constrain(
22897                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22898                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22899                    }
22900                }
22901            }.start();
22902
22903            final String dataAppName = codeFile.getName();
22904            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22905                    dataAppName, appId, seinfo, targetSdkVersion);
22906        } else {
22907            move = null;
22908        }
22909
22910        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22911
22912        final Message msg = mHandler.obtainMessage(INIT_COPY);
22913        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22914        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22915                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22916                packageAbiOverride, null /*grantedPermissions*/,
22917                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22918        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22919        msg.obj = params;
22920
22921        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22922                System.identityHashCode(msg.obj));
22923        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22924                System.identityHashCode(msg.obj));
22925
22926        mHandler.sendMessage(msg);
22927    }
22928
22929    @Override
22930    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22931        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22932
22933        final int realMoveId = mNextMoveId.getAndIncrement();
22934        final Bundle extras = new Bundle();
22935        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22936        mMoveCallbacks.notifyCreated(realMoveId, extras);
22937
22938        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22939            @Override
22940            public void onCreated(int moveId, Bundle extras) {
22941                // Ignored
22942            }
22943
22944            @Override
22945            public void onStatusChanged(int moveId, int status, long estMillis) {
22946                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22947            }
22948        };
22949
22950        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22951        storage.setPrimaryStorageUuid(volumeUuid, callback);
22952        return realMoveId;
22953    }
22954
22955    @Override
22956    public int getMoveStatus(int moveId) {
22957        mContext.enforceCallingOrSelfPermission(
22958                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22959        return mMoveCallbacks.mLastStatus.get(moveId);
22960    }
22961
22962    @Override
22963    public void registerMoveCallback(IPackageMoveObserver callback) {
22964        mContext.enforceCallingOrSelfPermission(
22965                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22966        mMoveCallbacks.register(callback);
22967    }
22968
22969    @Override
22970    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22971        mContext.enforceCallingOrSelfPermission(
22972                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22973        mMoveCallbacks.unregister(callback);
22974    }
22975
22976    @Override
22977    public boolean setInstallLocation(int loc) {
22978        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22979                null);
22980        if (getInstallLocation() == loc) {
22981            return true;
22982        }
22983        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22984                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22985            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22986                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22987            return true;
22988        }
22989        return false;
22990   }
22991
22992    @Override
22993    public int getInstallLocation() {
22994        // allow instant app access
22995        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22996                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22997                PackageHelper.APP_INSTALL_AUTO);
22998    }
22999
23000    /** Called by UserManagerService */
23001    void cleanUpUser(UserManagerService userManager, int userHandle) {
23002        synchronized (mPackages) {
23003            mDirtyUsers.remove(userHandle);
23004            mUserNeedsBadging.delete(userHandle);
23005            mSettings.removeUserLPw(userHandle);
23006            mPendingBroadcasts.remove(userHandle);
23007            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23008            removeUnusedPackagesLPw(userManager, userHandle);
23009        }
23010    }
23011
23012    /**
23013     * We're removing userHandle and would like to remove any downloaded packages
23014     * that are no longer in use by any other user.
23015     * @param userHandle the user being removed
23016     */
23017    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23018        final boolean DEBUG_CLEAN_APKS = false;
23019        int [] users = userManager.getUserIds();
23020        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23021        while (psit.hasNext()) {
23022            PackageSetting ps = psit.next();
23023            if (ps.pkg == null) {
23024                continue;
23025            }
23026            final String packageName = ps.pkg.packageName;
23027            // Skip over if system app
23028            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23029                continue;
23030            }
23031            if (DEBUG_CLEAN_APKS) {
23032                Slog.i(TAG, "Checking package " + packageName);
23033            }
23034            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23035            if (keep) {
23036                if (DEBUG_CLEAN_APKS) {
23037                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23038                }
23039            } else {
23040                for (int i = 0; i < users.length; i++) {
23041                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23042                        keep = true;
23043                        if (DEBUG_CLEAN_APKS) {
23044                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23045                                    + users[i]);
23046                        }
23047                        break;
23048                    }
23049                }
23050            }
23051            if (!keep) {
23052                if (DEBUG_CLEAN_APKS) {
23053                    Slog.i(TAG, "  Removing package " + packageName);
23054                }
23055                mHandler.post(new Runnable() {
23056                    public void run() {
23057                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23058                                userHandle, 0);
23059                    } //end run
23060                });
23061            }
23062        }
23063    }
23064
23065    /** Called by UserManagerService */
23066    void createNewUser(int userId, String[] disallowedPackages) {
23067        synchronized (mInstallLock) {
23068            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23069        }
23070        synchronized (mPackages) {
23071            scheduleWritePackageRestrictionsLocked(userId);
23072            scheduleWritePackageListLocked(userId);
23073            applyFactoryDefaultBrowserLPw(userId);
23074            primeDomainVerificationsLPw(userId);
23075        }
23076    }
23077
23078    void onNewUserCreated(final int userId) {
23079        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23080        synchronized(mPackages) {
23081            // If permission review for legacy apps is required, we represent
23082            // dagerous permissions for such apps as always granted runtime
23083            // permissions to keep per user flag state whether review is needed.
23084            // Hence, if a new user is added we have to propagate dangerous
23085            // permission grants for these legacy apps.
23086            if (mSettings.mPermissions.mPermissionReviewRequired) {
23087// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
23088                mPermissionManager.updateAllPermissions(
23089                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
23090                        mPermissionCallback);
23091            }
23092        }
23093    }
23094
23095    @Override
23096    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23097        mContext.enforceCallingOrSelfPermission(
23098                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23099                "Only package verification agents can read the verifier device identity");
23100
23101        synchronized (mPackages) {
23102            return mSettings.getVerifierDeviceIdentityLPw();
23103        }
23104    }
23105
23106    @Override
23107    public void setPermissionEnforced(String permission, boolean enforced) {
23108        // TODO: Now that we no longer change GID for storage, this should to away.
23109        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23110                "setPermissionEnforced");
23111        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23112            synchronized (mPackages) {
23113                if (mSettings.mReadExternalStorageEnforced == null
23114                        || mSettings.mReadExternalStorageEnforced != enforced) {
23115                    mSettings.mReadExternalStorageEnforced =
23116                            enforced ? Boolean.TRUE : Boolean.FALSE;
23117                    mSettings.writeLPr();
23118                }
23119            }
23120            // kill any non-foreground processes so we restart them and
23121            // grant/revoke the GID.
23122            final IActivityManager am = ActivityManager.getService();
23123            if (am != null) {
23124                final long token = Binder.clearCallingIdentity();
23125                try {
23126                    am.killProcessesBelowForeground("setPermissionEnforcement");
23127                } catch (RemoteException e) {
23128                } finally {
23129                    Binder.restoreCallingIdentity(token);
23130                }
23131            }
23132        } else {
23133            throw new IllegalArgumentException("No selective enforcement for " + permission);
23134        }
23135    }
23136
23137    @Override
23138    @Deprecated
23139    public boolean isPermissionEnforced(String permission) {
23140        // allow instant applications
23141        return true;
23142    }
23143
23144    @Override
23145    public boolean isStorageLow() {
23146        // allow instant applications
23147        final long token = Binder.clearCallingIdentity();
23148        try {
23149            final DeviceStorageMonitorInternal
23150                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23151            if (dsm != null) {
23152                return dsm.isMemoryLow();
23153            } else {
23154                return false;
23155            }
23156        } finally {
23157            Binder.restoreCallingIdentity(token);
23158        }
23159    }
23160
23161    @Override
23162    public IPackageInstaller getPackageInstaller() {
23163        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23164            return null;
23165        }
23166        return mInstallerService;
23167    }
23168
23169    @Override
23170    public IArtManager getArtManager() {
23171        return mArtManagerService;
23172    }
23173
23174    private boolean userNeedsBadging(int userId) {
23175        int index = mUserNeedsBadging.indexOfKey(userId);
23176        if (index < 0) {
23177            final UserInfo userInfo;
23178            final long token = Binder.clearCallingIdentity();
23179            try {
23180                userInfo = sUserManager.getUserInfo(userId);
23181            } finally {
23182                Binder.restoreCallingIdentity(token);
23183            }
23184            final boolean b;
23185            if (userInfo != null && userInfo.isManagedProfile()) {
23186                b = true;
23187            } else {
23188                b = false;
23189            }
23190            mUserNeedsBadging.put(userId, b);
23191            return b;
23192        }
23193        return mUserNeedsBadging.valueAt(index);
23194    }
23195
23196    @Override
23197    public KeySet getKeySetByAlias(String packageName, String alias) {
23198        if (packageName == null || alias == null) {
23199            return null;
23200        }
23201        synchronized(mPackages) {
23202            final PackageParser.Package pkg = mPackages.get(packageName);
23203            if (pkg == null) {
23204                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23205                throw new IllegalArgumentException("Unknown package: " + packageName);
23206            }
23207            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23208            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23209                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23210                throw new IllegalArgumentException("Unknown package: " + packageName);
23211            }
23212            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23213            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23214        }
23215    }
23216
23217    @Override
23218    public KeySet getSigningKeySet(String packageName) {
23219        if (packageName == null) {
23220            return null;
23221        }
23222        synchronized(mPackages) {
23223            final int callingUid = Binder.getCallingUid();
23224            final int callingUserId = UserHandle.getUserId(callingUid);
23225            final PackageParser.Package pkg = mPackages.get(packageName);
23226            if (pkg == null) {
23227                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23228                throw new IllegalArgumentException("Unknown package: " + packageName);
23229            }
23230            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23231            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23232                // filter and pretend the package doesn't exist
23233                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23234                        + ", uid:" + callingUid);
23235                throw new IllegalArgumentException("Unknown package: " + packageName);
23236            }
23237            if (pkg.applicationInfo.uid != callingUid
23238                    && Process.SYSTEM_UID != callingUid) {
23239                throw new SecurityException("May not access signing KeySet of other apps.");
23240            }
23241            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23242            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23243        }
23244    }
23245
23246    @Override
23247    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23248        final int callingUid = Binder.getCallingUid();
23249        if (getInstantAppPackageName(callingUid) != null) {
23250            return false;
23251        }
23252        if (packageName == null || ks == null) {
23253            return false;
23254        }
23255        synchronized(mPackages) {
23256            final PackageParser.Package pkg = mPackages.get(packageName);
23257            if (pkg == null
23258                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23259                            UserHandle.getUserId(callingUid))) {
23260                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23261                throw new IllegalArgumentException("Unknown package: " + packageName);
23262            }
23263            IBinder ksh = ks.getToken();
23264            if (ksh instanceof KeySetHandle) {
23265                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23266                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23267            }
23268            return false;
23269        }
23270    }
23271
23272    @Override
23273    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23274        final int callingUid = Binder.getCallingUid();
23275        if (getInstantAppPackageName(callingUid) != null) {
23276            return false;
23277        }
23278        if (packageName == null || ks == null) {
23279            return false;
23280        }
23281        synchronized(mPackages) {
23282            final PackageParser.Package pkg = mPackages.get(packageName);
23283            if (pkg == null
23284                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23285                            UserHandle.getUserId(callingUid))) {
23286                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23287                throw new IllegalArgumentException("Unknown package: " + packageName);
23288            }
23289            IBinder ksh = ks.getToken();
23290            if (ksh instanceof KeySetHandle) {
23291                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23292                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23293            }
23294            return false;
23295        }
23296    }
23297
23298    private void deletePackageIfUnusedLPr(final String packageName) {
23299        PackageSetting ps = mSettings.mPackages.get(packageName);
23300        if (ps == null) {
23301            return;
23302        }
23303        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23304            // TODO Implement atomic delete if package is unused
23305            // It is currently possible that the package will be deleted even if it is installed
23306            // after this method returns.
23307            mHandler.post(new Runnable() {
23308                public void run() {
23309                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23310                            0, PackageManager.DELETE_ALL_USERS);
23311                }
23312            });
23313        }
23314    }
23315
23316    /**
23317     * Check and throw if the given before/after packages would be considered a
23318     * downgrade.
23319     */
23320    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23321            throws PackageManagerException {
23322        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23323            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23324                    "Update version code " + after.versionCode + " is older than current "
23325                    + before.getLongVersionCode());
23326        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23327            if (after.baseRevisionCode < before.baseRevisionCode) {
23328                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23329                        "Update base revision code " + after.baseRevisionCode
23330                        + " is older than current " + before.baseRevisionCode);
23331            }
23332
23333            if (!ArrayUtils.isEmpty(after.splitNames)) {
23334                for (int i = 0; i < after.splitNames.length; i++) {
23335                    final String splitName = after.splitNames[i];
23336                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23337                    if (j != -1) {
23338                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23339                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23340                                    "Update split " + splitName + " revision code "
23341                                    + after.splitRevisionCodes[i] + " is older than current "
23342                                    + before.splitRevisionCodes[j]);
23343                        }
23344                    }
23345                }
23346            }
23347        }
23348    }
23349
23350    private static class MoveCallbacks extends Handler {
23351        private static final int MSG_CREATED = 1;
23352        private static final int MSG_STATUS_CHANGED = 2;
23353
23354        private final RemoteCallbackList<IPackageMoveObserver>
23355                mCallbacks = new RemoteCallbackList<>();
23356
23357        private final SparseIntArray mLastStatus = new SparseIntArray();
23358
23359        public MoveCallbacks(Looper looper) {
23360            super(looper);
23361        }
23362
23363        public void register(IPackageMoveObserver callback) {
23364            mCallbacks.register(callback);
23365        }
23366
23367        public void unregister(IPackageMoveObserver callback) {
23368            mCallbacks.unregister(callback);
23369        }
23370
23371        @Override
23372        public void handleMessage(Message msg) {
23373            final SomeArgs args = (SomeArgs) msg.obj;
23374            final int n = mCallbacks.beginBroadcast();
23375            for (int i = 0; i < n; i++) {
23376                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23377                try {
23378                    invokeCallback(callback, msg.what, args);
23379                } catch (RemoteException ignored) {
23380                }
23381            }
23382            mCallbacks.finishBroadcast();
23383            args.recycle();
23384        }
23385
23386        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23387                throws RemoteException {
23388            switch (what) {
23389                case MSG_CREATED: {
23390                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23391                    break;
23392                }
23393                case MSG_STATUS_CHANGED: {
23394                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23395                    break;
23396                }
23397            }
23398        }
23399
23400        private void notifyCreated(int moveId, Bundle extras) {
23401            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23402
23403            final SomeArgs args = SomeArgs.obtain();
23404            args.argi1 = moveId;
23405            args.arg2 = extras;
23406            obtainMessage(MSG_CREATED, args).sendToTarget();
23407        }
23408
23409        private void notifyStatusChanged(int moveId, int status) {
23410            notifyStatusChanged(moveId, status, -1);
23411        }
23412
23413        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23414            Slog.v(TAG, "Move " + moveId + " status " + status);
23415
23416            final SomeArgs args = SomeArgs.obtain();
23417            args.argi1 = moveId;
23418            args.argi2 = status;
23419            args.arg3 = estMillis;
23420            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23421
23422            synchronized (mLastStatus) {
23423                mLastStatus.put(moveId, status);
23424            }
23425        }
23426    }
23427
23428    private final static class OnPermissionChangeListeners extends Handler {
23429        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23430
23431        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23432                new RemoteCallbackList<>();
23433
23434        public OnPermissionChangeListeners(Looper looper) {
23435            super(looper);
23436        }
23437
23438        @Override
23439        public void handleMessage(Message msg) {
23440            switch (msg.what) {
23441                case MSG_ON_PERMISSIONS_CHANGED: {
23442                    final int uid = msg.arg1;
23443                    handleOnPermissionsChanged(uid);
23444                } break;
23445            }
23446        }
23447
23448        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23449            mPermissionListeners.register(listener);
23450
23451        }
23452
23453        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23454            mPermissionListeners.unregister(listener);
23455        }
23456
23457        public void onPermissionsChanged(int uid) {
23458            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23459                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23460            }
23461        }
23462
23463        private void handleOnPermissionsChanged(int uid) {
23464            final int count = mPermissionListeners.beginBroadcast();
23465            try {
23466                for (int i = 0; i < count; i++) {
23467                    IOnPermissionsChangeListener callback = mPermissionListeners
23468                            .getBroadcastItem(i);
23469                    try {
23470                        callback.onPermissionsChanged(uid);
23471                    } catch (RemoteException e) {
23472                        Log.e(TAG, "Permission listener is dead", e);
23473                    }
23474                }
23475            } finally {
23476                mPermissionListeners.finishBroadcast();
23477            }
23478        }
23479    }
23480
23481    private class PackageManagerNative extends IPackageManagerNative.Stub {
23482        @Override
23483        public String[] getNamesForUids(int[] uids) throws RemoteException {
23484            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23485            // massage results so they can be parsed by the native binder
23486            for (int i = results.length - 1; i >= 0; --i) {
23487                if (results[i] == null) {
23488                    results[i] = "";
23489                }
23490            }
23491            return results;
23492        }
23493
23494        // NB: this differentiates between preloads and sideloads
23495        @Override
23496        public String getInstallerForPackage(String packageName) throws RemoteException {
23497            final String installerName = getInstallerPackageName(packageName);
23498            if (!TextUtils.isEmpty(installerName)) {
23499                return installerName;
23500            }
23501            // differentiate between preload and sideload
23502            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23503            ApplicationInfo appInfo = getApplicationInfo(packageName,
23504                                    /*flags*/ 0,
23505                                    /*userId*/ callingUser);
23506            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23507                return "preload";
23508            }
23509            return "";
23510        }
23511
23512        @Override
23513        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23514            try {
23515                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23516                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23517                if (pInfo != null) {
23518                    return pInfo.getLongVersionCode();
23519                }
23520            } catch (Exception e) {
23521            }
23522            return 0;
23523        }
23524    }
23525
23526    private class PackageManagerInternalImpl extends PackageManagerInternal {
23527        @Override
23528        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23529                int flagValues, int userId) {
23530            PackageManagerService.this.updatePermissionFlags(
23531                    permName, packageName, flagMask, flagValues, userId);
23532        }
23533
23534        @Override
23535        public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) {
23536            SigningDetails sd = getSigningDetails(packageName);
23537            if (sd == null) {
23538                return false;
23539            }
23540            return sd.hasSha256Certificate(restoringFromSigHash,
23541                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23542        }
23543
23544        @Override
23545        public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) {
23546            SigningDetails sd = getSigningDetails(packageName);
23547            if (sd == null) {
23548                return false;
23549            }
23550            return sd.hasCertificate(restoringFromSig,
23551                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23552        }
23553
23554        private SigningDetails getSigningDetails(@NonNull String packageName) {
23555            synchronized (mPackages) {
23556                PackageParser.Package p = mPackages.get(packageName);
23557                if (p == null) {
23558                    return null;
23559                }
23560                return p.mSigningDetails;
23561            }
23562        }
23563
23564        @Override
23565        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23566            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23567        }
23568
23569        @Override
23570        public boolean isInstantApp(String packageName, int userId) {
23571            return PackageManagerService.this.isInstantApp(packageName, userId);
23572        }
23573
23574        @Override
23575        public String getInstantAppPackageName(int uid) {
23576            return PackageManagerService.this.getInstantAppPackageName(uid);
23577        }
23578
23579        @Override
23580        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23581            synchronized (mPackages) {
23582                return PackageManagerService.this.filterAppAccessLPr(
23583                        (PackageSetting) pkg.mExtras, callingUid, userId);
23584            }
23585        }
23586
23587        @Override
23588        public PackageParser.Package getPackage(String packageName) {
23589            synchronized (mPackages) {
23590                packageName = resolveInternalPackageNameLPr(
23591                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23592                return mPackages.get(packageName);
23593            }
23594        }
23595
23596        @Override
23597        public PackageList getPackageList(PackageListObserver observer) {
23598            synchronized (mPackages) {
23599                final int N = mPackages.size();
23600                final ArrayList<String> list = new ArrayList<>(N);
23601                for (int i = 0; i < N; i++) {
23602                    list.add(mPackages.keyAt(i));
23603                }
23604                final PackageList packageList = new PackageList(list, observer);
23605                if (observer != null) {
23606                    mPackageListObservers.add(packageList);
23607                }
23608                return packageList;
23609            }
23610        }
23611
23612        @Override
23613        public void removePackageListObserver(PackageListObserver observer) {
23614            synchronized (mPackages) {
23615                mPackageListObservers.remove(observer);
23616            }
23617        }
23618
23619        @Override
23620        public PackageParser.Package getDisabledPackage(String packageName) {
23621            synchronized (mPackages) {
23622                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23623                return (ps != null) ? ps.pkg : null;
23624            }
23625        }
23626
23627        @Override
23628        public String getKnownPackageName(int knownPackage, int userId) {
23629            switch(knownPackage) {
23630                case PackageManagerInternal.PACKAGE_BROWSER:
23631                    return getDefaultBrowserPackageName(userId);
23632                case PackageManagerInternal.PACKAGE_INSTALLER:
23633                    return mRequiredInstallerPackage;
23634                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23635                    return mSetupWizardPackage;
23636                case PackageManagerInternal.PACKAGE_SYSTEM:
23637                    return "android";
23638                case PackageManagerInternal.PACKAGE_VERIFIER:
23639                    return mRequiredVerifierPackage;
23640                case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER:
23641                    return mSystemTextClassifierPackage;
23642            }
23643            return null;
23644        }
23645
23646        @Override
23647        public boolean isResolveActivityComponent(ComponentInfo component) {
23648            return mResolveActivity.packageName.equals(component.packageName)
23649                    && mResolveActivity.name.equals(component.name);
23650        }
23651
23652        @Override
23653        public void setLocationPackagesProvider(PackagesProvider provider) {
23654            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23655        }
23656
23657        @Override
23658        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23659            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23660        }
23661
23662        @Override
23663        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23664            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23665        }
23666
23667        @Override
23668        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23669            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23670        }
23671
23672        @Override
23673        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23674            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23675        }
23676
23677        @Override
23678        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23679            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23680        }
23681
23682        @Override
23683        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23684            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23685        }
23686
23687        @Override
23688        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23689            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23690        }
23691
23692        @Override
23693        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23694            synchronized (mPackages) {
23695                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23696            }
23697            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23698        }
23699
23700        @Override
23701        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23702            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23703                    packageName, userId);
23704        }
23705
23706        @Override
23707        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23708            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23709                    packageName, userId);
23710        }
23711
23712        @Override
23713        public void setKeepUninstalledPackages(final List<String> packageList) {
23714            Preconditions.checkNotNull(packageList);
23715            List<String> removedFromList = null;
23716            synchronized (mPackages) {
23717                if (mKeepUninstalledPackages != null) {
23718                    final int packagesCount = mKeepUninstalledPackages.size();
23719                    for (int i = 0; i < packagesCount; i++) {
23720                        String oldPackage = mKeepUninstalledPackages.get(i);
23721                        if (packageList != null && packageList.contains(oldPackage)) {
23722                            continue;
23723                        }
23724                        if (removedFromList == null) {
23725                            removedFromList = new ArrayList<>();
23726                        }
23727                        removedFromList.add(oldPackage);
23728                    }
23729                }
23730                mKeepUninstalledPackages = new ArrayList<>(packageList);
23731                if (removedFromList != null) {
23732                    final int removedCount = removedFromList.size();
23733                    for (int i = 0; i < removedCount; i++) {
23734                        deletePackageIfUnusedLPr(removedFromList.get(i));
23735                    }
23736                }
23737            }
23738        }
23739
23740        @Override
23741        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23742            synchronized (mPackages) {
23743                return mPermissionManager.isPermissionsReviewRequired(
23744                        mPackages.get(packageName), userId);
23745            }
23746        }
23747
23748        @Override
23749        public PackageInfo getPackageInfo(
23750                String packageName, int flags, int filterCallingUid, int userId) {
23751            return PackageManagerService.this
23752                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23753                            flags, filterCallingUid, userId);
23754        }
23755
23756        @Override
23757        public int getPackageUid(String packageName, int flags, int userId) {
23758            return PackageManagerService.this
23759                    .getPackageUid(packageName, flags, userId);
23760        }
23761
23762        @Override
23763        public ApplicationInfo getApplicationInfo(
23764                String packageName, int flags, int filterCallingUid, int userId) {
23765            return PackageManagerService.this
23766                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23767        }
23768
23769        @Override
23770        public ActivityInfo getActivityInfo(
23771                ComponentName component, int flags, int filterCallingUid, int userId) {
23772            return PackageManagerService.this
23773                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23774        }
23775
23776        @Override
23777        public List<ResolveInfo> queryIntentActivities(
23778                Intent intent, int flags, int filterCallingUid, int userId) {
23779            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23780            return PackageManagerService.this
23781                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23782                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23783        }
23784
23785        @Override
23786        public List<ResolveInfo> queryIntentServices(
23787                Intent intent, int flags, int callingUid, int userId) {
23788            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23789            return PackageManagerService.this
23790                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23791                            false);
23792        }
23793
23794        @Override
23795        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23796                int userId) {
23797            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23798        }
23799
23800        @Override
23801        public ComponentName getDefaultHomeActivity(int userId) {
23802            return PackageManagerService.this.getDefaultHomeActivity(userId);
23803        }
23804
23805        @Override
23806        public void setDeviceAndProfileOwnerPackages(
23807                int deviceOwnerUserId, String deviceOwnerPackage,
23808                SparseArray<String> profileOwnerPackages) {
23809            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23810                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23811        }
23812
23813        @Override
23814        public boolean isPackageDataProtected(int userId, String packageName) {
23815            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23816        }
23817
23818        @Override
23819        public boolean isPackageEphemeral(int userId, String packageName) {
23820            synchronized (mPackages) {
23821                final PackageSetting ps = mSettings.mPackages.get(packageName);
23822                return ps != null ? ps.getInstantApp(userId) : false;
23823            }
23824        }
23825
23826        @Override
23827        public boolean wasPackageEverLaunched(String packageName, int userId) {
23828            synchronized (mPackages) {
23829                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23830            }
23831        }
23832
23833        @Override
23834        public void grantRuntimePermission(String packageName, String permName, int userId,
23835                boolean overridePolicy) {
23836            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23837                    permName, packageName, overridePolicy, getCallingUid(), userId,
23838                    mPermissionCallback);
23839        }
23840
23841        @Override
23842        public void revokeRuntimePermission(String packageName, String permName, int userId,
23843                boolean overridePolicy) {
23844            mPermissionManager.revokeRuntimePermission(
23845                    permName, packageName, overridePolicy, getCallingUid(), userId,
23846                    mPermissionCallback);
23847        }
23848
23849        @Override
23850        public String getNameForUid(int uid) {
23851            return PackageManagerService.this.getNameForUid(uid);
23852        }
23853
23854        @Override
23855        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23856                Intent origIntent, String resolvedType, String callingPackage,
23857                Bundle verificationBundle, int userId) {
23858            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23859                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23860                    userId);
23861        }
23862
23863        @Override
23864        public void grantEphemeralAccess(int userId, Intent intent,
23865                int targetAppId, int ephemeralAppId) {
23866            synchronized (mPackages) {
23867                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23868                        targetAppId, ephemeralAppId);
23869            }
23870        }
23871
23872        @Override
23873        public boolean isInstantAppInstallerComponent(ComponentName component) {
23874            synchronized (mPackages) {
23875                return mInstantAppInstallerActivity != null
23876                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23877            }
23878        }
23879
23880        @Override
23881        public void pruneInstantApps() {
23882            mInstantAppRegistry.pruneInstantApps();
23883        }
23884
23885        @Override
23886        public String getSetupWizardPackageName() {
23887            return mSetupWizardPackage;
23888        }
23889
23890        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23891            if (policy != null) {
23892                mExternalSourcesPolicy = policy;
23893            }
23894        }
23895
23896        @Override
23897        public boolean isPackagePersistent(String packageName) {
23898            synchronized (mPackages) {
23899                PackageParser.Package pkg = mPackages.get(packageName);
23900                return pkg != null
23901                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23902                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23903                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23904                        : false;
23905            }
23906        }
23907
23908        @Override
23909        public boolean isLegacySystemApp(Package pkg) {
23910            synchronized (mPackages) {
23911                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23912                return mPromoteSystemApps
23913                        && ps.isSystem()
23914                        && mExistingSystemPackages.contains(ps.name);
23915            }
23916        }
23917
23918        @Override
23919        public List<PackageInfo> getOverlayPackages(int userId) {
23920            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23921            synchronized (mPackages) {
23922                for (PackageParser.Package p : mPackages.values()) {
23923                    if (p.mOverlayTarget != null) {
23924                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23925                        if (pkg != null) {
23926                            overlayPackages.add(pkg);
23927                        }
23928                    }
23929                }
23930            }
23931            return overlayPackages;
23932        }
23933
23934        @Override
23935        public List<String> getTargetPackageNames(int userId) {
23936            List<String> targetPackages = new ArrayList<>();
23937            synchronized (mPackages) {
23938                for (PackageParser.Package p : mPackages.values()) {
23939                    if (p.mOverlayTarget == null) {
23940                        targetPackages.add(p.packageName);
23941                    }
23942                }
23943            }
23944            return targetPackages;
23945        }
23946
23947        @Override
23948        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23949                @Nullable List<String> overlayPackageNames) {
23950            synchronized (mPackages) {
23951                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23952                    Slog.e(TAG, "failed to find package " + targetPackageName);
23953                    return false;
23954                }
23955                ArrayList<String> overlayPaths = null;
23956                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23957                    final int N = overlayPackageNames.size();
23958                    overlayPaths = new ArrayList<>(N);
23959                    for (int i = 0; i < N; i++) {
23960                        final String packageName = overlayPackageNames.get(i);
23961                        final PackageParser.Package pkg = mPackages.get(packageName);
23962                        if (pkg == null) {
23963                            Slog.e(TAG, "failed to find package " + packageName);
23964                            return false;
23965                        }
23966                        overlayPaths.add(pkg.baseCodePath);
23967                    }
23968                }
23969
23970                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23971                ps.setOverlayPaths(overlayPaths, userId);
23972                return true;
23973            }
23974        }
23975
23976        @Override
23977        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23978                int flags, int userId, boolean resolveForStart) {
23979            return resolveIntentInternal(
23980                    intent, resolvedType, flags, userId, resolveForStart);
23981        }
23982
23983        @Override
23984        public ResolveInfo resolveService(Intent intent, String resolvedType,
23985                int flags, int userId, int callingUid) {
23986            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23987        }
23988
23989        @Override
23990        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23991            return PackageManagerService.this.resolveContentProviderInternal(
23992                    name, flags, userId);
23993        }
23994
23995        @Override
23996        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23997            synchronized (mPackages) {
23998                mIsolatedOwners.put(isolatedUid, ownerUid);
23999            }
24000        }
24001
24002        @Override
24003        public void removeIsolatedUid(int isolatedUid) {
24004            synchronized (mPackages) {
24005                mIsolatedOwners.delete(isolatedUid);
24006            }
24007        }
24008
24009        @Override
24010        public int getUidTargetSdkVersion(int uid) {
24011            synchronized (mPackages) {
24012                return getUidTargetSdkVersionLockedLPr(uid);
24013            }
24014        }
24015
24016        @Override
24017        public int getPackageTargetSdkVersion(String packageName) {
24018            synchronized (mPackages) {
24019                return getPackageTargetSdkVersionLockedLPr(packageName);
24020            }
24021        }
24022
24023        @Override
24024        public boolean canAccessInstantApps(int callingUid, int userId) {
24025            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24026        }
24027
24028        @Override
24029        public boolean canAccessComponent(int callingUid, ComponentName component, int userId) {
24030            synchronized (mPackages) {
24031                final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
24032                return !PackageManagerService.this.filterAppAccessLPr(
24033                        ps, callingUid, component, TYPE_UNKNOWN, userId);
24034            }
24035        }
24036
24037        @Override
24038        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
24039            synchronized (mPackages) {
24040                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
24041            }
24042        }
24043
24044        @Override
24045        public void notifyPackageUse(String packageName, int reason) {
24046            synchronized (mPackages) {
24047                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
24048            }
24049        }
24050    }
24051
24052    @Override
24053    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24054        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24055        synchronized (mPackages) {
24056            final long identity = Binder.clearCallingIdentity();
24057            try {
24058                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
24059                        packageNames, userId);
24060            } finally {
24061                Binder.restoreCallingIdentity(identity);
24062            }
24063        }
24064    }
24065
24066    @Override
24067    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24068        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24069        synchronized (mPackages) {
24070            final long identity = Binder.clearCallingIdentity();
24071            try {
24072                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
24073                        packageNames, userId);
24074            } finally {
24075                Binder.restoreCallingIdentity(identity);
24076            }
24077        }
24078    }
24079
24080    @Override
24081    public void grantDefaultPermissionsToEnabledTelephonyDataServices(
24082            String[] packageNames, int userId) {
24083        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledTelephonyDataServices");
24084        synchronized (mPackages) {
24085            Binder.withCleanCallingIdentity( () -> {
24086                mDefaultPermissionPolicy.
24087                        grantDefaultPermissionsToEnabledTelephonyDataServices(
24088                                packageNames, userId);
24089            });
24090        }
24091    }
24092
24093    @Override
24094    public void revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24095            String[] packageNames, int userId) {
24096        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromDisabledTelephonyDataServices");
24097        synchronized (mPackages) {
24098            Binder.withCleanCallingIdentity( () -> {
24099                mDefaultPermissionPolicy.
24100                        revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24101                                packageNames, userId);
24102            });
24103        }
24104    }
24105
24106    @Override
24107    public void grantDefaultPermissionsToActiveLuiApp(String packageName, int userId) {
24108        enforceSystemOrPhoneCaller("grantDefaultPermissionsToActiveLuiApp");
24109        synchronized (mPackages) {
24110            final long identity = Binder.clearCallingIdentity();
24111            try {
24112                mDefaultPermissionPolicy.grantDefaultPermissionsToActiveLuiApp(
24113                        packageName, userId);
24114            } finally {
24115                Binder.restoreCallingIdentity(identity);
24116            }
24117        }
24118    }
24119
24120    @Override
24121    public void revokeDefaultPermissionsFromLuiApps(String[] packageNames, int userId) {
24122        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromLuiApps");
24123        synchronized (mPackages) {
24124            final long identity = Binder.clearCallingIdentity();
24125            try {
24126                mDefaultPermissionPolicy.revokeDefaultPermissionsFromLuiApps(packageNames, userId);
24127            } finally {
24128                Binder.restoreCallingIdentity(identity);
24129            }
24130        }
24131    }
24132
24133    private static void enforceSystemOrPhoneCaller(String tag) {
24134        int callingUid = Binder.getCallingUid();
24135        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24136            throw new SecurityException(
24137                    "Cannot call " + tag + " from UID " + callingUid);
24138        }
24139    }
24140
24141    boolean isHistoricalPackageUsageAvailable() {
24142        return mPackageUsage.isHistoricalPackageUsageAvailable();
24143    }
24144
24145    /**
24146     * Return a <b>copy</b> of the collection of packages known to the package manager.
24147     * @return A copy of the values of mPackages.
24148     */
24149    Collection<PackageParser.Package> getPackages() {
24150        synchronized (mPackages) {
24151            return new ArrayList<>(mPackages.values());
24152        }
24153    }
24154
24155    /**
24156     * Logs process start information (including base APK hash) to the security log.
24157     * @hide
24158     */
24159    @Override
24160    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24161            String apkFile, int pid) {
24162        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24163            return;
24164        }
24165        if (!SecurityLog.isLoggingEnabled()) {
24166            return;
24167        }
24168        Bundle data = new Bundle();
24169        data.putLong("startTimestamp", System.currentTimeMillis());
24170        data.putString("processName", processName);
24171        data.putInt("uid", uid);
24172        data.putString("seinfo", seinfo);
24173        data.putString("apkFile", apkFile);
24174        data.putInt("pid", pid);
24175        Message msg = mProcessLoggingHandler.obtainMessage(
24176                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24177        msg.setData(data);
24178        mProcessLoggingHandler.sendMessage(msg);
24179    }
24180
24181    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24182        return mCompilerStats.getPackageStats(pkgName);
24183    }
24184
24185    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24186        return getOrCreateCompilerPackageStats(pkg.packageName);
24187    }
24188
24189    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24190        return mCompilerStats.getOrCreatePackageStats(pkgName);
24191    }
24192
24193    public void deleteCompilerPackageStats(String pkgName) {
24194        mCompilerStats.deletePackageStats(pkgName);
24195    }
24196
24197    @Override
24198    public int getInstallReason(String packageName, int userId) {
24199        final int callingUid = Binder.getCallingUid();
24200        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24201                true /* requireFullPermission */, false /* checkShell */,
24202                "get install reason");
24203        synchronized (mPackages) {
24204            final PackageSetting ps = mSettings.mPackages.get(packageName);
24205            if (filterAppAccessLPr(ps, callingUid, userId)) {
24206                return PackageManager.INSTALL_REASON_UNKNOWN;
24207            }
24208            if (ps != null) {
24209                return ps.getInstallReason(userId);
24210            }
24211        }
24212        return PackageManager.INSTALL_REASON_UNKNOWN;
24213    }
24214
24215    @Override
24216    public boolean canRequestPackageInstalls(String packageName, int userId) {
24217        return canRequestPackageInstallsInternal(packageName, 0, userId,
24218                true /* throwIfPermNotDeclared*/);
24219    }
24220
24221    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24222            boolean throwIfPermNotDeclared) {
24223        int callingUid = Binder.getCallingUid();
24224        int uid = getPackageUid(packageName, 0, userId);
24225        if (callingUid != uid && callingUid != Process.ROOT_UID
24226                && callingUid != Process.SYSTEM_UID) {
24227            throw new SecurityException(
24228                    "Caller uid " + callingUid + " does not own package " + packageName);
24229        }
24230        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24231        if (info == null) {
24232            return false;
24233        }
24234        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24235            return false;
24236        }
24237        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24238        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24239        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24240            if (throwIfPermNotDeclared) {
24241                throw new SecurityException("Need to declare " + appOpPermission
24242                        + " to call this api");
24243            } else {
24244                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24245                return false;
24246            }
24247        }
24248        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24249            return false;
24250        }
24251        if (mExternalSourcesPolicy != null) {
24252            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24253            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24254                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24255            }
24256        }
24257        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24258    }
24259
24260    @Override
24261    public ComponentName getInstantAppResolverSettingsComponent() {
24262        return mInstantAppResolverSettingsComponent;
24263    }
24264
24265    @Override
24266    public ComponentName getInstantAppInstallerComponent() {
24267        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24268            return null;
24269        }
24270        return mInstantAppInstallerActivity == null
24271                ? null : mInstantAppInstallerActivity.getComponentName();
24272    }
24273
24274    @Override
24275    public String getInstantAppAndroidId(String packageName, int userId) {
24276        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24277                "getInstantAppAndroidId");
24278        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24279                true /* requireFullPermission */, false /* checkShell */,
24280                "getInstantAppAndroidId");
24281        // Make sure the target is an Instant App.
24282        if (!isInstantApp(packageName, userId)) {
24283            return null;
24284        }
24285        synchronized (mPackages) {
24286            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24287        }
24288    }
24289
24290    boolean canHaveOatDir(String packageName) {
24291        synchronized (mPackages) {
24292            PackageParser.Package p = mPackages.get(packageName);
24293            if (p == null) {
24294                return false;
24295            }
24296            return p.canHaveOatDir();
24297        }
24298    }
24299
24300    private String getOatDir(PackageParser.Package pkg) {
24301        if (!pkg.canHaveOatDir()) {
24302            return null;
24303        }
24304        File codePath = new File(pkg.codePath);
24305        if (codePath.isDirectory()) {
24306            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24307        }
24308        return null;
24309    }
24310
24311    void deleteOatArtifactsOfPackage(String packageName) {
24312        final String[] instructionSets;
24313        final List<String> codePaths;
24314        final String oatDir;
24315        final PackageParser.Package pkg;
24316        synchronized (mPackages) {
24317            pkg = mPackages.get(packageName);
24318        }
24319        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24320        codePaths = pkg.getAllCodePaths();
24321        oatDir = getOatDir(pkg);
24322
24323        for (String codePath : codePaths) {
24324            for (String isa : instructionSets) {
24325                try {
24326                    mInstaller.deleteOdex(codePath, isa, oatDir);
24327                } catch (InstallerException e) {
24328                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24329                }
24330            }
24331        }
24332    }
24333
24334    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24335        Set<String> unusedPackages = new HashSet<>();
24336        long currentTimeInMillis = System.currentTimeMillis();
24337        synchronized (mPackages) {
24338            for (PackageParser.Package pkg : mPackages.values()) {
24339                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24340                if (ps == null) {
24341                    continue;
24342                }
24343                PackageDexUsage.PackageUseInfo packageUseInfo =
24344                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24345                if (PackageManagerServiceUtils
24346                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24347                                downgradeTimeThresholdMillis, packageUseInfo,
24348                                pkg.getLatestPackageUseTimeInMills(),
24349                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24350                    unusedPackages.add(pkg.packageName);
24351                }
24352            }
24353        }
24354        return unusedPackages;
24355    }
24356
24357    @Override
24358    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24359            int userId) {
24360        final int callingUid = Binder.getCallingUid();
24361        final int callingAppId = UserHandle.getAppId(callingUid);
24362
24363        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24364                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24365
24366        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24367                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24368            throw new SecurityException("Caller must have the "
24369                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24370        }
24371
24372        synchronized(mPackages) {
24373            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24374            scheduleWritePackageRestrictionsLocked(userId);
24375        }
24376    }
24377
24378    @Nullable
24379    @Override
24380    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24381        final int callingUid = Binder.getCallingUid();
24382        final int callingAppId = UserHandle.getAppId(callingUid);
24383
24384        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24385                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24386
24387        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24388                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24389            throw new SecurityException("Caller must have the "
24390                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24391        }
24392
24393        synchronized(mPackages) {
24394            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24395        }
24396    }
24397
24398    @Override
24399    public boolean isPackageStateProtected(@NonNull String packageName, @UserIdInt int userId) {
24400        final int callingUid = Binder.getCallingUid();
24401        final int callingAppId = UserHandle.getAppId(callingUid);
24402
24403        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24404                false /*requireFullPermission*/, true /*checkShell*/, "isPackageStateProtected");
24405
24406        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID
24407                && checkUidPermission(MANAGE_DEVICE_ADMINS, callingUid) != PERMISSION_GRANTED) {
24408            throw new SecurityException("Caller must have the "
24409                    + MANAGE_DEVICE_ADMINS + " permission.");
24410        }
24411
24412        return mProtectedPackages.isPackageStateProtected(userId, packageName);
24413    }
24414}
24415
24416interface PackageSender {
24417    /**
24418     * @param userIds User IDs where the action occurred on a full application
24419     * @param instantUserIds User IDs where the action occurred on an instant application
24420     */
24421    void sendPackageBroadcast(final String action, final String pkg,
24422        final Bundle extras, final int flags, final String targetPkg,
24423        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24424    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24425        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24426    void notifyPackageAdded(String packageName);
24427    void notifyPackageRemoved(String packageName);
24428}
24429