PackageManagerService.java revision 313d225cd19885979596cf690103a8d77e19c3dc
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.SET_HARMFUL_APP_WARNINGS;
21import static android.Manifest.permission.INSTALL_PACKAGES;
22import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
23import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
24import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
25import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
26import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
27import static android.content.pm.PackageManager.CERT_INPUT_RAW_X509;
28import static android.content.pm.PackageManager.CERT_INPUT_SHA256;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
31import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
32import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
33import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
34import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
39import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
40import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
41import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
42import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
43import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
44import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
45import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
50import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
51import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
52import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
53import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
54import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
57import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
58import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.isApkFile;
86import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
87import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
88import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
89import static android.system.OsConstants.O_CREAT;
90import static android.system.OsConstants.O_RDWR;
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendInt;
96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
104import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
105import static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
106import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
107import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
108import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
109import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
110import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
111import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
115
116import android.Manifest;
117import android.annotation.IntDef;
118import android.annotation.NonNull;
119import android.annotation.Nullable;
120import android.app.ActivityManager;
121import android.app.ActivityManagerInternal;
122import android.app.AppOpsManager;
123import android.app.IActivityManager;
124import android.app.ResourcesManager;
125import android.app.admin.IDevicePolicyManager;
126import android.app.admin.SecurityLog;
127import android.app.backup.IBackupManager;
128import android.content.BroadcastReceiver;
129import android.content.ComponentName;
130import android.content.ContentResolver;
131import android.content.Context;
132import android.content.IIntentReceiver;
133import android.content.Intent;
134import android.content.IntentFilter;
135import android.content.IntentSender;
136import android.content.IntentSender.SendIntentException;
137import android.content.ServiceConnection;
138import android.content.pm.ActivityInfo;
139import android.content.pm.ApplicationInfo;
140import android.content.pm.AppsQueryHelper;
141import android.content.pm.AuxiliaryResolveInfo;
142import android.content.pm.ChangedPackages;
143import android.content.pm.ComponentInfo;
144import android.content.pm.FallbackCategoryProvider;
145import android.content.pm.FeatureInfo;
146import android.content.pm.IDexModuleRegisterCallback;
147import android.content.pm.IOnPermissionsChangeListener;
148import android.content.pm.IPackageDataObserver;
149import android.content.pm.IPackageDeleteObserver;
150import android.content.pm.IPackageDeleteObserver2;
151import android.content.pm.IPackageInstallObserver2;
152import android.content.pm.IPackageInstaller;
153import android.content.pm.IPackageManager;
154import android.content.pm.IPackageManagerNative;
155import android.content.pm.IPackageMoveObserver;
156import android.content.pm.IPackageStatsObserver;
157import android.content.pm.InstantAppInfo;
158import android.content.pm.InstantAppRequest;
159import android.content.pm.InstantAppResolveInfo;
160import android.content.pm.InstrumentationInfo;
161import android.content.pm.IntentFilterVerificationInfo;
162import android.content.pm.KeySet;
163import android.content.pm.PackageCleanItem;
164import android.content.pm.PackageInfo;
165import android.content.pm.PackageInfoLite;
166import android.content.pm.PackageInstaller;
167import android.content.pm.PackageList;
168import android.content.pm.PackageManager;
169import android.content.pm.PackageManagerInternal;
170import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
171import android.content.pm.PackageManagerInternal.PackageListObserver;
172import android.content.pm.PackageParser;
173import android.content.pm.PackageParser.ActivityIntentInfo;
174import android.content.pm.PackageParser.Package;
175import android.content.pm.PackageParser.PackageLite;
176import android.content.pm.PackageParser.PackageParserException;
177import android.content.pm.PackageParser.ParseFlags;
178import android.content.pm.PackageParser.ServiceIntentInfo;
179import android.content.pm.PackageParser.SigningDetails;
180import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion;
181import android.content.pm.PackageStats;
182import android.content.pm.PackageUserState;
183import android.content.pm.ParceledListSlice;
184import android.content.pm.PermissionGroupInfo;
185import android.content.pm.PermissionInfo;
186import android.content.pm.ProviderInfo;
187import android.content.pm.ResolveInfo;
188import android.content.pm.ServiceInfo;
189import android.content.pm.SharedLibraryInfo;
190import android.content.pm.Signature;
191import android.content.pm.UserInfo;
192import android.content.pm.VerifierDeviceIdentity;
193import android.content.pm.VerifierInfo;
194import android.content.pm.VersionedPackage;
195import android.content.pm.dex.ArtManager;
196import android.content.pm.dex.DexMetadataHelper;
197import android.content.pm.dex.IArtManager;
198import android.content.res.Resources;
199import android.database.ContentObserver;
200import android.graphics.Bitmap;
201import android.hardware.display.DisplayManager;
202import android.net.Uri;
203import android.os.Binder;
204import android.os.Build;
205import android.os.Bundle;
206import android.os.Debug;
207import android.os.Environment;
208import android.os.Environment.UserEnvironment;
209import android.os.FileUtils;
210import android.os.Handler;
211import android.os.IBinder;
212import android.os.Looper;
213import android.os.Message;
214import android.os.Parcel;
215import android.os.ParcelFileDescriptor;
216import android.os.PatternMatcher;
217import android.os.Process;
218import android.os.RemoteCallbackList;
219import android.os.RemoteException;
220import android.os.ResultReceiver;
221import android.os.SELinux;
222import android.os.ServiceManager;
223import android.os.ShellCallback;
224import android.os.SystemClock;
225import android.os.SystemProperties;
226import android.os.Trace;
227import android.os.UserHandle;
228import android.os.UserManager;
229import android.os.UserManagerInternal;
230import android.os.storage.IStorageManager;
231import android.os.storage.StorageEventListener;
232import android.os.storage.StorageManager;
233import android.os.storage.StorageManagerInternal;
234import android.os.storage.VolumeInfo;
235import android.os.storage.VolumeRecord;
236import android.provider.Settings.Global;
237import android.provider.Settings.Secure;
238import android.security.KeyStore;
239import android.security.SystemKeyStore;
240import android.service.pm.PackageServiceDumpProto;
241import android.service.textclassifier.TextClassifierService;
242import android.system.ErrnoException;
243import android.system.Os;
244import android.text.TextUtils;
245import android.text.format.DateUtils;
246import android.util.ArrayMap;
247import android.util.ArraySet;
248import android.util.Base64;
249import android.util.ByteStringUtils;
250import android.util.DisplayMetrics;
251import android.util.EventLog;
252import android.util.ExceptionUtils;
253import android.util.Log;
254import android.util.LogPrinter;
255import android.util.LongSparseArray;
256import android.util.LongSparseLongArray;
257import android.util.MathUtils;
258import android.util.PackageUtils;
259import android.util.Pair;
260import android.util.PrintStreamPrinter;
261import android.util.Slog;
262import android.util.SparseArray;
263import android.util.SparseBooleanArray;
264import android.util.SparseIntArray;
265import android.util.TimingsTraceLog;
266import android.util.Xml;
267import android.util.jar.StrictJarFile;
268import android.util.proto.ProtoOutputStream;
269import android.view.Display;
270
271import com.android.internal.R;
272import com.android.internal.annotations.GuardedBy;
273import com.android.internal.app.IMediaContainerService;
274import com.android.internal.app.ResolverActivity;
275import com.android.internal.content.NativeLibraryHelper;
276import com.android.internal.content.PackageHelper;
277import com.android.internal.logging.MetricsLogger;
278import com.android.internal.os.IParcelFileDescriptorFactory;
279import com.android.internal.os.SomeArgs;
280import com.android.internal.os.Zygote;
281import com.android.internal.telephony.CarrierAppUtils;
282import com.android.internal.util.ArrayUtils;
283import com.android.internal.util.ConcurrentUtils;
284import com.android.internal.util.DumpUtils;
285import com.android.internal.util.FastXmlSerializer;
286import com.android.internal.util.IndentingPrintWriter;
287import com.android.internal.util.Preconditions;
288import com.android.internal.util.XmlUtils;
289import com.android.server.AttributeCache;
290import com.android.server.DeviceIdleController;
291import com.android.server.EventLogTags;
292import com.android.server.FgThread;
293import com.android.server.IntentResolver;
294import com.android.server.LocalServices;
295import com.android.server.LockGuard;
296import com.android.server.ServiceThread;
297import com.android.server.SystemConfig;
298import com.android.server.SystemServerInitThreadPool;
299import com.android.server.Watchdog;
300import com.android.server.net.NetworkPolicyManagerInternal;
301import com.android.server.pm.Installer.InstallerException;
302import com.android.server.pm.Settings.DatabaseVersion;
303import com.android.server.pm.Settings.VersionInfo;
304import com.android.server.pm.dex.ArtManagerService;
305import com.android.server.pm.dex.DexLogger;
306import com.android.server.pm.dex.DexManager;
307import com.android.server.pm.dex.DexoptOptions;
308import com.android.server.pm.dex.PackageDexUsage;
309import com.android.server.pm.permission.BasePermission;
310import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
311import com.android.server.pm.permission.PermissionManagerService;
312import com.android.server.pm.permission.PermissionManagerInternal;
313import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
314import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
315import com.android.server.pm.permission.PermissionsState;
316import com.android.server.pm.permission.PermissionsState.PermissionState;
317import com.android.server.security.VerityUtils;
318import com.android.server.storage.DeviceStorageMonitorInternal;
319
320import dalvik.system.CloseGuard;
321import dalvik.system.VMRuntime;
322
323import libcore.io.IoUtils;
324
325import org.xmlpull.v1.XmlPullParser;
326import org.xmlpull.v1.XmlPullParserException;
327import org.xmlpull.v1.XmlSerializer;
328
329import java.io.BufferedOutputStream;
330import java.io.ByteArrayInputStream;
331import java.io.ByteArrayOutputStream;
332import java.io.File;
333import java.io.FileDescriptor;
334import java.io.FileInputStream;
335import java.io.FileOutputStream;
336import java.io.FilenameFilter;
337import java.io.IOException;
338import java.io.PrintWriter;
339import java.lang.annotation.Retention;
340import java.lang.annotation.RetentionPolicy;
341import java.nio.charset.StandardCharsets;
342import java.security.DigestException;
343import java.security.DigestInputStream;
344import java.security.MessageDigest;
345import java.security.NoSuchAlgorithmException;
346import java.security.PublicKey;
347import java.security.SecureRandom;
348import java.security.cert.CertificateException;
349import java.util.ArrayList;
350import java.util.Arrays;
351import java.util.Collection;
352import java.util.Collections;
353import java.util.Comparator;
354import java.util.HashMap;
355import java.util.HashSet;
356import java.util.Iterator;
357import java.util.LinkedHashSet;
358import java.util.List;
359import java.util.Map;
360import java.util.Objects;
361import java.util.Set;
362import java.util.concurrent.CountDownLatch;
363import java.util.concurrent.Future;
364import java.util.concurrent.TimeUnit;
365import java.util.concurrent.atomic.AtomicBoolean;
366import java.util.concurrent.atomic.AtomicInteger;
367
368/**
369 * Keep track of all those APKs everywhere.
370 * <p>
371 * Internally there are two important locks:
372 * <ul>
373 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
374 * and other related state. It is a fine-grained lock that should only be held
375 * momentarily, as it's one of the most contended locks in the system.
376 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
377 * operations typically involve heavy lifting of application data on disk. Since
378 * {@code installd} is single-threaded, and it's operations can often be slow,
379 * this lock should never be acquired while already holding {@link #mPackages}.
380 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
381 * holding {@link #mInstallLock}.
382 * </ul>
383 * Many internal methods rely on the caller to hold the appropriate locks, and
384 * this contract is expressed through method name suffixes:
385 * <ul>
386 * <li>fooLI(): the caller must hold {@link #mInstallLock}
387 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
388 * being modified must be frozen
389 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
390 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
391 * </ul>
392 * <p>
393 * Because this class is very central to the platform's security; please run all
394 * CTS and unit tests whenever making modifications:
395 *
396 * <pre>
397 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
398 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
399 * </pre>
400 */
401public class PackageManagerService extends IPackageManager.Stub
402        implements PackageSender {
403    static final String TAG = "PackageManager";
404    public static final boolean DEBUG_SETTINGS = false;
405    static final boolean DEBUG_PREFERRED = false;
406    static final boolean DEBUG_UPGRADE = false;
407    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
408    private static final boolean DEBUG_BACKUP = false;
409    public static final boolean DEBUG_INSTALL = false;
410    public static final boolean DEBUG_REMOVE = false;
411    private static final boolean DEBUG_BROADCASTS = false;
412    private static final boolean DEBUG_SHOW_INFO = false;
413    private static final boolean DEBUG_PACKAGE_INFO = false;
414    private static final boolean DEBUG_INTENT_MATCHING = false;
415    public static final boolean DEBUG_PACKAGE_SCANNING = false;
416    private static final boolean DEBUG_VERIFY = false;
417    private static final boolean DEBUG_FILTERS = false;
418    public static final boolean DEBUG_PERMISSIONS = false;
419    private static final boolean DEBUG_SHARED_LIBRARIES = false;
420    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
421
422    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
423    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
424    // user, but by default initialize to this.
425    public static final boolean DEBUG_DEXOPT = false;
426
427    private static final boolean DEBUG_ABI_SELECTION = false;
428    private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
429    private static final boolean DEBUG_TRIAGED_MISSING = false;
430    private static final boolean DEBUG_APP_DATA = false;
431
432    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
433    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
434
435    private static final boolean HIDE_EPHEMERAL_APIS = false;
436
437    private static final boolean ENABLE_FREE_CACHE_V2 =
438            SystemProperties.getBoolean("fw.free_cache_v2", true);
439
440    private static final int RADIO_UID = Process.PHONE_UID;
441    private static final int LOG_UID = Process.LOG_UID;
442    private static final int NFC_UID = Process.NFC_UID;
443    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
444    private static final int SHELL_UID = Process.SHELL_UID;
445    private static final int SE_UID = Process.SE_UID;
446
447    // Suffix used during package installation when copying/moving
448    // package apks to install directory.
449    private static final String INSTALL_PACKAGE_SUFFIX = "-";
450
451    static final int SCAN_NO_DEX = 1<<0;
452    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
453    static final int SCAN_NEW_INSTALL = 1<<2;
454    static final int SCAN_UPDATE_TIME = 1<<3;
455    static final int SCAN_BOOTING = 1<<4;
456    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
457    static final int SCAN_REQUIRE_KNOWN = 1<<7;
458    static final int SCAN_MOVE = 1<<8;
459    static final int SCAN_INITIAL = 1<<9;
460    static final int SCAN_CHECK_ONLY = 1<<10;
461    static final int SCAN_DONT_KILL_APP = 1<<11;
462    static final int SCAN_IGNORE_FROZEN = 1<<12;
463    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
464    static final int SCAN_AS_INSTANT_APP = 1<<14;
465    static final int SCAN_AS_FULL_APP = 1<<15;
466    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
467    static final int SCAN_AS_SYSTEM = 1<<17;
468    static final int SCAN_AS_PRIVILEGED = 1<<18;
469    static final int SCAN_AS_OEM = 1<<19;
470    static final int SCAN_AS_VENDOR = 1<<20;
471    static final int SCAN_AS_PRODUCT = 1<<21;
472
473    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
474            SCAN_NO_DEX,
475            SCAN_UPDATE_SIGNATURE,
476            SCAN_NEW_INSTALL,
477            SCAN_UPDATE_TIME,
478            SCAN_BOOTING,
479            SCAN_DELETE_DATA_ON_FAILURES,
480            SCAN_REQUIRE_KNOWN,
481            SCAN_MOVE,
482            SCAN_INITIAL,
483            SCAN_CHECK_ONLY,
484            SCAN_DONT_KILL_APP,
485            SCAN_IGNORE_FROZEN,
486            SCAN_FIRST_BOOT_OR_UPGRADE,
487            SCAN_AS_INSTANT_APP,
488            SCAN_AS_FULL_APP,
489            SCAN_AS_VIRTUAL_PRELOAD,
490    })
491    @Retention(RetentionPolicy.SOURCE)
492    public @interface ScanFlags {}
493
494    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
495    /** Extension of the compressed packages */
496    public final static String COMPRESSED_EXTENSION = ".gz";
497    /** Suffix of stub packages on the system partition */
498    public final static String STUB_SUFFIX = "-Stub";
499
500    private static final int[] EMPTY_INT_ARRAY = new int[0];
501
502    private static final int TYPE_UNKNOWN = 0;
503    private static final int TYPE_ACTIVITY = 1;
504    private static final int TYPE_RECEIVER = 2;
505    private static final int TYPE_SERVICE = 3;
506    private static final int TYPE_PROVIDER = 4;
507    @IntDef(prefix = { "TYPE_" }, value = {
508            TYPE_UNKNOWN,
509            TYPE_ACTIVITY,
510            TYPE_RECEIVER,
511            TYPE_SERVICE,
512            TYPE_PROVIDER,
513    })
514    @Retention(RetentionPolicy.SOURCE)
515    public @interface ComponentType {}
516
517    /**
518     * Timeout (in milliseconds) after which the watchdog should declare that
519     * our handler thread is wedged.  The usual default for such things is one
520     * minute but we sometimes do very lengthy I/O operations on this thread,
521     * such as installing multi-gigabyte applications, so ours needs to be longer.
522     */
523    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
524
525    /**
526     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
527     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
528     * settings entry if available, otherwise we use the hardcoded default.  If it's been
529     * more than this long since the last fstrim, we force one during the boot sequence.
530     *
531     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
532     * one gets run at the next available charging+idle time.  This final mandatory
533     * no-fstrim check kicks in only of the other scheduling criteria is never met.
534     */
535    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
536
537    /**
538     * Whether verification is enabled by default.
539     */
540    private static final boolean DEFAULT_VERIFY_ENABLE = true;
541
542    /**
543     * The default maximum time to wait for the verification agent to return in
544     * milliseconds.
545     */
546    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
547
548    /**
549     * The default response for package verification timeout.
550     *
551     * This can be either PackageManager.VERIFICATION_ALLOW or
552     * PackageManager.VERIFICATION_REJECT.
553     */
554    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
555
556    public static final String PLATFORM_PACKAGE_NAME = "android";
557
558    public static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
559
560    public static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
561            DEFAULT_CONTAINER_PACKAGE,
562            "com.android.defcontainer.DefaultContainerService");
563
564    private static final String KILL_APP_REASON_GIDS_CHANGED =
565            "permission grant or revoke changed gids";
566
567    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
568            "permissions revoked";
569
570    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
571
572    private static final String PACKAGE_SCHEME = "package";
573
574    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
575
576    private static final String PRODUCT_OVERLAY_DIR = "/product/overlay";
577
578    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
579
580    /** Canonical intent used to identify what counts as a "web browser" app */
581    private static final Intent sBrowserIntent;
582    static {
583        sBrowserIntent = new Intent();
584        sBrowserIntent.setAction(Intent.ACTION_VIEW);
585        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
586        sBrowserIntent.setData(Uri.parse("http:"));
587        sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
588    }
589
590    /**
591     * The set of all protected actions [i.e. those actions for which a high priority
592     * intent filter is disallowed].
593     */
594    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
595    static {
596        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
597        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
598        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
599        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
600    }
601
602    // Compilation reasons.
603    public static final int REASON_UNKNOWN = -1;
604    public static final int REASON_FIRST_BOOT = 0;
605    public static final int REASON_BOOT = 1;
606    public static final int REASON_INSTALL = 2;
607    public static final int REASON_BACKGROUND_DEXOPT = 3;
608    public static final int REASON_AB_OTA = 4;
609    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
610    public static final int REASON_SHARED = 6;
611
612    public static final int REASON_LAST = REASON_SHARED;
613
614    /**
615     * Version number for the package parser cache. Increment this whenever the format or
616     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
617     */
618    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
619
620    /**
621     * Whether the package parser cache is enabled.
622     */
623    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
624
625    /**
626     * Permissions required in order to receive instant application lifecycle broadcasts.
627     */
628    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
629            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
630
631    final ServiceThread mHandlerThread;
632
633    final PackageHandler mHandler;
634
635    private final ProcessLoggingHandler mProcessLoggingHandler;
636
637    /**
638     * Messages for {@link #mHandler} that need to wait for system ready before
639     * being dispatched.
640     */
641    private ArrayList<Message> mPostSystemReadyMessages;
642
643    final int mSdkVersion = Build.VERSION.SDK_INT;
644
645    final Context mContext;
646    final boolean mFactoryTest;
647    final boolean mOnlyCore;
648    final DisplayMetrics mMetrics;
649    final int mDefParseFlags;
650    final String[] mSeparateProcesses;
651    final boolean mIsUpgrade;
652    final boolean mIsPreNUpgrade;
653    final boolean mIsPreNMR1Upgrade;
654
655    // Have we told the Activity Manager to whitelist the default container service by uid yet?
656    @GuardedBy("mPackages")
657    boolean mDefaultContainerWhitelisted = false;
658
659    @GuardedBy("mPackages")
660    private boolean mDexOptDialogShown;
661
662    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
663    // LOCK HELD.  Can be called with mInstallLock held.
664    @GuardedBy("mInstallLock")
665    final Installer mInstaller;
666
667    /** Directory where installed applications are stored */
668    private static final File sAppInstallDir =
669            new File(Environment.getDataDirectory(), "app");
670    /** Directory where installed application's 32-bit native libraries are copied. */
671    private static final File sAppLib32InstallDir =
672            new File(Environment.getDataDirectory(), "app-lib");
673    /** Directory where code and non-resource assets of forward-locked applications are stored */
674    private static final File sDrmAppPrivateInstallDir =
675            new File(Environment.getDataDirectory(), "app-private");
676
677    // ----------------------------------------------------------------
678
679    // Lock for state used when installing and doing other long running
680    // operations.  Methods that must be called with this lock held have
681    // the suffix "LI".
682    final Object mInstallLock = new Object();
683
684    // ----------------------------------------------------------------
685
686    // Keys are String (package name), values are Package.  This also serves
687    // as the lock for the global state.  Methods that must be called with
688    // this lock held have the prefix "LP".
689    @GuardedBy("mPackages")
690    final ArrayMap<String, PackageParser.Package> mPackages =
691            new ArrayMap<String, PackageParser.Package>();
692
693    final ArrayMap<String, Set<String>> mKnownCodebase =
694            new ArrayMap<String, Set<String>>();
695
696    // Keys are isolated uids and values are the uid of the application
697    // that created the isolated proccess.
698    @GuardedBy("mPackages")
699    final SparseIntArray mIsolatedOwners = new SparseIntArray();
700
701    /**
702     * Tracks new system packages [received in an OTA] that we expect to
703     * find updated user-installed versions. Keys are package name, values
704     * are package location.
705     */
706    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
707    /**
708     * Tracks high priority intent filters for protected actions. During boot, certain
709     * filter actions are protected and should never be allowed to have a high priority
710     * intent filter for them. However, there is one, and only one exception -- the
711     * setup wizard. It must be able to define a high priority intent filter for these
712     * actions to ensure there are no escapes from the wizard. We need to delay processing
713     * of these during boot as we need to look at all of the system packages in order
714     * to know which component is the setup wizard.
715     */
716    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
717    /**
718     * Whether or not processing protected filters should be deferred.
719     */
720    private boolean mDeferProtectedFilters = true;
721
722    /**
723     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
724     */
725    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
726    /**
727     * Whether or not system app permissions should be promoted from install to runtime.
728     */
729    boolean mPromoteSystemApps;
730
731    @GuardedBy("mPackages")
732    final Settings mSettings;
733
734    /**
735     * Set of package names that are currently "frozen", which means active
736     * surgery is being done on the code/data for that package. The platform
737     * will refuse to launch frozen packages to avoid race conditions.
738     *
739     * @see PackageFreezer
740     */
741    @GuardedBy("mPackages")
742    final ArraySet<String> mFrozenPackages = new ArraySet<>();
743
744    final ProtectedPackages mProtectedPackages;
745
746    @GuardedBy("mLoadedVolumes")
747    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
748
749    boolean mFirstBoot;
750
751    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
752
753    @GuardedBy("mAvailableFeatures")
754    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
755
756    private final InstantAppRegistry mInstantAppRegistry;
757
758    @GuardedBy("mPackages")
759    int mChangedPackagesSequenceNumber;
760    /**
761     * List of changed [installed, removed or updated] packages.
762     * mapping from user id -> sequence number -> package name
763     */
764    @GuardedBy("mPackages")
765    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
766    /**
767     * The sequence number of the last change to a package.
768     * mapping from user id -> package name -> sequence number
769     */
770    @GuardedBy("mPackages")
771    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
772
773    @GuardedBy("mPackages")
774    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
775
776    class PackageParserCallback implements PackageParser.Callback {
777        @Override public final boolean hasFeature(String feature) {
778            return PackageManagerService.this.hasSystemFeature(feature, 0);
779        }
780
781        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
782                Collection<PackageParser.Package> allPackages, String targetPackageName) {
783            List<PackageParser.Package> overlayPackages = null;
784            for (PackageParser.Package p : allPackages) {
785                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
786                    if (overlayPackages == null) {
787                        overlayPackages = new ArrayList<PackageParser.Package>();
788                    }
789                    overlayPackages.add(p);
790                }
791            }
792            if (overlayPackages != null) {
793                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
794                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
795                        return p1.mOverlayPriority - p2.mOverlayPriority;
796                    }
797                };
798                Collections.sort(overlayPackages, cmp);
799            }
800            return overlayPackages;
801        }
802
803        @GuardedBy("mInstallLock")
804        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
805                String targetPackageName, String targetPath) {
806            if ("android".equals(targetPackageName)) {
807                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
808                // native AssetManager.
809                return null;
810            }
811            List<PackageParser.Package> overlayPackages =
812                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
813            if (overlayPackages == null || overlayPackages.isEmpty()) {
814                return null;
815            }
816            List<String> overlayPathList = null;
817            for (PackageParser.Package overlayPackage : overlayPackages) {
818                if (targetPath == null) {
819                    if (overlayPathList == null) {
820                        overlayPathList = new ArrayList<String>();
821                    }
822                    overlayPathList.add(overlayPackage.baseCodePath);
823                    continue;
824                }
825
826                try {
827                    // Creates idmaps for system to parse correctly the Android manifest of the
828                    // target package.
829                    //
830                    // OverlayManagerService will update each of them with a correct gid from its
831                    // target package app id.
832                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
833                            UserHandle.getSharedAppGid(
834                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
835                    if (overlayPathList == null) {
836                        overlayPathList = new ArrayList<String>();
837                    }
838                    overlayPathList.add(overlayPackage.baseCodePath);
839                } catch (InstallerException e) {
840                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
841                            overlayPackage.baseCodePath);
842                }
843            }
844            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
845        }
846
847        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
848            synchronized (mPackages) {
849                return getStaticOverlayPathsLocked(
850                        mPackages.values(), targetPackageName, targetPath);
851            }
852        }
853
854        @Override public final String[] getOverlayApks(String targetPackageName) {
855            return getStaticOverlayPaths(targetPackageName, null);
856        }
857
858        @Override public final String[] getOverlayPaths(String targetPackageName,
859                String targetPath) {
860            return getStaticOverlayPaths(targetPackageName, targetPath);
861        }
862    }
863
864    class ParallelPackageParserCallback extends PackageParserCallback {
865        List<PackageParser.Package> mOverlayPackages = null;
866
867        void findStaticOverlayPackages() {
868            synchronized (mPackages) {
869                for (PackageParser.Package p : mPackages.values()) {
870                    if (p.mOverlayIsStatic) {
871                        if (mOverlayPackages == null) {
872                            mOverlayPackages = new ArrayList<PackageParser.Package>();
873                        }
874                        mOverlayPackages.add(p);
875                    }
876                }
877            }
878        }
879
880        @Override
881        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
882            // We can trust mOverlayPackages without holding mPackages because package uninstall
883            // can't happen while running parallel parsing.
884            // Moreover holding mPackages on each parsing thread causes dead-lock.
885            return mOverlayPackages == null ? null :
886                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
887        }
888    }
889
890    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
891    final ParallelPackageParserCallback mParallelPackageParserCallback =
892            new ParallelPackageParserCallback();
893
894    public static final class SharedLibraryEntry {
895        public final @Nullable String path;
896        public final @Nullable String apk;
897        public final @NonNull SharedLibraryInfo info;
898
899        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
900                String declaringPackageName, long declaringPackageVersionCode) {
901            path = _path;
902            apk = _apk;
903            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
904                    declaringPackageName, declaringPackageVersionCode), null);
905        }
906    }
907
908    // Currently known shared libraries.
909    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
910    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
911            new ArrayMap<>();
912
913    // All available activities, for your resolving pleasure.
914    final ActivityIntentResolver mActivities =
915            new ActivityIntentResolver();
916
917    // All available receivers, for your resolving pleasure.
918    final ActivityIntentResolver mReceivers =
919            new ActivityIntentResolver();
920
921    // All available services, for your resolving pleasure.
922    final ServiceIntentResolver mServices = new ServiceIntentResolver();
923
924    // All available providers, for your resolving pleasure.
925    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
926
927    // Mapping from provider base names (first directory in content URI codePath)
928    // to the provider information.
929    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
930            new ArrayMap<String, PackageParser.Provider>();
931
932    // Mapping from instrumentation class names to info about them.
933    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
934            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
935
936    // Packages whose data we have transfered into another package, thus
937    // should no longer exist.
938    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
939
940    // Broadcast actions that are only available to the system.
941    @GuardedBy("mProtectedBroadcasts")
942    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
943
944    /** List of packages waiting for verification. */
945    final SparseArray<PackageVerificationState> mPendingVerification
946            = new SparseArray<PackageVerificationState>();
947
948    final PackageInstallerService mInstallerService;
949
950    final ArtManagerService mArtManagerService;
951
952    private final PackageDexOptimizer mPackageDexOptimizer;
953    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
954    // is used by other apps).
955    private final DexManager mDexManager;
956
957    private AtomicInteger mNextMoveId = new AtomicInteger();
958    private final MoveCallbacks mMoveCallbacks;
959
960    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
961
962    // Cache of users who need badging.
963    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
964
965    /** Token for keys in mPendingVerification. */
966    private int mPendingVerificationToken = 0;
967
968    volatile boolean mSystemReady;
969    volatile boolean mSafeMode;
970    volatile boolean mHasSystemUidErrors;
971    private volatile boolean mWebInstantAppsDisabled;
972
973    ApplicationInfo mAndroidApplication;
974    final ActivityInfo mResolveActivity = new ActivityInfo();
975    final ResolveInfo mResolveInfo = new ResolveInfo();
976    ComponentName mResolveComponentName;
977    PackageParser.Package mPlatformPackage;
978    ComponentName mCustomResolverComponentName;
979
980    boolean mResolverReplaced = false;
981
982    private final @Nullable ComponentName mIntentFilterVerifierComponent;
983    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
984
985    private int mIntentFilterVerificationToken = 0;
986
987    /** The service connection to the ephemeral resolver */
988    final InstantAppResolverConnection mInstantAppResolverConnection;
989    /** Component used to show resolver settings for Instant Apps */
990    final ComponentName mInstantAppResolverSettingsComponent;
991
992    /** Activity used to install instant applications */
993    ActivityInfo mInstantAppInstallerActivity;
994    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
995
996    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
997            = new SparseArray<IntentFilterVerificationState>();
998
999    // TODO remove this and go through mPermissonManager directly
1000    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1001    private final PermissionManagerInternal mPermissionManager;
1002
1003    // List of packages names to keep cached, even if they are uninstalled for all users
1004    private List<String> mKeepUninstalledPackages;
1005
1006    private UserManagerInternal mUserManagerInternal;
1007    private ActivityManagerInternal mActivityManagerInternal;
1008
1009    private DeviceIdleController.LocalService mDeviceIdleController;
1010
1011    private File mCacheDir;
1012
1013    private Future<?> mPrepareAppDataFuture;
1014
1015    private static class IFVerificationParams {
1016        PackageParser.Package pkg;
1017        boolean replacing;
1018        int userId;
1019        int verifierUid;
1020
1021        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1022                int _userId, int _verifierUid) {
1023            pkg = _pkg;
1024            replacing = _replacing;
1025            userId = _userId;
1026            replacing = _replacing;
1027            verifierUid = _verifierUid;
1028        }
1029    }
1030
1031    private interface IntentFilterVerifier<T extends IntentFilter> {
1032        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1033                                               T filter, String packageName);
1034        void startVerifications(int userId);
1035        void receiveVerificationResponse(int verificationId);
1036    }
1037
1038    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1039        private Context mContext;
1040        private ComponentName mIntentFilterVerifierComponent;
1041        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1042
1043        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1044            mContext = context;
1045            mIntentFilterVerifierComponent = verifierComponent;
1046        }
1047
1048        private String getDefaultScheme() {
1049            return IntentFilter.SCHEME_HTTPS;
1050        }
1051
1052        @Override
1053        public void startVerifications(int userId) {
1054            // Launch verifications requests
1055            int count = mCurrentIntentFilterVerifications.size();
1056            for (int n=0; n<count; n++) {
1057                int verificationId = mCurrentIntentFilterVerifications.get(n);
1058                final IntentFilterVerificationState ivs =
1059                        mIntentFilterVerificationStates.get(verificationId);
1060
1061                String packageName = ivs.getPackageName();
1062
1063                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1064                final int filterCount = filters.size();
1065                ArraySet<String> domainsSet = new ArraySet<>();
1066                for (int m=0; m<filterCount; m++) {
1067                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1068                    domainsSet.addAll(filter.getHostsList());
1069                }
1070                synchronized (mPackages) {
1071                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1072                            packageName, domainsSet) != null) {
1073                        scheduleWriteSettingsLocked();
1074                    }
1075                }
1076                sendVerificationRequest(verificationId, ivs);
1077            }
1078            mCurrentIntentFilterVerifications.clear();
1079        }
1080
1081        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1082            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1083            verificationIntent.putExtra(
1084                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1085                    verificationId);
1086            verificationIntent.putExtra(
1087                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1088                    getDefaultScheme());
1089            verificationIntent.putExtra(
1090                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1091                    ivs.getHostsString());
1092            verificationIntent.putExtra(
1093                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1094                    ivs.getPackageName());
1095            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1096            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1097
1098            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1099            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1100                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1101                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1102
1103            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1104            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1105                    "Sending IntentFilter verification broadcast");
1106        }
1107
1108        public void receiveVerificationResponse(int verificationId) {
1109            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1110
1111            final boolean verified = ivs.isVerified();
1112
1113            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1114            final int count = filters.size();
1115            if (DEBUG_DOMAIN_VERIFICATION) {
1116                Slog.i(TAG, "Received verification response " + verificationId
1117                        + " for " + count + " filters, verified=" + verified);
1118            }
1119            for (int n=0; n<count; n++) {
1120                PackageParser.ActivityIntentInfo filter = filters.get(n);
1121                filter.setVerified(verified);
1122
1123                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1124                        + " verified with result:" + verified + " and hosts:"
1125                        + ivs.getHostsString());
1126            }
1127
1128            mIntentFilterVerificationStates.remove(verificationId);
1129
1130            final String packageName = ivs.getPackageName();
1131            IntentFilterVerificationInfo ivi = null;
1132
1133            synchronized (mPackages) {
1134                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1135            }
1136            if (ivi == null) {
1137                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1138                        + verificationId + " packageName:" + packageName);
1139                return;
1140            }
1141            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1142                    "Updating IntentFilterVerificationInfo for package " + packageName
1143                            +" verificationId:" + verificationId);
1144
1145            synchronized (mPackages) {
1146                if (verified) {
1147                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1148                } else {
1149                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1150                }
1151                scheduleWriteSettingsLocked();
1152
1153                final int userId = ivs.getUserId();
1154                if (userId != UserHandle.USER_ALL) {
1155                    final int userStatus =
1156                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1157
1158                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1159                    boolean needUpdate = false;
1160
1161                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1162                    // already been set by the User thru the Disambiguation dialog
1163                    switch (userStatus) {
1164                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1165                            if (verified) {
1166                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1167                            } else {
1168                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1169                            }
1170                            needUpdate = true;
1171                            break;
1172
1173                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1174                            if (verified) {
1175                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1176                                needUpdate = true;
1177                            }
1178                            break;
1179
1180                        default:
1181                            // Nothing to do
1182                    }
1183
1184                    if (needUpdate) {
1185                        mSettings.updateIntentFilterVerificationStatusLPw(
1186                                packageName, updatedStatus, userId);
1187                        scheduleWritePackageRestrictionsLocked(userId);
1188                    }
1189                }
1190            }
1191        }
1192
1193        @Override
1194        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1195                    ActivityIntentInfo filter, String packageName) {
1196            if (!hasValidDomains(filter)) {
1197                return false;
1198            }
1199            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1200            if (ivs == null) {
1201                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1202                        packageName);
1203            }
1204            if (DEBUG_DOMAIN_VERIFICATION) {
1205                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1206            }
1207            ivs.addFilter(filter);
1208            return true;
1209        }
1210
1211        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1212                int userId, int verificationId, String packageName) {
1213            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1214                    verifierUid, userId, packageName);
1215            ivs.setPendingState();
1216            synchronized (mPackages) {
1217                mIntentFilterVerificationStates.append(verificationId, ivs);
1218                mCurrentIntentFilterVerifications.add(verificationId);
1219            }
1220            return ivs;
1221        }
1222    }
1223
1224    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1225        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1226                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1227                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1228    }
1229
1230    // Set of pending broadcasts for aggregating enable/disable of components.
1231    static class PendingPackageBroadcasts {
1232        // for each user id, a map of <package name -> components within that package>
1233        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1234
1235        public PendingPackageBroadcasts() {
1236            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1237        }
1238
1239        public ArrayList<String> get(int userId, String packageName) {
1240            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1241            return packages.get(packageName);
1242        }
1243
1244        public void put(int userId, String packageName, ArrayList<String> components) {
1245            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1246            packages.put(packageName, components);
1247        }
1248
1249        public void remove(int userId, String packageName) {
1250            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1251            if (packages != null) {
1252                packages.remove(packageName);
1253            }
1254        }
1255
1256        public void remove(int userId) {
1257            mUidMap.remove(userId);
1258        }
1259
1260        public int userIdCount() {
1261            return mUidMap.size();
1262        }
1263
1264        public int userIdAt(int n) {
1265            return mUidMap.keyAt(n);
1266        }
1267
1268        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1269            return mUidMap.get(userId);
1270        }
1271
1272        public int size() {
1273            // total number of pending broadcast entries across all userIds
1274            int num = 0;
1275            for (int i = 0; i< mUidMap.size(); i++) {
1276                num += mUidMap.valueAt(i).size();
1277            }
1278            return num;
1279        }
1280
1281        public void clear() {
1282            mUidMap.clear();
1283        }
1284
1285        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1286            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1287            if (map == null) {
1288                map = new ArrayMap<String, ArrayList<String>>();
1289                mUidMap.put(userId, map);
1290            }
1291            return map;
1292        }
1293    }
1294    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1295
1296    // Service Connection to remote media container service to copy
1297    // package uri's from external media onto secure containers
1298    // or internal storage.
1299    private IMediaContainerService mContainerService = null;
1300
1301    static final int SEND_PENDING_BROADCAST = 1;
1302    static final int MCS_BOUND = 3;
1303    static final int END_COPY = 4;
1304    static final int INIT_COPY = 5;
1305    static final int MCS_UNBIND = 6;
1306    static final int START_CLEANING_PACKAGE = 7;
1307    static final int FIND_INSTALL_LOC = 8;
1308    static final int POST_INSTALL = 9;
1309    static final int MCS_RECONNECT = 10;
1310    static final int MCS_GIVE_UP = 11;
1311    static final int WRITE_SETTINGS = 13;
1312    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1313    static final int PACKAGE_VERIFIED = 15;
1314    static final int CHECK_PENDING_VERIFICATION = 16;
1315    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1316    static final int INTENT_FILTER_VERIFIED = 18;
1317    static final int WRITE_PACKAGE_LIST = 19;
1318    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1319
1320    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1321
1322    // Delay time in millisecs
1323    static final int BROADCAST_DELAY = 10 * 1000;
1324
1325    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1326            2 * 60 * 60 * 1000L; /* two hours */
1327
1328    static UserManagerService sUserManager;
1329
1330    // Stores a list of users whose package restrictions file needs to be updated
1331    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1332
1333    final private DefaultContainerConnection mDefContainerConn =
1334            new DefaultContainerConnection();
1335    class DefaultContainerConnection implements ServiceConnection {
1336        public void onServiceConnected(ComponentName name, IBinder service) {
1337            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1338            final IMediaContainerService imcs = IMediaContainerService.Stub
1339                    .asInterface(Binder.allowBlocking(service));
1340            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1341        }
1342
1343        public void onServiceDisconnected(ComponentName name) {
1344            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1345        }
1346    }
1347
1348    // Recordkeeping of restore-after-install operations that are currently in flight
1349    // between the Package Manager and the Backup Manager
1350    static class PostInstallData {
1351        public InstallArgs args;
1352        public PackageInstalledInfo res;
1353
1354        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1355            args = _a;
1356            res = _r;
1357        }
1358    }
1359
1360    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1361    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1362
1363    // XML tags for backup/restore of various bits of state
1364    private static final String TAG_PREFERRED_BACKUP = "pa";
1365    private static final String TAG_DEFAULT_APPS = "da";
1366    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1367
1368    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1369    private static final String TAG_ALL_GRANTS = "rt-grants";
1370    private static final String TAG_GRANT = "grant";
1371    private static final String ATTR_PACKAGE_NAME = "pkg";
1372
1373    private static final String TAG_PERMISSION = "perm";
1374    private static final String ATTR_PERMISSION_NAME = "name";
1375    private static final String ATTR_IS_GRANTED = "g";
1376    private static final String ATTR_USER_SET = "set";
1377    private static final String ATTR_USER_FIXED = "fixed";
1378    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1379
1380    // System/policy permission grants are not backed up
1381    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1382            FLAG_PERMISSION_POLICY_FIXED
1383            | FLAG_PERMISSION_SYSTEM_FIXED
1384            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1385
1386    // And we back up these user-adjusted states
1387    private static final int USER_RUNTIME_GRANT_MASK =
1388            FLAG_PERMISSION_USER_SET
1389            | FLAG_PERMISSION_USER_FIXED
1390            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1391
1392    final @Nullable String mRequiredVerifierPackage;
1393    final @NonNull String mRequiredInstallerPackage;
1394    final @NonNull String mRequiredUninstallerPackage;
1395    final @Nullable String mSetupWizardPackage;
1396    final @Nullable String mStorageManagerPackage;
1397    final @Nullable String mSystemTextClassifierPackage;
1398    final @NonNull String mServicesSystemSharedLibraryPackageName;
1399    final @NonNull String mSharedSystemSharedLibraryPackageName;
1400
1401    private final PackageUsage mPackageUsage = new PackageUsage();
1402    private final CompilerStats mCompilerStats = new CompilerStats();
1403
1404    class PackageHandler extends Handler {
1405        private boolean mBound = false;
1406        final ArrayList<HandlerParams> mPendingInstalls =
1407            new ArrayList<HandlerParams>();
1408
1409        private boolean connectToService() {
1410            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1411                    " DefaultContainerService");
1412            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1413            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1414            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1415                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1416                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1417                mBound = true;
1418                return true;
1419            }
1420            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1421            return false;
1422        }
1423
1424        private void disconnectService() {
1425            mContainerService = null;
1426            mBound = false;
1427            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1428            mContext.unbindService(mDefContainerConn);
1429            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1430        }
1431
1432        PackageHandler(Looper looper) {
1433            super(looper);
1434        }
1435
1436        public void handleMessage(Message msg) {
1437            try {
1438                doHandleMessage(msg);
1439            } finally {
1440                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1441            }
1442        }
1443
1444        void doHandleMessage(Message msg) {
1445            switch (msg.what) {
1446                case INIT_COPY: {
1447                    HandlerParams params = (HandlerParams) msg.obj;
1448                    int idx = mPendingInstalls.size();
1449                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1450                    // If a bind was already initiated we dont really
1451                    // need to do anything. The pending install
1452                    // will be processed later on.
1453                    if (!mBound) {
1454                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1455                                System.identityHashCode(mHandler));
1456                        // If this is the only one pending we might
1457                        // have to bind to the service again.
1458                        if (!connectToService()) {
1459                            Slog.e(TAG, "Failed to bind to media container service");
1460                            params.serviceError();
1461                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1462                                    System.identityHashCode(mHandler));
1463                            if (params.traceMethod != null) {
1464                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1465                                        params.traceCookie);
1466                            }
1467                            return;
1468                        } else {
1469                            // Once we bind to the service, the first
1470                            // pending request will be processed.
1471                            mPendingInstalls.add(idx, params);
1472                        }
1473                    } else {
1474                        mPendingInstalls.add(idx, params);
1475                        // Already bound to the service. Just make
1476                        // sure we trigger off processing the first request.
1477                        if (idx == 0) {
1478                            mHandler.sendEmptyMessage(MCS_BOUND);
1479                        }
1480                    }
1481                    break;
1482                }
1483                case MCS_BOUND: {
1484                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1485                    if (msg.obj != null) {
1486                        mContainerService = (IMediaContainerService) msg.obj;
1487                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1488                                System.identityHashCode(mHandler));
1489                    }
1490                    if (mContainerService == null) {
1491                        if (!mBound) {
1492                            // Something seriously wrong since we are not bound and we are not
1493                            // waiting for connection. Bail out.
1494                            Slog.e(TAG, "Cannot bind to media container service");
1495                            for (HandlerParams params : mPendingInstalls) {
1496                                // Indicate service bind error
1497                                params.serviceError();
1498                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1499                                        System.identityHashCode(params));
1500                                if (params.traceMethod != null) {
1501                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1502                                            params.traceMethod, params.traceCookie);
1503                                }
1504                                return;
1505                            }
1506                            mPendingInstalls.clear();
1507                        } else {
1508                            Slog.w(TAG, "Waiting to connect to media container service");
1509                        }
1510                    } else if (mPendingInstalls.size() > 0) {
1511                        HandlerParams params = mPendingInstalls.get(0);
1512                        if (params != null) {
1513                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1514                                    System.identityHashCode(params));
1515                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1516                            if (params.startCopy()) {
1517                                // We are done...  look for more work or to
1518                                // go idle.
1519                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1520                                        "Checking for more work or unbind...");
1521                                // Delete pending install
1522                                if (mPendingInstalls.size() > 0) {
1523                                    mPendingInstalls.remove(0);
1524                                }
1525                                if (mPendingInstalls.size() == 0) {
1526                                    if (mBound) {
1527                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1528                                                "Posting delayed MCS_UNBIND");
1529                                        removeMessages(MCS_UNBIND);
1530                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1531                                        // Unbind after a little delay, to avoid
1532                                        // continual thrashing.
1533                                        sendMessageDelayed(ubmsg, 10000);
1534                                    }
1535                                } else {
1536                                    // There are more pending requests in queue.
1537                                    // Just post MCS_BOUND message to trigger processing
1538                                    // of next pending install.
1539                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1540                                            "Posting MCS_BOUND for next work");
1541                                    mHandler.sendEmptyMessage(MCS_BOUND);
1542                                }
1543                            }
1544                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1545                        }
1546                    } else {
1547                        // Should never happen ideally.
1548                        Slog.w(TAG, "Empty queue");
1549                    }
1550                    break;
1551                }
1552                case MCS_RECONNECT: {
1553                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1554                    if (mPendingInstalls.size() > 0) {
1555                        if (mBound) {
1556                            disconnectService();
1557                        }
1558                        if (!connectToService()) {
1559                            Slog.e(TAG, "Failed to bind to media container service");
1560                            for (HandlerParams params : mPendingInstalls) {
1561                                // Indicate service bind error
1562                                params.serviceError();
1563                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1564                                        System.identityHashCode(params));
1565                            }
1566                            mPendingInstalls.clear();
1567                        }
1568                    }
1569                    break;
1570                }
1571                case MCS_UNBIND: {
1572                    // If there is no actual work left, then time to unbind.
1573                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1574
1575                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1576                        if (mBound) {
1577                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1578
1579                            disconnectService();
1580                        }
1581                    } else if (mPendingInstalls.size() > 0) {
1582                        // There are more pending requests in queue.
1583                        // Just post MCS_BOUND message to trigger processing
1584                        // of next pending install.
1585                        mHandler.sendEmptyMessage(MCS_BOUND);
1586                    }
1587
1588                    break;
1589                }
1590                case MCS_GIVE_UP: {
1591                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1592                    HandlerParams params = mPendingInstalls.remove(0);
1593                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1594                            System.identityHashCode(params));
1595                    break;
1596                }
1597                case SEND_PENDING_BROADCAST: {
1598                    String packages[];
1599                    ArrayList<String> components[];
1600                    int size = 0;
1601                    int uids[];
1602                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1603                    synchronized (mPackages) {
1604                        if (mPendingBroadcasts == null) {
1605                            return;
1606                        }
1607                        size = mPendingBroadcasts.size();
1608                        if (size <= 0) {
1609                            // Nothing to be done. Just return
1610                            return;
1611                        }
1612                        packages = new String[size];
1613                        components = new ArrayList[size];
1614                        uids = new int[size];
1615                        int i = 0;  // filling out the above arrays
1616
1617                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1618                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1619                            Iterator<Map.Entry<String, ArrayList<String>>> it
1620                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1621                                            .entrySet().iterator();
1622                            while (it.hasNext() && i < size) {
1623                                Map.Entry<String, ArrayList<String>> ent = it.next();
1624                                packages[i] = ent.getKey();
1625                                components[i] = ent.getValue();
1626                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1627                                uids[i] = (ps != null)
1628                                        ? UserHandle.getUid(packageUserId, ps.appId)
1629                                        : -1;
1630                                i++;
1631                            }
1632                        }
1633                        size = i;
1634                        mPendingBroadcasts.clear();
1635                    }
1636                    // Send broadcasts
1637                    for (int i = 0; i < size; i++) {
1638                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1639                    }
1640                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1641                    break;
1642                }
1643                case START_CLEANING_PACKAGE: {
1644                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1645                    final String packageName = (String)msg.obj;
1646                    final int userId = msg.arg1;
1647                    final boolean andCode = msg.arg2 != 0;
1648                    synchronized (mPackages) {
1649                        if (userId == UserHandle.USER_ALL) {
1650                            int[] users = sUserManager.getUserIds();
1651                            for (int user : users) {
1652                                mSettings.addPackageToCleanLPw(
1653                                        new PackageCleanItem(user, packageName, andCode));
1654                            }
1655                        } else {
1656                            mSettings.addPackageToCleanLPw(
1657                                    new PackageCleanItem(userId, packageName, andCode));
1658                        }
1659                    }
1660                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1661                    startCleaningPackages();
1662                } break;
1663                case POST_INSTALL: {
1664                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1665
1666                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1667                    final boolean didRestore = (msg.arg2 != 0);
1668                    mRunningInstalls.delete(msg.arg1);
1669
1670                    if (data != null) {
1671                        InstallArgs args = data.args;
1672                        PackageInstalledInfo parentRes = data.res;
1673
1674                        final boolean grantPermissions = (args.installFlags
1675                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1676                        final boolean killApp = (args.installFlags
1677                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1678                        final boolean virtualPreload = ((args.installFlags
1679                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1680                        final String[] grantedPermissions = args.installGrantPermissions;
1681
1682                        // Handle the parent package
1683                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1684                                virtualPreload, grantedPermissions, didRestore,
1685                                args.installerPackageName, args.observer);
1686
1687                        // Handle the child packages
1688                        final int childCount = (parentRes.addedChildPackages != null)
1689                                ? parentRes.addedChildPackages.size() : 0;
1690                        for (int i = 0; i < childCount; i++) {
1691                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1692                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1693                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1694                                    args.installerPackageName, args.observer);
1695                        }
1696
1697                        // Log tracing if needed
1698                        if (args.traceMethod != null) {
1699                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1700                                    args.traceCookie);
1701                        }
1702                    } else {
1703                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1704                    }
1705
1706                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1707                } break;
1708                case WRITE_SETTINGS: {
1709                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1710                    synchronized (mPackages) {
1711                        removeMessages(WRITE_SETTINGS);
1712                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1713                        mSettings.writeLPr();
1714                        mDirtyUsers.clear();
1715                    }
1716                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1717                } break;
1718                case WRITE_PACKAGE_RESTRICTIONS: {
1719                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1720                    synchronized (mPackages) {
1721                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1722                        for (int userId : mDirtyUsers) {
1723                            mSettings.writePackageRestrictionsLPr(userId);
1724                        }
1725                        mDirtyUsers.clear();
1726                    }
1727                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1728                } break;
1729                case WRITE_PACKAGE_LIST: {
1730                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1731                    synchronized (mPackages) {
1732                        removeMessages(WRITE_PACKAGE_LIST);
1733                        mSettings.writePackageListLPr(msg.arg1);
1734                    }
1735                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1736                } break;
1737                case CHECK_PENDING_VERIFICATION: {
1738                    final int verificationId = msg.arg1;
1739                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1740
1741                    if ((state != null) && !state.timeoutExtended()) {
1742                        final InstallArgs args = state.getInstallArgs();
1743                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1744
1745                        Slog.i(TAG, "Verification timed out for " + originUri);
1746                        mPendingVerification.remove(verificationId);
1747
1748                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1749
1750                        final UserHandle user = args.getUser();
1751                        if (getDefaultVerificationResponse(user)
1752                                == PackageManager.VERIFICATION_ALLOW) {
1753                            Slog.i(TAG, "Continuing with installation of " + originUri);
1754                            state.setVerifierResponse(Binder.getCallingUid(),
1755                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1756                            broadcastPackageVerified(verificationId, originUri,
1757                                    PackageManager.VERIFICATION_ALLOW, user);
1758                            try {
1759                                ret = args.copyApk(mContainerService, true);
1760                            } catch (RemoteException e) {
1761                                Slog.e(TAG, "Could not contact the ContainerService");
1762                            }
1763                        } else {
1764                            broadcastPackageVerified(verificationId, originUri,
1765                                    PackageManager.VERIFICATION_REJECT, user);
1766                        }
1767
1768                        Trace.asyncTraceEnd(
1769                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1770
1771                        processPendingInstall(args, ret);
1772                        mHandler.sendEmptyMessage(MCS_UNBIND);
1773                    }
1774                    break;
1775                }
1776                case PACKAGE_VERIFIED: {
1777                    final int verificationId = msg.arg1;
1778
1779                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1780                    if (state == null) {
1781                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1782                        break;
1783                    }
1784
1785                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1786
1787                    state.setVerifierResponse(response.callerUid, response.code);
1788
1789                    if (state.isVerificationComplete()) {
1790                        mPendingVerification.remove(verificationId);
1791
1792                        final InstallArgs args = state.getInstallArgs();
1793                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1794
1795                        int ret;
1796                        if (state.isInstallAllowed()) {
1797                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1798                            broadcastPackageVerified(verificationId, originUri,
1799                                    response.code, state.getInstallArgs().getUser());
1800                            try {
1801                                ret = args.copyApk(mContainerService, true);
1802                            } catch (RemoteException e) {
1803                                Slog.e(TAG, "Could not contact the ContainerService");
1804                            }
1805                        } else {
1806                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1807                        }
1808
1809                        Trace.asyncTraceEnd(
1810                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1811
1812                        processPendingInstall(args, ret);
1813                        mHandler.sendEmptyMessage(MCS_UNBIND);
1814                    }
1815
1816                    break;
1817                }
1818                case START_INTENT_FILTER_VERIFICATIONS: {
1819                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1820                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1821                            params.replacing, params.pkg);
1822                    break;
1823                }
1824                case INTENT_FILTER_VERIFIED: {
1825                    final int verificationId = msg.arg1;
1826
1827                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1828                            verificationId);
1829                    if (state == null) {
1830                        Slog.w(TAG, "Invalid IntentFilter verification token "
1831                                + verificationId + " received");
1832                        break;
1833                    }
1834
1835                    final int userId = state.getUserId();
1836
1837                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1838                            "Processing IntentFilter verification with token:"
1839                            + verificationId + " and userId:" + userId);
1840
1841                    final IntentFilterVerificationResponse response =
1842                            (IntentFilterVerificationResponse) msg.obj;
1843
1844                    state.setVerifierResponse(response.callerUid, response.code);
1845
1846                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1847                            "IntentFilter verification with token:" + verificationId
1848                            + " and userId:" + userId
1849                            + " is settings verifier response with response code:"
1850                            + response.code);
1851
1852                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1853                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1854                                + response.getFailedDomainsString());
1855                    }
1856
1857                    if (state.isVerificationComplete()) {
1858                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1859                    } else {
1860                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1861                                "IntentFilter verification with token:" + verificationId
1862                                + " was not said to be complete");
1863                    }
1864
1865                    break;
1866                }
1867                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1868                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1869                            mInstantAppResolverConnection,
1870                            (InstantAppRequest) msg.obj,
1871                            mInstantAppInstallerActivity,
1872                            mHandler);
1873                }
1874            }
1875        }
1876    }
1877
1878    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1879        @Override
1880        public void onGidsChanged(int appId, int userId) {
1881            mHandler.post(new Runnable() {
1882                @Override
1883                public void run() {
1884                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1885                }
1886            });
1887        }
1888        @Override
1889        public void onPermissionGranted(int uid, int userId) {
1890            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1891
1892            // Not critical; if this is lost, the application has to request again.
1893            synchronized (mPackages) {
1894                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1895            }
1896        }
1897        @Override
1898        public void onInstallPermissionGranted() {
1899            synchronized (mPackages) {
1900                scheduleWriteSettingsLocked();
1901            }
1902        }
1903        @Override
1904        public void onPermissionRevoked(int uid, int userId) {
1905            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1906
1907            synchronized (mPackages) {
1908                // Critical; after this call the application should never have the permission
1909                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1910            }
1911
1912            final int appId = UserHandle.getAppId(uid);
1913            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1914        }
1915        @Override
1916        public void onInstallPermissionRevoked() {
1917            synchronized (mPackages) {
1918                scheduleWriteSettingsLocked();
1919            }
1920        }
1921        @Override
1922        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1923            synchronized (mPackages) {
1924                for (int userId : updatedUserIds) {
1925                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1926                }
1927            }
1928        }
1929        @Override
1930        public void onInstallPermissionUpdated() {
1931            synchronized (mPackages) {
1932                scheduleWriteSettingsLocked();
1933            }
1934        }
1935        @Override
1936        public void onPermissionRemoved() {
1937            synchronized (mPackages) {
1938                mSettings.writeLPr();
1939            }
1940        }
1941    };
1942
1943    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1944            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1945            boolean launchedForRestore, String installerPackage,
1946            IPackageInstallObserver2 installObserver) {
1947        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1948            // Send the removed broadcasts
1949            if (res.removedInfo != null) {
1950                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1951            }
1952
1953            // Now that we successfully installed the package, grant runtime
1954            // permissions if requested before broadcasting the install. Also
1955            // for legacy apps in permission review mode we clear the permission
1956            // review flag which is used to emulate runtime permissions for
1957            // legacy apps.
1958            if (grantPermissions) {
1959                final int callingUid = Binder.getCallingUid();
1960                mPermissionManager.grantRequestedRuntimePermissions(
1961                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1962                        mPermissionCallback);
1963            }
1964
1965            final boolean update = res.removedInfo != null
1966                    && res.removedInfo.removedPackage != null;
1967            final String installerPackageName =
1968                    res.installerPackageName != null
1969                            ? res.installerPackageName
1970                            : res.removedInfo != null
1971                                    ? res.removedInfo.installerPackageName
1972                                    : null;
1973
1974            // If this is the first time we have child packages for a disabled privileged
1975            // app that had no children, we grant requested runtime permissions to the new
1976            // children if the parent on the system image had them already granted.
1977            if (res.pkg.parentPackage != null) {
1978                final int callingUid = Binder.getCallingUid();
1979                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1980                        res.pkg, callingUid, mPermissionCallback);
1981            }
1982
1983            synchronized (mPackages) {
1984                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1985            }
1986
1987            final String packageName = res.pkg.applicationInfo.packageName;
1988
1989            // Determine the set of users who are adding this package for
1990            // the first time vs. those who are seeing an update.
1991            int[] firstUserIds = EMPTY_INT_ARRAY;
1992            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
1993            int[] updateUserIds = EMPTY_INT_ARRAY;
1994            int[] instantUserIds = EMPTY_INT_ARRAY;
1995            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1996            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1997            for (int newUser : res.newUsers) {
1998                final boolean isInstantApp = ps.getInstantApp(newUser);
1999                if (allNewUsers) {
2000                    if (isInstantApp) {
2001                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2002                    } else {
2003                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2004                    }
2005                    continue;
2006                }
2007                boolean isNew = true;
2008                for (int origUser : res.origUsers) {
2009                    if (origUser == newUser) {
2010                        isNew = false;
2011                        break;
2012                    }
2013                }
2014                if (isNew) {
2015                    if (isInstantApp) {
2016                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2017                    } else {
2018                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2019                    }
2020                } else {
2021                    if (isInstantApp) {
2022                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2023                    } else {
2024                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2025                    }
2026                }
2027            }
2028
2029            // Send installed broadcasts if the package is not a static shared lib.
2030            if (res.pkg.staticSharedLibName == null) {
2031                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2032
2033                // Send added for users that see the package for the first time
2034                // sendPackageAddedForNewUsers also deals with system apps
2035                int appId = UserHandle.getAppId(res.uid);
2036                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2037                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2038                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2039
2040                // Send added for users that don't see the package for the first time
2041                Bundle extras = new Bundle(1);
2042                extras.putInt(Intent.EXTRA_UID, res.uid);
2043                if (update) {
2044                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2045                }
2046                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2047                        extras, 0 /*flags*/,
2048                        null /*targetPackage*/, null /*finishedReceiver*/,
2049                        updateUserIds, instantUserIds);
2050                if (installerPackageName != null) {
2051                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2052                            extras, 0 /*flags*/,
2053                            installerPackageName, null /*finishedReceiver*/,
2054                            updateUserIds, instantUserIds);
2055                }
2056
2057                // Send replaced for users that don't see the package for the first time
2058                if (update) {
2059                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2060                            packageName, extras, 0 /*flags*/,
2061                            null /*targetPackage*/, null /*finishedReceiver*/,
2062                            updateUserIds, instantUserIds);
2063                    if (installerPackageName != null) {
2064                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2065                                extras, 0 /*flags*/,
2066                                installerPackageName, null /*finishedReceiver*/,
2067                                updateUserIds, instantUserIds);
2068                    }
2069                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2070                            null /*package*/, null /*extras*/, 0 /*flags*/,
2071                            packageName /*targetPackage*/,
2072                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2073                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2074                    // First-install and we did a restore, so we're responsible for the
2075                    // first-launch broadcast.
2076                    if (DEBUG_BACKUP) {
2077                        Slog.i(TAG, "Post-restore of " + packageName
2078                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2079                    }
2080                    sendFirstLaunchBroadcast(packageName, installerPackage,
2081                            firstUserIds, firstInstantUserIds);
2082                }
2083
2084                // Send broadcast package appeared if forward locked/external for all users
2085                // treat asec-hosted packages like removable media on upgrade
2086                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2087                    if (DEBUG_INSTALL) {
2088                        Slog.i(TAG, "upgrading pkg " + res.pkg
2089                                + " is ASEC-hosted -> AVAILABLE");
2090                    }
2091                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2092                    ArrayList<String> pkgList = new ArrayList<>(1);
2093                    pkgList.add(packageName);
2094                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2095                }
2096            }
2097
2098            // Work that needs to happen on first install within each user
2099            if (firstUserIds != null && firstUserIds.length > 0) {
2100                synchronized (mPackages) {
2101                    for (int userId : firstUserIds) {
2102                        // If this app is a browser and it's newly-installed for some
2103                        // users, clear any default-browser state in those users. The
2104                        // app's nature doesn't depend on the user, so we can just check
2105                        // its browser nature in any user and generalize.
2106                        if (packageIsBrowser(packageName, userId)) {
2107                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2108                        }
2109
2110                        // We may also need to apply pending (restored) runtime
2111                        // permission grants within these users.
2112                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2113                    }
2114                }
2115            }
2116
2117            if (allNewUsers && !update) {
2118                notifyPackageAdded(packageName);
2119            }
2120
2121            // Log current value of "unknown sources" setting
2122            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2123                    getUnknownSourcesSettings());
2124
2125            // Remove the replaced package's older resources safely now
2126            // We delete after a gc for applications  on sdcard.
2127            if (res.removedInfo != null && res.removedInfo.args != null) {
2128                Runtime.getRuntime().gc();
2129                synchronized (mInstallLock) {
2130                    res.removedInfo.args.doPostDeleteLI(true);
2131                }
2132            } else {
2133                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2134                // and not block here.
2135                VMRuntime.getRuntime().requestConcurrentGC();
2136            }
2137
2138            // Notify DexManager that the package was installed for new users.
2139            // The updated users should already be indexed and the package code paths
2140            // should not change.
2141            // Don't notify the manager for ephemeral apps as they are not expected to
2142            // survive long enough to benefit of background optimizations.
2143            for (int userId : firstUserIds) {
2144                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2145                // There's a race currently where some install events may interleave with an uninstall.
2146                // This can lead to package info being null (b/36642664).
2147                if (info != null) {
2148                    mDexManager.notifyPackageInstalled(info, userId);
2149                }
2150            }
2151        }
2152
2153        // If someone is watching installs - notify them
2154        if (installObserver != null) {
2155            try {
2156                Bundle extras = extrasForInstallResult(res);
2157                installObserver.onPackageInstalled(res.name, res.returnCode,
2158                        res.returnMsg, extras);
2159            } catch (RemoteException e) {
2160                Slog.i(TAG, "Observer no longer exists.");
2161            }
2162        }
2163    }
2164
2165    private StorageEventListener mStorageListener = new StorageEventListener() {
2166        @Override
2167        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2168            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2169                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2170                    final String volumeUuid = vol.getFsUuid();
2171
2172                    // Clean up any users or apps that were removed or recreated
2173                    // while this volume was missing
2174                    sUserManager.reconcileUsers(volumeUuid);
2175                    reconcileApps(volumeUuid);
2176
2177                    // Clean up any install sessions that expired or were
2178                    // cancelled while this volume was missing
2179                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2180
2181                    loadPrivatePackages(vol);
2182
2183                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2184                    unloadPrivatePackages(vol);
2185                }
2186            }
2187        }
2188
2189        @Override
2190        public void onVolumeForgotten(String fsUuid) {
2191            if (TextUtils.isEmpty(fsUuid)) {
2192                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2193                return;
2194            }
2195
2196            // Remove any apps installed on the forgotten volume
2197            synchronized (mPackages) {
2198                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2199                for (PackageSetting ps : packages) {
2200                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2201                    deletePackageVersioned(new VersionedPackage(ps.name,
2202                            PackageManager.VERSION_CODE_HIGHEST),
2203                            new LegacyPackageDeleteObserver(null).getBinder(),
2204                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2205                    // Try very hard to release any references to this package
2206                    // so we don't risk the system server being killed due to
2207                    // open FDs
2208                    AttributeCache.instance().removePackage(ps.name);
2209                }
2210
2211                mSettings.onVolumeForgotten(fsUuid);
2212                mSettings.writeLPr();
2213            }
2214        }
2215    };
2216
2217    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2218        Bundle extras = null;
2219        switch (res.returnCode) {
2220            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2221                extras = new Bundle();
2222                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2223                        res.origPermission);
2224                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2225                        res.origPackage);
2226                break;
2227            }
2228            case PackageManager.INSTALL_SUCCEEDED: {
2229                extras = new Bundle();
2230                extras.putBoolean(Intent.EXTRA_REPLACING,
2231                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2232                break;
2233            }
2234        }
2235        return extras;
2236    }
2237
2238    void scheduleWriteSettingsLocked() {
2239        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2240            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2241        }
2242    }
2243
2244    void scheduleWritePackageListLocked(int userId) {
2245        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2246            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2247            msg.arg1 = userId;
2248            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2249        }
2250    }
2251
2252    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2253        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2254        scheduleWritePackageRestrictionsLocked(userId);
2255    }
2256
2257    void scheduleWritePackageRestrictionsLocked(int userId) {
2258        final int[] userIds = (userId == UserHandle.USER_ALL)
2259                ? sUserManager.getUserIds() : new int[]{userId};
2260        for (int nextUserId : userIds) {
2261            if (!sUserManager.exists(nextUserId)) return;
2262            mDirtyUsers.add(nextUserId);
2263            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2264                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2265            }
2266        }
2267    }
2268
2269    public static PackageManagerService main(Context context, Installer installer,
2270            boolean factoryTest, boolean onlyCore) {
2271        // Self-check for initial settings.
2272        PackageManagerServiceCompilerMapping.checkProperties();
2273
2274        PackageManagerService m = new PackageManagerService(context, installer,
2275                factoryTest, onlyCore);
2276        m.enableSystemUserPackages();
2277        ServiceManager.addService("package", m);
2278        final PackageManagerNative pmn = m.new PackageManagerNative();
2279        ServiceManager.addService("package_native", pmn);
2280        return m;
2281    }
2282
2283    private void enableSystemUserPackages() {
2284        if (!UserManager.isSplitSystemUser()) {
2285            return;
2286        }
2287        // For system user, enable apps based on the following conditions:
2288        // - app is whitelisted or belong to one of these groups:
2289        //   -- system app which has no launcher icons
2290        //   -- system app which has INTERACT_ACROSS_USERS permission
2291        //   -- system IME app
2292        // - app is not in the blacklist
2293        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2294        Set<String> enableApps = new ArraySet<>();
2295        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2296                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2297                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2298        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2299        enableApps.addAll(wlApps);
2300        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2301                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2302        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2303        enableApps.removeAll(blApps);
2304        Log.i(TAG, "Applications installed for system user: " + enableApps);
2305        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2306                UserHandle.SYSTEM);
2307        final int allAppsSize = allAps.size();
2308        synchronized (mPackages) {
2309            for (int i = 0; i < allAppsSize; i++) {
2310                String pName = allAps.get(i);
2311                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2312                // Should not happen, but we shouldn't be failing if it does
2313                if (pkgSetting == null) {
2314                    continue;
2315                }
2316                boolean install = enableApps.contains(pName);
2317                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2318                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2319                            + " for system user");
2320                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2321                }
2322            }
2323            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2324        }
2325    }
2326
2327    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2328        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2329                Context.DISPLAY_SERVICE);
2330        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2331    }
2332
2333    /**
2334     * Requests that files preopted on a secondary system partition be copied to the data partition
2335     * if possible.  Note that the actual copying of the files is accomplished by init for security
2336     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2337     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2338     */
2339    private static void requestCopyPreoptedFiles() {
2340        final int WAIT_TIME_MS = 100;
2341        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2342        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2343            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2344            // We will wait for up to 100 seconds.
2345            final long timeStart = SystemClock.uptimeMillis();
2346            final long timeEnd = timeStart + 100 * 1000;
2347            long timeNow = timeStart;
2348            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2349                try {
2350                    Thread.sleep(WAIT_TIME_MS);
2351                } catch (InterruptedException e) {
2352                    // Do nothing
2353                }
2354                timeNow = SystemClock.uptimeMillis();
2355                if (timeNow > timeEnd) {
2356                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2357                    Slog.wtf(TAG, "cppreopt did not finish!");
2358                    break;
2359                }
2360            }
2361
2362            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2363        }
2364    }
2365
2366    public PackageManagerService(Context context, Installer installer,
2367            boolean factoryTest, boolean onlyCore) {
2368        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2369        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2370        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2371                SystemClock.uptimeMillis());
2372
2373        if (mSdkVersion <= 0) {
2374            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2375        }
2376
2377        mContext = context;
2378
2379        mFactoryTest = factoryTest;
2380        mOnlyCore = onlyCore;
2381        mMetrics = new DisplayMetrics();
2382        mInstaller = installer;
2383
2384        // Create sub-components that provide services / data. Order here is important.
2385        synchronized (mInstallLock) {
2386        synchronized (mPackages) {
2387            // Expose private service for system components to use.
2388            LocalServices.addService(
2389                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2390            sUserManager = new UserManagerService(context, this,
2391                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2392            mPermissionManager = PermissionManagerService.create(context,
2393                    new DefaultPermissionGrantedCallback() {
2394                        @Override
2395                        public void onDefaultRuntimePermissionsGranted(int userId) {
2396                            synchronized(mPackages) {
2397                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2398                            }
2399                        }
2400                    }, mPackages /*externalLock*/);
2401            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2402            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2403        }
2404        }
2405        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2406                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2407        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2408                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2409        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2410                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2411        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2412                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2413        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2414                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2415        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2416                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2417        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2418                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2419
2420        String separateProcesses = SystemProperties.get("debug.separate_processes");
2421        if (separateProcesses != null && separateProcesses.length() > 0) {
2422            if ("*".equals(separateProcesses)) {
2423                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2424                mSeparateProcesses = null;
2425                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2426            } else {
2427                mDefParseFlags = 0;
2428                mSeparateProcesses = separateProcesses.split(",");
2429                Slog.w(TAG, "Running with debug.separate_processes: "
2430                        + separateProcesses);
2431            }
2432        } else {
2433            mDefParseFlags = 0;
2434            mSeparateProcesses = null;
2435        }
2436
2437        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2438                "*dexopt*");
2439        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2440                installer, mInstallLock);
2441        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2442                dexManagerListener);
2443        mArtManagerService = new ArtManagerService(this, installer, mInstallLock);
2444        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2445
2446        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2447                FgThread.get().getLooper());
2448
2449        getDefaultDisplayMetrics(context, mMetrics);
2450
2451        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2452        SystemConfig systemConfig = SystemConfig.getInstance();
2453        mAvailableFeatures = systemConfig.getAvailableFeatures();
2454        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2455
2456        mProtectedPackages = new ProtectedPackages(mContext);
2457
2458        synchronized (mInstallLock) {
2459        // writer
2460        synchronized (mPackages) {
2461            mHandlerThread = new ServiceThread(TAG,
2462                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2463            mHandlerThread.start();
2464            mHandler = new PackageHandler(mHandlerThread.getLooper());
2465            mProcessLoggingHandler = new ProcessLoggingHandler();
2466            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2467            mInstantAppRegistry = new InstantAppRegistry(this);
2468
2469            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2470            final int builtInLibCount = libConfig.size();
2471            for (int i = 0; i < builtInLibCount; i++) {
2472                String name = libConfig.keyAt(i);
2473                String path = libConfig.valueAt(i);
2474                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2475                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2476            }
2477
2478            SELinuxMMAC.readInstallPolicy();
2479
2480            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2481            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2482            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2483
2484            // Clean up orphaned packages for which the code path doesn't exist
2485            // and they are an update to a system app - caused by bug/32321269
2486            final int packageSettingCount = mSettings.mPackages.size();
2487            for (int i = packageSettingCount - 1; i >= 0; i--) {
2488                PackageSetting ps = mSettings.mPackages.valueAt(i);
2489                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2490                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2491                    mSettings.mPackages.removeAt(i);
2492                    mSettings.enableSystemPackageLPw(ps.name);
2493                }
2494            }
2495
2496            if (mFirstBoot) {
2497                requestCopyPreoptedFiles();
2498            }
2499
2500            String customResolverActivity = Resources.getSystem().getString(
2501                    R.string.config_customResolverActivity);
2502            if (TextUtils.isEmpty(customResolverActivity)) {
2503                customResolverActivity = null;
2504            } else {
2505                mCustomResolverComponentName = ComponentName.unflattenFromString(
2506                        customResolverActivity);
2507            }
2508
2509            long startTime = SystemClock.uptimeMillis();
2510
2511            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2512                    startTime);
2513
2514            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2515            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2516
2517            if (bootClassPath == null) {
2518                Slog.w(TAG, "No BOOTCLASSPATH found!");
2519            }
2520
2521            if (systemServerClassPath == null) {
2522                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2523            }
2524
2525            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2526
2527            final VersionInfo ver = mSettings.getInternalVersion();
2528            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2529            if (mIsUpgrade) {
2530                logCriticalInfo(Log.INFO,
2531                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2532            }
2533
2534            // when upgrading from pre-M, promote system app permissions from install to runtime
2535            mPromoteSystemApps =
2536                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2537
2538            // When upgrading from pre-N, we need to handle package extraction like first boot,
2539            // as there is no profiling data available.
2540            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2541
2542            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2543
2544            // save off the names of pre-existing system packages prior to scanning; we don't
2545            // want to automatically grant runtime permissions for new system apps
2546            if (mPromoteSystemApps) {
2547                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2548                while (pkgSettingIter.hasNext()) {
2549                    PackageSetting ps = pkgSettingIter.next();
2550                    if (isSystemApp(ps)) {
2551                        mExistingSystemPackages.add(ps.name);
2552                    }
2553                }
2554            }
2555
2556            mCacheDir = preparePackageParserCache(mIsUpgrade);
2557
2558            // Set flag to monitor and not change apk file paths when
2559            // scanning install directories.
2560            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2561
2562            if (mIsUpgrade || mFirstBoot) {
2563                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2564            }
2565
2566            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2567            // For security and version matching reason, only consider
2568            // overlay packages if they reside in the right directory.
2569            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2570                    mDefParseFlags
2571                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2572                    scanFlags
2573                    | SCAN_AS_SYSTEM
2574                    | SCAN_AS_VENDOR,
2575                    0);
2576            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2577                    mDefParseFlags
2578                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2579                    scanFlags
2580                    | SCAN_AS_SYSTEM
2581                    | SCAN_AS_PRODUCT,
2582                    0);
2583
2584            mParallelPackageParserCallback.findStaticOverlayPackages();
2585
2586            // Find base frameworks (resource packages without code).
2587            scanDirTracedLI(frameworkDir,
2588                    mDefParseFlags
2589                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2590                    scanFlags
2591                    | SCAN_NO_DEX
2592                    | SCAN_AS_SYSTEM
2593                    | SCAN_AS_PRIVILEGED,
2594                    0);
2595
2596            // Collected privileged system packages.
2597            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2598            scanDirTracedLI(privilegedAppDir,
2599                    mDefParseFlags
2600                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2601                    scanFlags
2602                    | SCAN_AS_SYSTEM
2603                    | SCAN_AS_PRIVILEGED,
2604                    0);
2605
2606            // Collect ordinary system packages.
2607            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2608            scanDirTracedLI(systemAppDir,
2609                    mDefParseFlags
2610                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2611                    scanFlags
2612                    | SCAN_AS_SYSTEM,
2613                    0);
2614
2615            // Collected privileged vendor packages.
2616            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2617            try {
2618                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2619            } catch (IOException e) {
2620                // failed to look up canonical path, continue with original one
2621            }
2622            scanDirTracedLI(privilegedVendorAppDir,
2623                    mDefParseFlags
2624                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2625                    scanFlags
2626                    | SCAN_AS_SYSTEM
2627                    | SCAN_AS_VENDOR
2628                    | SCAN_AS_PRIVILEGED,
2629                    0);
2630
2631            // Collect ordinary vendor packages.
2632            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2633            try {
2634                vendorAppDir = vendorAppDir.getCanonicalFile();
2635            } catch (IOException e) {
2636                // failed to look up canonical path, continue with original one
2637            }
2638            scanDirTracedLI(vendorAppDir,
2639                    mDefParseFlags
2640                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2641                    scanFlags
2642                    | SCAN_AS_SYSTEM
2643                    | SCAN_AS_VENDOR,
2644                    0);
2645
2646            // Collect all OEM packages.
2647            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2648            scanDirTracedLI(oemAppDir,
2649                    mDefParseFlags
2650                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2651                    scanFlags
2652                    | SCAN_AS_SYSTEM
2653                    | SCAN_AS_OEM,
2654                    0);
2655
2656            // Collected privileged product packages.
2657            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2658            try {
2659                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2660            } catch (IOException e) {
2661                // failed to look up canonical path, continue with original one
2662            }
2663            scanDirTracedLI(privilegedProductAppDir,
2664                    mDefParseFlags
2665                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2666                    scanFlags
2667                    | SCAN_AS_SYSTEM
2668                    | SCAN_AS_PRODUCT
2669                    | SCAN_AS_PRIVILEGED,
2670                    0);
2671
2672            // Collect ordinary product packages.
2673            File productAppDir = new File(Environment.getProductDirectory(), "app");
2674            try {
2675                productAppDir = productAppDir.getCanonicalFile();
2676            } catch (IOException e) {
2677                // failed to look up canonical path, continue with original one
2678            }
2679            scanDirTracedLI(productAppDir,
2680                    mDefParseFlags
2681                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2682                    scanFlags
2683                    | SCAN_AS_SYSTEM
2684                    | SCAN_AS_PRODUCT,
2685                    0);
2686
2687            // Prune any system packages that no longer exist.
2688            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2689            // Stub packages must either be replaced with full versions in the /data
2690            // partition or be disabled.
2691            final List<String> stubSystemApps = new ArrayList<>();
2692            if (!mOnlyCore) {
2693                // do this first before mucking with mPackages for the "expecting better" case
2694                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2695                while (pkgIterator.hasNext()) {
2696                    final PackageParser.Package pkg = pkgIterator.next();
2697                    if (pkg.isStub) {
2698                        stubSystemApps.add(pkg.packageName);
2699                    }
2700                }
2701
2702                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2703                while (psit.hasNext()) {
2704                    PackageSetting ps = psit.next();
2705
2706                    /*
2707                     * If this is not a system app, it can't be a
2708                     * disable system app.
2709                     */
2710                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2711                        continue;
2712                    }
2713
2714                    /*
2715                     * If the package is scanned, it's not erased.
2716                     */
2717                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2718                    if (scannedPkg != null) {
2719                        /*
2720                         * If the system app is both scanned and in the
2721                         * disabled packages list, then it must have been
2722                         * added via OTA. Remove it from the currently
2723                         * scanned package so the previously user-installed
2724                         * application can be scanned.
2725                         */
2726                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2727                            logCriticalInfo(Log.WARN,
2728                                    "Expecting better updated system app for " + ps.name
2729                                    + "; removing system app.  Last known"
2730                                    + " codePath=" + ps.codePathString
2731                                    + ", versionCode=" + ps.versionCode
2732                                    + "; scanned versionCode=" + scannedPkg.getLongVersionCode());
2733                            removePackageLI(scannedPkg, true);
2734                            mExpectingBetter.put(ps.name, ps.codePath);
2735                        }
2736
2737                        continue;
2738                    }
2739
2740                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2741                        psit.remove();
2742                        logCriticalInfo(Log.WARN, "System package " + ps.name
2743                                + " no longer exists; it's data will be wiped");
2744                        // Actual deletion of code and data will be handled by later
2745                        // reconciliation step
2746                    } else {
2747                        // we still have a disabled system package, but, it still might have
2748                        // been removed. check the code path still exists and check there's
2749                        // still a package. the latter can happen if an OTA keeps the same
2750                        // code path, but, changes the package name.
2751                        final PackageSetting disabledPs =
2752                                mSettings.getDisabledSystemPkgLPr(ps.name);
2753                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2754                                || disabledPs.pkg == null) {
2755                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2756                        }
2757                    }
2758                }
2759            }
2760
2761            //delete tmp files
2762            deleteTempPackageFiles();
2763
2764            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2765
2766            // Remove any shared userIDs that have no associated packages
2767            mSettings.pruneSharedUsersLPw();
2768            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2769            final int systemPackagesCount = mPackages.size();
2770            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2771                    + " ms, packageCount: " + systemPackagesCount
2772                    + " , timePerPackage: "
2773                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2774                    + " , cached: " + cachedSystemApps);
2775            if (mIsUpgrade && systemPackagesCount > 0) {
2776                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2777                        ((int) systemScanTime) / systemPackagesCount);
2778            }
2779            if (!mOnlyCore) {
2780                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2781                        SystemClock.uptimeMillis());
2782                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2783
2784                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2785                        | PackageParser.PARSE_FORWARD_LOCK,
2786                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2787
2788                // Remove disable package settings for updated system apps that were
2789                // removed via an OTA. If the update is no longer present, remove the
2790                // app completely. Otherwise, revoke their system privileges.
2791                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2792                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2793                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2794                    final String msg;
2795                    if (deletedPkg == null) {
2796                        // should have found an update, but, we didn't; remove everything
2797                        msg = "Updated system package " + deletedAppName
2798                                + " no longer exists; removing its data";
2799                        // Actual deletion of code and data will be handled by later
2800                        // reconciliation step
2801                    } else {
2802                        // found an update; revoke system privileges
2803                        msg = "Updated system package + " + deletedAppName
2804                                + " no longer exists; revoking system privileges";
2805
2806                        // Don't do anything if a stub is removed from the system image. If
2807                        // we were to remove the uncompressed version from the /data partition,
2808                        // this is where it'd be done.
2809
2810                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2811                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2812                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2813                    }
2814                    logCriticalInfo(Log.WARN, msg);
2815                }
2816
2817                /*
2818                 * Make sure all system apps that we expected to appear on
2819                 * the userdata partition actually showed up. If they never
2820                 * appeared, crawl back and revive the system version.
2821                 */
2822                for (int i = 0; i < mExpectingBetter.size(); i++) {
2823                    final String packageName = mExpectingBetter.keyAt(i);
2824                    if (!mPackages.containsKey(packageName)) {
2825                        final File scanFile = mExpectingBetter.valueAt(i);
2826
2827                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2828                                + " but never showed up; reverting to system");
2829
2830                        final @ParseFlags int reparseFlags;
2831                        final @ScanFlags int rescanFlags;
2832                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2833                            reparseFlags =
2834                                    mDefParseFlags |
2835                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2836                            rescanFlags =
2837                                    scanFlags
2838                                    | SCAN_AS_SYSTEM
2839                                    | SCAN_AS_PRIVILEGED;
2840                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2841                            reparseFlags =
2842                                    mDefParseFlags |
2843                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2844                            rescanFlags =
2845                                    scanFlags
2846                                    | SCAN_AS_SYSTEM;
2847                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)) {
2848                            reparseFlags =
2849                                    mDefParseFlags |
2850                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2851                            rescanFlags =
2852                                    scanFlags
2853                                    | SCAN_AS_SYSTEM
2854                                    | SCAN_AS_VENDOR
2855                                    | SCAN_AS_PRIVILEGED;
2856                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2857                            reparseFlags =
2858                                    mDefParseFlags |
2859                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2860                            rescanFlags =
2861                                    scanFlags
2862                                    | SCAN_AS_SYSTEM
2863                                    | SCAN_AS_VENDOR;
2864                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2865                            reparseFlags =
2866                                    mDefParseFlags |
2867                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2868                            rescanFlags =
2869                                    scanFlags
2870                                    | SCAN_AS_SYSTEM
2871                                    | SCAN_AS_OEM;
2872                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2873                            reparseFlags =
2874                                    mDefParseFlags |
2875                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2876                            rescanFlags =
2877                                    scanFlags
2878                                    | SCAN_AS_SYSTEM
2879                                    | SCAN_AS_PRODUCT
2880                                    | SCAN_AS_PRIVILEGED;
2881                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2882                            reparseFlags =
2883                                    mDefParseFlags |
2884                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2885                            rescanFlags =
2886                                    scanFlags
2887                                    | SCAN_AS_SYSTEM
2888                                    | SCAN_AS_PRODUCT;
2889                        } else {
2890                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2891                            continue;
2892                        }
2893
2894                        mSettings.enableSystemPackageLPw(packageName);
2895
2896                        try {
2897                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2898                        } catch (PackageManagerException e) {
2899                            Slog.e(TAG, "Failed to parse original system package: "
2900                                    + e.getMessage());
2901                        }
2902                    }
2903                }
2904
2905                // Uncompress and install any stubbed system applications.
2906                // This must be done last to ensure all stubs are replaced or disabled.
2907                decompressSystemApplications(stubSystemApps, scanFlags);
2908
2909                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2910                                - cachedSystemApps;
2911
2912                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2913                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2914                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2915                        + " ms, packageCount: " + dataPackagesCount
2916                        + " , timePerPackage: "
2917                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2918                        + " , cached: " + cachedNonSystemApps);
2919                if (mIsUpgrade && dataPackagesCount > 0) {
2920                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2921                            ((int) dataScanTime) / dataPackagesCount);
2922                }
2923            }
2924            mExpectingBetter.clear();
2925
2926            // Resolve the storage manager.
2927            mStorageManagerPackage = getStorageManagerPackageName();
2928
2929            // Resolve protected action filters. Only the setup wizard is allowed to
2930            // have a high priority filter for these actions.
2931            mSetupWizardPackage = getSetupWizardPackageName();
2932            if (mProtectedFilters.size() > 0) {
2933                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2934                    Slog.i(TAG, "No setup wizard;"
2935                        + " All protected intents capped to priority 0");
2936                }
2937                for (ActivityIntentInfo filter : mProtectedFilters) {
2938                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2939                        if (DEBUG_FILTERS) {
2940                            Slog.i(TAG, "Found setup wizard;"
2941                                + " allow priority " + filter.getPriority() + ";"
2942                                + " package: " + filter.activity.info.packageName
2943                                + " activity: " + filter.activity.className
2944                                + " priority: " + filter.getPriority());
2945                        }
2946                        // skip setup wizard; allow it to keep the high priority filter
2947                        continue;
2948                    }
2949                    if (DEBUG_FILTERS) {
2950                        Slog.i(TAG, "Protected action; cap priority to 0;"
2951                                + " package: " + filter.activity.info.packageName
2952                                + " activity: " + filter.activity.className
2953                                + " origPrio: " + filter.getPriority());
2954                    }
2955                    filter.setPriority(0);
2956                }
2957            }
2958
2959            mSystemTextClassifierPackage = getSystemTextClassifierPackageName();
2960
2961            mDeferProtectedFilters = false;
2962            mProtectedFilters.clear();
2963
2964            // Now that we know all of the shared libraries, update all clients to have
2965            // the correct library paths.
2966            updateAllSharedLibrariesLPw(null);
2967
2968            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2969                // NOTE: We ignore potential failures here during a system scan (like
2970                // the rest of the commands above) because there's precious little we
2971                // can do about it. A settings error is reported, though.
2972                final List<String> changedAbiCodePath =
2973                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2974                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
2975                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
2976                        final String codePathString = changedAbiCodePath.get(i);
2977                        try {
2978                            mInstaller.rmdex(codePathString,
2979                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
2980                        } catch (InstallerException ignored) {
2981                        }
2982                    }
2983                }
2984            }
2985
2986            // Now that we know all the packages we are keeping,
2987            // read and update their last usage times.
2988            mPackageUsage.read(mPackages);
2989            mCompilerStats.read();
2990
2991            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2992                    SystemClock.uptimeMillis());
2993            Slog.i(TAG, "Time to scan packages: "
2994                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2995                    + " seconds");
2996
2997            // If the platform SDK has changed since the last time we booted,
2998            // we need to re-grant app permission to catch any new ones that
2999            // appear.  This is really a hack, and means that apps can in some
3000            // cases get permissions that the user didn't initially explicitly
3001            // allow...  it would be nice to have some better way to handle
3002            // this situation.
3003            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3004            if (sdkUpdated) {
3005                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3006                        + mSdkVersion + "; regranting permissions for internal storage");
3007            }
3008            mPermissionManager.updateAllPermissions(
3009                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3010                    mPermissionCallback);
3011            ver.sdkVersion = mSdkVersion;
3012
3013            // If this is the first boot or an update from pre-M, and it is a normal
3014            // boot, then we need to initialize the default preferred apps across
3015            // all defined users.
3016            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3017                for (UserInfo user : sUserManager.getUsers(true)) {
3018                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3019                    applyFactoryDefaultBrowserLPw(user.id);
3020                    primeDomainVerificationsLPw(user.id);
3021                }
3022            }
3023
3024            // Prepare storage for system user really early during boot,
3025            // since core system apps like SettingsProvider and SystemUI
3026            // can't wait for user to start
3027            final int storageFlags;
3028            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3029                storageFlags = StorageManager.FLAG_STORAGE_DE;
3030            } else {
3031                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3032            }
3033            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3034                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3035                    true /* onlyCoreApps */);
3036            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3037                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3038                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3039                traceLog.traceBegin("AppDataFixup");
3040                try {
3041                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3042                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3043                } catch (InstallerException e) {
3044                    Slog.w(TAG, "Trouble fixing GIDs", e);
3045                }
3046                traceLog.traceEnd();
3047
3048                traceLog.traceBegin("AppDataPrepare");
3049                if (deferPackages == null || deferPackages.isEmpty()) {
3050                    return;
3051                }
3052                int count = 0;
3053                for (String pkgName : deferPackages) {
3054                    PackageParser.Package pkg = null;
3055                    synchronized (mPackages) {
3056                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3057                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3058                            pkg = ps.pkg;
3059                        }
3060                    }
3061                    if (pkg != null) {
3062                        synchronized (mInstallLock) {
3063                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3064                                    true /* maybeMigrateAppData */);
3065                        }
3066                        count++;
3067                    }
3068                }
3069                traceLog.traceEnd();
3070                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3071            }, "prepareAppData");
3072
3073            // If this is first boot after an OTA, and a normal boot, then
3074            // we need to clear code cache directories.
3075            // Note that we do *not* clear the application profiles. These remain valid
3076            // across OTAs and are used to drive profile verification (post OTA) and
3077            // profile compilation (without waiting to collect a fresh set of profiles).
3078            if (mIsUpgrade && !onlyCore) {
3079                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3080                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3081                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3082                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3083                        // No apps are running this early, so no need to freeze
3084                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3085                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3086                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3087                    }
3088                }
3089                ver.fingerprint = Build.FINGERPRINT;
3090            }
3091
3092            checkDefaultBrowser();
3093
3094            // clear only after permissions and other defaults have been updated
3095            mExistingSystemPackages.clear();
3096            mPromoteSystemApps = false;
3097
3098            // All the changes are done during package scanning.
3099            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3100
3101            // can downgrade to reader
3102            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3103            mSettings.writeLPr();
3104            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3105            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3106                    SystemClock.uptimeMillis());
3107
3108            if (!mOnlyCore) {
3109                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3110                mRequiredInstallerPackage = getRequiredInstallerLPr();
3111                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3112                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3113                if (mIntentFilterVerifierComponent != null) {
3114                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3115                            mIntentFilterVerifierComponent);
3116                } else {
3117                    mIntentFilterVerifier = null;
3118                }
3119                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3120                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3121                        SharedLibraryInfo.VERSION_UNDEFINED);
3122                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3123                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3124                        SharedLibraryInfo.VERSION_UNDEFINED);
3125            } else {
3126                mRequiredVerifierPackage = null;
3127                mRequiredInstallerPackage = null;
3128                mRequiredUninstallerPackage = null;
3129                mIntentFilterVerifierComponent = null;
3130                mIntentFilterVerifier = null;
3131                mServicesSystemSharedLibraryPackageName = null;
3132                mSharedSystemSharedLibraryPackageName = null;
3133            }
3134
3135            mInstallerService = new PackageInstallerService(context, this);
3136            final Pair<ComponentName, String> instantAppResolverComponent =
3137                    getInstantAppResolverLPr();
3138            if (instantAppResolverComponent != null) {
3139                if (DEBUG_INSTANT) {
3140                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3141                }
3142                mInstantAppResolverConnection = new InstantAppResolverConnection(
3143                        mContext, instantAppResolverComponent.first,
3144                        instantAppResolverComponent.second);
3145                mInstantAppResolverSettingsComponent =
3146                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3147            } else {
3148                mInstantAppResolverConnection = null;
3149                mInstantAppResolverSettingsComponent = null;
3150            }
3151            updateInstantAppInstallerLocked(null);
3152
3153            // Read and update the usage of dex files.
3154            // Do this at the end of PM init so that all the packages have their
3155            // data directory reconciled.
3156            // At this point we know the code paths of the packages, so we can validate
3157            // the disk file and build the internal cache.
3158            // The usage file is expected to be small so loading and verifying it
3159            // should take a fairly small time compare to the other activities (e.g. package
3160            // scanning).
3161            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3162            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3163            for (int userId : currentUserIds) {
3164                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3165            }
3166            mDexManager.load(userPackages);
3167            if (mIsUpgrade) {
3168                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3169                        (int) (SystemClock.uptimeMillis() - startTime));
3170            }
3171        } // synchronized (mPackages)
3172        } // synchronized (mInstallLock)
3173
3174        // Now after opening every single application zip, make sure they
3175        // are all flushed.  Not really needed, but keeps things nice and
3176        // tidy.
3177        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3178        Runtime.getRuntime().gc();
3179        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3180
3181        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3182        FallbackCategoryProvider.loadFallbacks();
3183        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3184
3185        // The initial scanning above does many calls into installd while
3186        // holding the mPackages lock, but we're mostly interested in yelling
3187        // once we have a booted system.
3188        mInstaller.setWarnIfHeld(mPackages);
3189
3190        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3191    }
3192
3193    /**
3194     * Uncompress and install stub applications.
3195     * <p>In order to save space on the system partition, some applications are shipped in a
3196     * compressed form. In addition the compressed bits for the full application, the
3197     * system image contains a tiny stub comprised of only the Android manifest.
3198     * <p>During the first boot, attempt to uncompress and install the full application. If
3199     * the application can't be installed for any reason, disable the stub and prevent
3200     * uncompressing the full application during future boots.
3201     * <p>In order to forcefully attempt an installation of a full application, go to app
3202     * settings and enable the application.
3203     */
3204    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3205        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3206            final String pkgName = stubSystemApps.get(i);
3207            // skip if the system package is already disabled
3208            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3209                stubSystemApps.remove(i);
3210                continue;
3211            }
3212            // skip if the package isn't installed (?!); this should never happen
3213            final PackageParser.Package pkg = mPackages.get(pkgName);
3214            if (pkg == null) {
3215                stubSystemApps.remove(i);
3216                continue;
3217            }
3218            // skip if the package has been disabled by the user
3219            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3220            if (ps != null) {
3221                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3222                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3223                    stubSystemApps.remove(i);
3224                    continue;
3225                }
3226            }
3227
3228            if (DEBUG_COMPRESSION) {
3229                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3230            }
3231
3232            // uncompress the binary to its eventual destination on /data
3233            final File scanFile = decompressPackage(pkg);
3234            if (scanFile == null) {
3235                continue;
3236            }
3237
3238            // install the package to replace the stub on /system
3239            try {
3240                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3241                removePackageLI(pkg, true /*chatty*/);
3242                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3243                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3244                        UserHandle.USER_SYSTEM, "android");
3245                stubSystemApps.remove(i);
3246                continue;
3247            } catch (PackageManagerException e) {
3248                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3249            }
3250
3251            // any failed attempt to install the package will be cleaned up later
3252        }
3253
3254        // disable any stub still left; these failed to install the full application
3255        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3256            final String pkgName = stubSystemApps.get(i);
3257            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3258            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3259                    UserHandle.USER_SYSTEM, "android");
3260            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3261        }
3262    }
3263
3264    /**
3265     * Decompresses the given package on the system image onto
3266     * the /data partition.
3267     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3268     */
3269    private File decompressPackage(PackageParser.Package pkg) {
3270        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3271        if (compressedFiles == null || compressedFiles.length == 0) {
3272            if (DEBUG_COMPRESSION) {
3273                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3274            }
3275            return null;
3276        }
3277        final File dstCodePath =
3278                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3279        int ret = PackageManager.INSTALL_SUCCEEDED;
3280        try {
3281            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3282            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3283            for (File srcFile : compressedFiles) {
3284                final String srcFileName = srcFile.getName();
3285                final String dstFileName = srcFileName.substring(
3286                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3287                final File dstFile = new File(dstCodePath, dstFileName);
3288                ret = decompressFile(srcFile, dstFile);
3289                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3290                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3291                            + "; pkg: " + pkg.packageName
3292                            + ", file: " + dstFileName);
3293                    break;
3294                }
3295            }
3296        } catch (ErrnoException e) {
3297            logCriticalInfo(Log.ERROR, "Failed to decompress"
3298                    + "; pkg: " + pkg.packageName
3299                    + ", err: " + e.errno);
3300        }
3301        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3302            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3303            NativeLibraryHelper.Handle handle = null;
3304            try {
3305                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3306                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3307                        null /*abiOverride*/);
3308            } catch (IOException e) {
3309                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3310                        + "; pkg: " + pkg.packageName);
3311                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3312            } finally {
3313                IoUtils.closeQuietly(handle);
3314            }
3315        }
3316        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3317            if (dstCodePath == null || !dstCodePath.exists()) {
3318                return null;
3319            }
3320            removeCodePathLI(dstCodePath);
3321            return null;
3322        }
3323
3324        return dstCodePath;
3325    }
3326
3327    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3328        // we're only interested in updating the installer appliction when 1) it's not
3329        // already set or 2) the modified package is the installer
3330        if (mInstantAppInstallerActivity != null
3331                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3332                        .equals(modifiedPackage)) {
3333            return;
3334        }
3335        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3336    }
3337
3338    private static File preparePackageParserCache(boolean isUpgrade) {
3339        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3340            return null;
3341        }
3342
3343        // Disable package parsing on eng builds to allow for faster incremental development.
3344        if (Build.IS_ENG) {
3345            return null;
3346        }
3347
3348        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3349            Slog.i(TAG, "Disabling package parser cache due to system property.");
3350            return null;
3351        }
3352
3353        // The base directory for the package parser cache lives under /data/system/.
3354        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3355                "package_cache");
3356        if (cacheBaseDir == null) {
3357            return null;
3358        }
3359
3360        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3361        // This also serves to "GC" unused entries when the package cache version changes (which
3362        // can only happen during upgrades).
3363        if (isUpgrade) {
3364            FileUtils.deleteContents(cacheBaseDir);
3365        }
3366
3367
3368        // Return the versioned package cache directory. This is something like
3369        // "/data/system/package_cache/1"
3370        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3371
3372        // The following is a workaround to aid development on non-numbered userdebug
3373        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3374        // the system partition is newer.
3375        //
3376        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3377        // that starts with "eng." to signify that this is an engineering build and not
3378        // destined for release.
3379        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3380            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3381
3382            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3383            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3384            // in general and should not be used for production changes. In this specific case,
3385            // we know that they will work.
3386            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3387            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3388                FileUtils.deleteContents(cacheBaseDir);
3389                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3390            }
3391        }
3392
3393        return cacheDir;
3394    }
3395
3396    @Override
3397    public boolean isFirstBoot() {
3398        // allow instant applications
3399        return mFirstBoot;
3400    }
3401
3402    @Override
3403    public boolean isOnlyCoreApps() {
3404        // allow instant applications
3405        return mOnlyCore;
3406    }
3407
3408    @Override
3409    public boolean isUpgrade() {
3410        // allow instant applications
3411        // The system property allows testing ota flow when upgraded to the same image.
3412        return mIsUpgrade || SystemProperties.getBoolean(
3413                "persist.pm.mock-upgrade", false /* default */);
3414    }
3415
3416    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3417        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3418
3419        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3420                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3421                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3422        if (matches.size() == 1) {
3423            return matches.get(0).getComponentInfo().packageName;
3424        } else if (matches.size() == 0) {
3425            Log.e(TAG, "There should probably be a verifier, but, none were found");
3426            return null;
3427        }
3428        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3429    }
3430
3431    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3432        synchronized (mPackages) {
3433            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3434            if (libraryEntry == null) {
3435                throw new IllegalStateException("Missing required shared library:" + name);
3436            }
3437            return libraryEntry.apk;
3438        }
3439    }
3440
3441    private @NonNull String getRequiredInstallerLPr() {
3442        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3443        intent.addCategory(Intent.CATEGORY_DEFAULT);
3444        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3445
3446        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3447                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3448                UserHandle.USER_SYSTEM);
3449        if (matches.size() == 1) {
3450            ResolveInfo resolveInfo = matches.get(0);
3451            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3452                throw new RuntimeException("The installer must be a privileged app");
3453            }
3454            return matches.get(0).getComponentInfo().packageName;
3455        } else {
3456            throw new RuntimeException("There must be exactly one installer; found " + matches);
3457        }
3458    }
3459
3460    private @NonNull String getRequiredUninstallerLPr() {
3461        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3462        intent.addCategory(Intent.CATEGORY_DEFAULT);
3463        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3464
3465        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3466                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3467                UserHandle.USER_SYSTEM);
3468        if (resolveInfo == null ||
3469                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3470            throw new RuntimeException("There must be exactly one uninstaller; found "
3471                    + resolveInfo);
3472        }
3473        return resolveInfo.getComponentInfo().packageName;
3474    }
3475
3476    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3477        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3478
3479        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3480                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3481                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3482        ResolveInfo best = null;
3483        final int N = matches.size();
3484        for (int i = 0; i < N; i++) {
3485            final ResolveInfo cur = matches.get(i);
3486            final String packageName = cur.getComponentInfo().packageName;
3487            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3488                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3489                continue;
3490            }
3491
3492            if (best == null || cur.priority > best.priority) {
3493                best = cur;
3494            }
3495        }
3496
3497        if (best != null) {
3498            return best.getComponentInfo().getComponentName();
3499        }
3500        Slog.w(TAG, "Intent filter verifier not found");
3501        return null;
3502    }
3503
3504    @Override
3505    public @Nullable ComponentName getInstantAppResolverComponent() {
3506        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3507            return null;
3508        }
3509        synchronized (mPackages) {
3510            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3511            if (instantAppResolver == null) {
3512                return null;
3513            }
3514            return instantAppResolver.first;
3515        }
3516    }
3517
3518    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3519        final String[] packageArray =
3520                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3521        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3522            if (DEBUG_INSTANT) {
3523                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3524            }
3525            return null;
3526        }
3527
3528        final int callingUid = Binder.getCallingUid();
3529        final int resolveFlags =
3530                MATCH_DIRECT_BOOT_AWARE
3531                | MATCH_DIRECT_BOOT_UNAWARE
3532                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3533        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3534        final Intent resolverIntent = new Intent(actionName);
3535        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3536                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3537        final int N = resolvers.size();
3538        if (N == 0) {
3539            if (DEBUG_INSTANT) {
3540                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3541            }
3542            return null;
3543        }
3544
3545        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3546        for (int i = 0; i < N; i++) {
3547            final ResolveInfo info = resolvers.get(i);
3548
3549            if (info.serviceInfo == null) {
3550                continue;
3551            }
3552
3553            final String packageName = info.serviceInfo.packageName;
3554            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3555                if (DEBUG_INSTANT) {
3556                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3557                            + " pkg: " + packageName + ", info:" + info);
3558                }
3559                continue;
3560            }
3561
3562            if (DEBUG_INSTANT) {
3563                Slog.v(TAG, "Ephemeral resolver found;"
3564                        + " pkg: " + packageName + ", info:" + info);
3565            }
3566            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3567        }
3568        if (DEBUG_INSTANT) {
3569            Slog.v(TAG, "Ephemeral resolver NOT found");
3570        }
3571        return null;
3572    }
3573
3574    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3575        String[] orderedActions = Build.IS_ENG
3576                ? new String[]{
3577                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3578                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3579                : new String[]{
3580                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3581
3582        final int resolveFlags =
3583                MATCH_DIRECT_BOOT_AWARE
3584                        | MATCH_DIRECT_BOOT_UNAWARE
3585                        | Intent.FLAG_IGNORE_EPHEMERAL
3586                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3587        final Intent intent = new Intent();
3588        intent.addCategory(Intent.CATEGORY_DEFAULT);
3589        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3590        List<ResolveInfo> matches = null;
3591        for (String action : orderedActions) {
3592            intent.setAction(action);
3593            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3594                    resolveFlags, UserHandle.USER_SYSTEM);
3595            if (matches.isEmpty()) {
3596                if (DEBUG_INSTANT) {
3597                    Slog.d(TAG, "Instant App installer not found with " + action);
3598                }
3599            } else {
3600                break;
3601            }
3602        }
3603        Iterator<ResolveInfo> iter = matches.iterator();
3604        while (iter.hasNext()) {
3605            final ResolveInfo rInfo = iter.next();
3606            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3607            if (ps != null) {
3608                final PermissionsState permissionsState = ps.getPermissionsState();
3609                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3610                        || Build.IS_ENG) {
3611                    continue;
3612                }
3613            }
3614            iter.remove();
3615        }
3616        if (matches.size() == 0) {
3617            return null;
3618        } else if (matches.size() == 1) {
3619            return (ActivityInfo) matches.get(0).getComponentInfo();
3620        } else {
3621            throw new RuntimeException(
3622                    "There must be at most one ephemeral installer; found " + matches);
3623        }
3624    }
3625
3626    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3627            @NonNull ComponentName resolver) {
3628        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3629                .addCategory(Intent.CATEGORY_DEFAULT)
3630                .setPackage(resolver.getPackageName());
3631        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3632        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3633                UserHandle.USER_SYSTEM);
3634        if (matches.isEmpty()) {
3635            return null;
3636        }
3637        return matches.get(0).getComponentInfo().getComponentName();
3638    }
3639
3640    private void primeDomainVerificationsLPw(int userId) {
3641        if (DEBUG_DOMAIN_VERIFICATION) {
3642            Slog.d(TAG, "Priming domain verifications in user " + userId);
3643        }
3644
3645        SystemConfig systemConfig = SystemConfig.getInstance();
3646        ArraySet<String> packages = systemConfig.getLinkedApps();
3647
3648        for (String packageName : packages) {
3649            PackageParser.Package pkg = mPackages.get(packageName);
3650            if (pkg != null) {
3651                if (!pkg.isSystem()) {
3652                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3653                    continue;
3654                }
3655
3656                ArraySet<String> domains = null;
3657                for (PackageParser.Activity a : pkg.activities) {
3658                    for (ActivityIntentInfo filter : a.intents) {
3659                        if (hasValidDomains(filter)) {
3660                            if (domains == null) {
3661                                domains = new ArraySet<String>();
3662                            }
3663                            domains.addAll(filter.getHostsList());
3664                        }
3665                    }
3666                }
3667
3668                if (domains != null && domains.size() > 0) {
3669                    if (DEBUG_DOMAIN_VERIFICATION) {
3670                        Slog.v(TAG, "      + " + packageName);
3671                    }
3672                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3673                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3674                    // and then 'always' in the per-user state actually used for intent resolution.
3675                    final IntentFilterVerificationInfo ivi;
3676                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3677                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3678                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3679                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3680                } else {
3681                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3682                            + "' does not handle web links");
3683                }
3684            } else {
3685                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3686            }
3687        }
3688
3689        scheduleWritePackageRestrictionsLocked(userId);
3690        scheduleWriteSettingsLocked();
3691    }
3692
3693    private void applyFactoryDefaultBrowserLPw(int userId) {
3694        // The default browser app's package name is stored in a string resource,
3695        // with a product-specific overlay used for vendor customization.
3696        String browserPkg = mContext.getResources().getString(
3697                com.android.internal.R.string.default_browser);
3698        if (!TextUtils.isEmpty(browserPkg)) {
3699            // non-empty string => required to be a known package
3700            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3701            if (ps == null) {
3702                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3703                browserPkg = null;
3704            } else {
3705                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3706            }
3707        }
3708
3709        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3710        // default.  If there's more than one, just leave everything alone.
3711        if (browserPkg == null) {
3712            calculateDefaultBrowserLPw(userId);
3713        }
3714    }
3715
3716    private void calculateDefaultBrowserLPw(int userId) {
3717        List<String> allBrowsers = resolveAllBrowserApps(userId);
3718        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3719        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3720    }
3721
3722    private List<String> resolveAllBrowserApps(int userId) {
3723        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3724        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3725                PackageManager.MATCH_ALL, userId);
3726
3727        final int count = list.size();
3728        List<String> result = new ArrayList<String>(count);
3729        for (int i=0; i<count; i++) {
3730            ResolveInfo info = list.get(i);
3731            if (info.activityInfo == null
3732                    || !info.handleAllWebDataURI
3733                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3734                    || result.contains(info.activityInfo.packageName)) {
3735                continue;
3736            }
3737            result.add(info.activityInfo.packageName);
3738        }
3739
3740        return result;
3741    }
3742
3743    private boolean packageIsBrowser(String packageName, int userId) {
3744        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3745                PackageManager.MATCH_ALL, userId);
3746        final int N = list.size();
3747        for (int i = 0; i < N; i++) {
3748            ResolveInfo info = list.get(i);
3749            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3750                return true;
3751            }
3752        }
3753        return false;
3754    }
3755
3756    private void checkDefaultBrowser() {
3757        final int myUserId = UserHandle.myUserId();
3758        final String packageName = getDefaultBrowserPackageName(myUserId);
3759        if (packageName != null) {
3760            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3761            if (info == null) {
3762                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3763                synchronized (mPackages) {
3764                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3765                }
3766            }
3767        }
3768    }
3769
3770    @Override
3771    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3772            throws RemoteException {
3773        try {
3774            return super.onTransact(code, data, reply, flags);
3775        } catch (RuntimeException e) {
3776            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3777                Slog.wtf(TAG, "Package Manager Crash", e);
3778            }
3779            throw e;
3780        }
3781    }
3782
3783    static int[] appendInts(int[] cur, int[] add) {
3784        if (add == null) return cur;
3785        if (cur == null) return add;
3786        final int N = add.length;
3787        for (int i=0; i<N; i++) {
3788            cur = appendInt(cur, add[i]);
3789        }
3790        return cur;
3791    }
3792
3793    /**
3794     * Returns whether or not a full application can see an instant application.
3795     * <p>
3796     * Currently, there are three cases in which this can occur:
3797     * <ol>
3798     * <li>The calling application is a "special" process. Special processes
3799     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3800     * <li>The calling application has the permission
3801     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3802     * <li>The calling application is the default launcher on the
3803     *     system partition.</li>
3804     * </ol>
3805     */
3806    private boolean canViewInstantApps(int callingUid, int userId) {
3807        if (callingUid < Process.FIRST_APPLICATION_UID) {
3808            return true;
3809        }
3810        if (mContext.checkCallingOrSelfPermission(
3811                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3812            return true;
3813        }
3814        if (mContext.checkCallingOrSelfPermission(
3815                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3816            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3817            if (homeComponent != null
3818                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3819                return true;
3820            }
3821        }
3822        return false;
3823    }
3824
3825    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3826        if (!sUserManager.exists(userId)) return null;
3827        if (ps == null) {
3828            return null;
3829        }
3830        final int callingUid = Binder.getCallingUid();
3831        // Filter out ephemeral app metadata:
3832        //   * The system/shell/root can see metadata for any app
3833        //   * An installed app can see metadata for 1) other installed apps
3834        //     and 2) ephemeral apps that have explicitly interacted with it
3835        //   * Ephemeral apps can only see their own data and exposed installed apps
3836        //   * Holding a signature permission allows seeing instant apps
3837        if (filterAppAccessLPr(ps, callingUid, userId)) {
3838            return null;
3839        }
3840
3841        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3842                && ps.isSystem()) {
3843            flags |= MATCH_ANY_USER;
3844        }
3845
3846        final PackageUserState state = ps.readUserState(userId);
3847        PackageParser.Package p = ps.pkg;
3848        if (p != null) {
3849            final PermissionsState permissionsState = ps.getPermissionsState();
3850
3851            // Compute GIDs only if requested
3852            final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3853                    ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3854            // Compute granted permissions only if package has requested permissions
3855            final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3856                    ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3857
3858            PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3859                    ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3860
3861            if (packageInfo == null) {
3862                return null;
3863            }
3864
3865            packageInfo.packageName = packageInfo.applicationInfo.packageName =
3866                    resolveExternalPackageNameLPr(p);
3867
3868            return packageInfo;
3869        } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
3870            PackageInfo pi = new PackageInfo();
3871            pi.packageName = ps.name;
3872            pi.setLongVersionCode(ps.versionCode);
3873            pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
3874            pi.firstInstallTime = ps.firstInstallTime;
3875            pi.lastUpdateTime = ps.lastUpdateTime;
3876
3877            ApplicationInfo ai = new ApplicationInfo();
3878            ai.packageName = ps.name;
3879            ai.uid = UserHandle.getUid(userId, ps.appId);
3880            ai.primaryCpuAbi = ps.primaryCpuAbiString;
3881            ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
3882            ai.versionCode = ps.versionCode;
3883            ai.flags = ps.pkgFlags;
3884            ai.privateFlags = ps.pkgPrivateFlags;
3885            pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
3886
3887            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
3888                    + ps.name + "]. Provides a minimum info.");
3889            return pi;
3890        } else {
3891            return null;
3892        }
3893    }
3894
3895    @Override
3896    public void checkPackageStartable(String packageName, int userId) {
3897        final int callingUid = Binder.getCallingUid();
3898        if (getInstantAppPackageName(callingUid) != null) {
3899            throw new SecurityException("Instant applications don't have access to this method");
3900        }
3901        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3902        synchronized (mPackages) {
3903            final PackageSetting ps = mSettings.mPackages.get(packageName);
3904            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3905                throw new SecurityException("Package " + packageName + " was not found!");
3906            }
3907
3908            if (!ps.getInstalled(userId)) {
3909                throw new SecurityException(
3910                        "Package " + packageName + " was not installed for user " + userId + "!");
3911            }
3912
3913            if (mSafeMode && !ps.isSystem()) {
3914                throw new SecurityException("Package " + packageName + " not a system app!");
3915            }
3916
3917            if (mFrozenPackages.contains(packageName)) {
3918                throw new SecurityException("Package " + packageName + " is currently frozen!");
3919            }
3920
3921            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3922                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3923            }
3924        }
3925    }
3926
3927    @Override
3928    public boolean isPackageAvailable(String packageName, int userId) {
3929        if (!sUserManager.exists(userId)) return false;
3930        final int callingUid = Binder.getCallingUid();
3931        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3932                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3933        synchronized (mPackages) {
3934            PackageParser.Package p = mPackages.get(packageName);
3935            if (p != null) {
3936                final PackageSetting ps = (PackageSetting) p.mExtras;
3937                if (filterAppAccessLPr(ps, callingUid, userId)) {
3938                    return false;
3939                }
3940                if (ps != null) {
3941                    final PackageUserState state = ps.readUserState(userId);
3942                    if (state != null) {
3943                        return PackageParser.isAvailable(state);
3944                    }
3945                }
3946            }
3947        }
3948        return false;
3949    }
3950
3951    @Override
3952    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3953        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3954                flags, Binder.getCallingUid(), userId);
3955    }
3956
3957    @Override
3958    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3959            int flags, int userId) {
3960        return getPackageInfoInternal(versionedPackage.getPackageName(),
3961                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
3962    }
3963
3964    /**
3965     * Important: The provided filterCallingUid is used exclusively to filter out packages
3966     * that can be seen based on user state. It's typically the original caller uid prior
3967     * to clearing. Because it can only be provided by trusted code, it's value can be
3968     * trusted and will be used as-is; unlike userId which will be validated by this method.
3969     */
3970    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
3971            int flags, int filterCallingUid, int userId) {
3972        if (!sUserManager.exists(userId)) return null;
3973        flags = updateFlagsForPackage(flags, userId, packageName);
3974        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3975                false /* requireFullPermission */, false /* checkShell */, "get package info");
3976
3977        // reader
3978        synchronized (mPackages) {
3979            // Normalize package name to handle renamed packages and static libs
3980            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3981
3982            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3983            if (matchFactoryOnly) {
3984                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3985                if (ps != null) {
3986                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3987                        return null;
3988                    }
3989                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3990                        return null;
3991                    }
3992                    return generatePackageInfo(ps, flags, userId);
3993                }
3994            }
3995
3996            PackageParser.Package p = mPackages.get(packageName);
3997            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3998                return null;
3999            }
4000            if (DEBUG_PACKAGE_INFO)
4001                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4002            if (p != null) {
4003                final PackageSetting ps = (PackageSetting) p.mExtras;
4004                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4005                    return null;
4006                }
4007                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4008                    return null;
4009                }
4010                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4011            }
4012            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4013                final PackageSetting ps = mSettings.mPackages.get(packageName);
4014                if (ps == null) return null;
4015                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4016                    return null;
4017                }
4018                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4019                    return null;
4020                }
4021                return generatePackageInfo(ps, flags, userId);
4022            }
4023        }
4024        return null;
4025    }
4026
4027    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4028        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4029            return true;
4030        }
4031        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4032            return true;
4033        }
4034        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4035            return true;
4036        }
4037        return false;
4038    }
4039
4040    private boolean isComponentVisibleToInstantApp(
4041            @Nullable ComponentName component, @ComponentType int type) {
4042        if (type == TYPE_ACTIVITY) {
4043            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4044            return activity != null
4045                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4046                    : false;
4047        } else if (type == TYPE_RECEIVER) {
4048            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4049            return activity != null
4050                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4051                    : false;
4052        } else if (type == TYPE_SERVICE) {
4053            final PackageParser.Service service = mServices.mServices.get(component);
4054            return service != null
4055                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4056                    : false;
4057        } else if (type == TYPE_PROVIDER) {
4058            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4059            return provider != null
4060                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4061                    : false;
4062        } else if (type == TYPE_UNKNOWN) {
4063            return isComponentVisibleToInstantApp(component);
4064        }
4065        return false;
4066    }
4067
4068    /**
4069     * Returns whether or not access to the application should be filtered.
4070     * <p>
4071     * Access may be limited based upon whether the calling or target applications
4072     * are instant applications.
4073     *
4074     * @see #canAccessInstantApps(int)
4075     */
4076    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4077            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4078        // if we're in an isolated process, get the real calling UID
4079        if (Process.isIsolated(callingUid)) {
4080            callingUid = mIsolatedOwners.get(callingUid);
4081        }
4082        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4083        final boolean callerIsInstantApp = instantAppPkgName != null;
4084        if (ps == null) {
4085            if (callerIsInstantApp) {
4086                // pretend the application exists, but, needs to be filtered
4087                return true;
4088            }
4089            return false;
4090        }
4091        // if the target and caller are the same application, don't filter
4092        if (isCallerSameApp(ps.name, callingUid)) {
4093            return false;
4094        }
4095        if (callerIsInstantApp) {
4096            // request for a specific component; if it hasn't been explicitly exposed, filter
4097            if (component != null) {
4098                return !isComponentVisibleToInstantApp(component, componentType);
4099            }
4100            // request for application; if no components have been explicitly exposed, filter
4101            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4102        }
4103        if (ps.getInstantApp(userId)) {
4104            // caller can see all components of all instant applications, don't filter
4105            if (canViewInstantApps(callingUid, userId)) {
4106                return false;
4107            }
4108            // request for a specific instant application component, filter
4109            if (component != null) {
4110                return true;
4111            }
4112            // request for an instant application; if the caller hasn't been granted access, filter
4113            return !mInstantAppRegistry.isInstantAccessGranted(
4114                    userId, UserHandle.getAppId(callingUid), ps.appId);
4115        }
4116        return false;
4117    }
4118
4119    /**
4120     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4121     */
4122    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4123        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4124    }
4125
4126    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4127            int flags) {
4128        // Callers can access only the libs they depend on, otherwise they need to explicitly
4129        // ask for the shared libraries given the caller is allowed to access all static libs.
4130        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4131            // System/shell/root get to see all static libs
4132            final int appId = UserHandle.getAppId(uid);
4133            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4134                    || appId == Process.ROOT_UID) {
4135                return false;
4136            }
4137        }
4138
4139        // No package means no static lib as it is always on internal storage
4140        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4141            return false;
4142        }
4143
4144        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4145                ps.pkg.staticSharedLibVersion);
4146        if (libEntry == null) {
4147            return false;
4148        }
4149
4150        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4151        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4152        if (uidPackageNames == null) {
4153            return true;
4154        }
4155
4156        for (String uidPackageName : uidPackageNames) {
4157            if (ps.name.equals(uidPackageName)) {
4158                return false;
4159            }
4160            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4161            if (uidPs != null) {
4162                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4163                        libEntry.info.getName());
4164                if (index < 0) {
4165                    continue;
4166                }
4167                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4168                    return false;
4169                }
4170            }
4171        }
4172        return true;
4173    }
4174
4175    @Override
4176    public String[] currentToCanonicalPackageNames(String[] names) {
4177        final int callingUid = Binder.getCallingUid();
4178        if (getInstantAppPackageName(callingUid) != null) {
4179            return names;
4180        }
4181        final String[] out = new String[names.length];
4182        // reader
4183        synchronized (mPackages) {
4184            final int callingUserId = UserHandle.getUserId(callingUid);
4185            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4186            for (int i=names.length-1; i>=0; i--) {
4187                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4188                boolean translateName = false;
4189                if (ps != null && ps.realName != null) {
4190                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4191                    translateName = !targetIsInstantApp
4192                            || canViewInstantApps
4193                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4194                                    UserHandle.getAppId(callingUid), ps.appId);
4195                }
4196                out[i] = translateName ? ps.realName : names[i];
4197            }
4198        }
4199        return out;
4200    }
4201
4202    @Override
4203    public String[] canonicalToCurrentPackageNames(String[] names) {
4204        final int callingUid = Binder.getCallingUid();
4205        if (getInstantAppPackageName(callingUid) != null) {
4206            return names;
4207        }
4208        final String[] out = new String[names.length];
4209        // reader
4210        synchronized (mPackages) {
4211            final int callingUserId = UserHandle.getUserId(callingUid);
4212            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4213            for (int i=names.length-1; i>=0; i--) {
4214                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4215                boolean translateName = false;
4216                if (cur != null) {
4217                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4218                    final boolean targetIsInstantApp =
4219                            ps != null && ps.getInstantApp(callingUserId);
4220                    translateName = !targetIsInstantApp
4221                            || canViewInstantApps
4222                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4223                                    UserHandle.getAppId(callingUid), ps.appId);
4224                }
4225                out[i] = translateName ? cur : names[i];
4226            }
4227        }
4228        return out;
4229    }
4230
4231    @Override
4232    public int getPackageUid(String packageName, int flags, int userId) {
4233        if (!sUserManager.exists(userId)) return -1;
4234        final int callingUid = Binder.getCallingUid();
4235        flags = updateFlagsForPackage(flags, userId, packageName);
4236        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4237                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4238
4239        // reader
4240        synchronized (mPackages) {
4241            final PackageParser.Package p = mPackages.get(packageName);
4242            if (p != null && p.isMatch(flags)) {
4243                PackageSetting ps = (PackageSetting) p.mExtras;
4244                if (filterAppAccessLPr(ps, callingUid, userId)) {
4245                    return -1;
4246                }
4247                return UserHandle.getUid(userId, p.applicationInfo.uid);
4248            }
4249            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4250                final PackageSetting ps = mSettings.mPackages.get(packageName);
4251                if (ps != null && ps.isMatch(flags)
4252                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4253                    return UserHandle.getUid(userId, ps.appId);
4254                }
4255            }
4256        }
4257
4258        return -1;
4259    }
4260
4261    @Override
4262    public int[] getPackageGids(String packageName, int flags, int userId) {
4263        if (!sUserManager.exists(userId)) return null;
4264        final int callingUid = Binder.getCallingUid();
4265        flags = updateFlagsForPackage(flags, userId, packageName);
4266        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4267                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4268
4269        // reader
4270        synchronized (mPackages) {
4271            final PackageParser.Package p = mPackages.get(packageName);
4272            if (p != null && p.isMatch(flags)) {
4273                PackageSetting ps = (PackageSetting) p.mExtras;
4274                if (filterAppAccessLPr(ps, callingUid, userId)) {
4275                    return null;
4276                }
4277                // TODO: Shouldn't this be checking for package installed state for userId and
4278                // return null?
4279                return ps.getPermissionsState().computeGids(userId);
4280            }
4281            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4282                final PackageSetting ps = mSettings.mPackages.get(packageName);
4283                if (ps != null && ps.isMatch(flags)
4284                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4285                    return ps.getPermissionsState().computeGids(userId);
4286                }
4287            }
4288        }
4289
4290        return null;
4291    }
4292
4293    @Override
4294    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4295        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4296    }
4297
4298    @Override
4299    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4300            int flags) {
4301        final List<PermissionInfo> permissionList =
4302                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4303        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4304    }
4305
4306    @Override
4307    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4308        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4309    }
4310
4311    @Override
4312    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4313        final List<PermissionGroupInfo> permissionList =
4314                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4315        return (permissionList == null)
4316                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4317    }
4318
4319    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4320            int filterCallingUid, int userId) {
4321        if (!sUserManager.exists(userId)) return null;
4322        PackageSetting ps = mSettings.mPackages.get(packageName);
4323        if (ps != null) {
4324            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4325                return null;
4326            }
4327            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4328                return null;
4329            }
4330            if (ps.pkg == null) {
4331                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4332                if (pInfo != null) {
4333                    return pInfo.applicationInfo;
4334                }
4335                return null;
4336            }
4337            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4338                    ps.readUserState(userId), userId);
4339            if (ai != null) {
4340                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4341            }
4342            return ai;
4343        }
4344        return null;
4345    }
4346
4347    @Override
4348    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4349        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4350    }
4351
4352    /**
4353     * Important: The provided filterCallingUid is used exclusively to filter out applications
4354     * that can be seen based on user state. It's typically the original caller uid prior
4355     * to clearing. Because it can only be provided by trusted code, it's value can be
4356     * trusted and will be used as-is; unlike userId which will be validated by this method.
4357     */
4358    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4359            int filterCallingUid, int userId) {
4360        if (!sUserManager.exists(userId)) return null;
4361        flags = updateFlagsForApplication(flags, userId, packageName);
4362        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4363                false /* requireFullPermission */, false /* checkShell */, "get application info");
4364
4365        // writer
4366        synchronized (mPackages) {
4367            // Normalize package name to handle renamed packages and static libs
4368            packageName = resolveInternalPackageNameLPr(packageName,
4369                    PackageManager.VERSION_CODE_HIGHEST);
4370
4371            PackageParser.Package p = mPackages.get(packageName);
4372            if (DEBUG_PACKAGE_INFO) Log.v(
4373                    TAG, "getApplicationInfo " + packageName
4374                    + ": " + p);
4375            if (p != null) {
4376                PackageSetting ps = mSettings.mPackages.get(packageName);
4377                if (ps == null) return null;
4378                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4379                    return null;
4380                }
4381                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4382                    return null;
4383                }
4384                // Note: isEnabledLP() does not apply here - always return info
4385                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4386                        p, flags, ps.readUserState(userId), userId);
4387                if (ai != null) {
4388                    ai.packageName = resolveExternalPackageNameLPr(p);
4389                }
4390                return ai;
4391            }
4392            if ("android".equals(packageName)||"system".equals(packageName)) {
4393                return mAndroidApplication;
4394            }
4395            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4396                // Already generates the external package name
4397                return generateApplicationInfoFromSettingsLPw(packageName,
4398                        flags, filterCallingUid, userId);
4399            }
4400        }
4401        return null;
4402    }
4403
4404    private String normalizePackageNameLPr(String packageName) {
4405        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4406        return normalizedPackageName != null ? normalizedPackageName : packageName;
4407    }
4408
4409    @Override
4410    public void deletePreloadsFileCache() {
4411        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4412            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4413        }
4414        File dir = Environment.getDataPreloadsFileCacheDirectory();
4415        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4416        FileUtils.deleteContents(dir);
4417    }
4418
4419    @Override
4420    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4421            final int storageFlags, final IPackageDataObserver observer) {
4422        mContext.enforceCallingOrSelfPermission(
4423                android.Manifest.permission.CLEAR_APP_CACHE, null);
4424        mHandler.post(() -> {
4425            boolean success = false;
4426            try {
4427                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4428                success = true;
4429            } catch (IOException e) {
4430                Slog.w(TAG, e);
4431            }
4432            if (observer != null) {
4433                try {
4434                    observer.onRemoveCompleted(null, success);
4435                } catch (RemoteException e) {
4436                    Slog.w(TAG, e);
4437                }
4438            }
4439        });
4440    }
4441
4442    @Override
4443    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4444            final int storageFlags, final IntentSender pi) {
4445        mContext.enforceCallingOrSelfPermission(
4446                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4447        mHandler.post(() -> {
4448            boolean success = false;
4449            try {
4450                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4451                success = true;
4452            } catch (IOException e) {
4453                Slog.w(TAG, e);
4454            }
4455            if (pi != null) {
4456                try {
4457                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4458                } catch (SendIntentException e) {
4459                    Slog.w(TAG, e);
4460                }
4461            }
4462        });
4463    }
4464
4465    /**
4466     * Blocking call to clear various types of cached data across the system
4467     * until the requested bytes are available.
4468     */
4469    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4470        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4471        final File file = storage.findPathForUuid(volumeUuid);
4472        if (file.getUsableSpace() >= bytes) return;
4473
4474        if (ENABLE_FREE_CACHE_V2) {
4475            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4476                    volumeUuid);
4477            final boolean aggressive = (storageFlags
4478                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4479            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4480
4481            // 1. Pre-flight to determine if we have any chance to succeed
4482            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4483            if (internalVolume && (aggressive || SystemProperties
4484                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4485                deletePreloadsFileCache();
4486                if (file.getUsableSpace() >= bytes) return;
4487            }
4488
4489            // 3. Consider parsed APK data (aggressive only)
4490            if (internalVolume && aggressive) {
4491                FileUtils.deleteContents(mCacheDir);
4492                if (file.getUsableSpace() >= bytes) return;
4493            }
4494
4495            // 4. Consider cached app data (above quotas)
4496            try {
4497                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4498                        Installer.FLAG_FREE_CACHE_V2);
4499            } catch (InstallerException ignored) {
4500            }
4501            if (file.getUsableSpace() >= bytes) return;
4502
4503            // 5. Consider shared libraries with refcount=0 and age>min cache period
4504            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4505                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4506                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4507                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4508                return;
4509            }
4510
4511            // 6. Consider dexopt output (aggressive only)
4512            // TODO: Implement
4513
4514            // 7. Consider installed instant apps unused longer than min cache period
4515            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4516                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4517                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4518                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4519                return;
4520            }
4521
4522            // 8. Consider cached app data (below quotas)
4523            try {
4524                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4525                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4526            } catch (InstallerException ignored) {
4527            }
4528            if (file.getUsableSpace() >= bytes) return;
4529
4530            // 9. Consider DropBox entries
4531            // TODO: Implement
4532
4533            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4534            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4535                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4536                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4537                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4538                return;
4539            }
4540        } else {
4541            try {
4542                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4543            } catch (InstallerException ignored) {
4544            }
4545            if (file.getUsableSpace() >= bytes) return;
4546        }
4547
4548        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4549    }
4550
4551    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4552            throws IOException {
4553        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4554        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4555
4556        List<VersionedPackage> packagesToDelete = null;
4557        final long now = System.currentTimeMillis();
4558
4559        synchronized (mPackages) {
4560            final int[] allUsers = sUserManager.getUserIds();
4561            final int libCount = mSharedLibraries.size();
4562            for (int i = 0; i < libCount; i++) {
4563                final LongSparseArray<SharedLibraryEntry> versionedLib
4564                        = mSharedLibraries.valueAt(i);
4565                if (versionedLib == null) {
4566                    continue;
4567                }
4568                final int versionCount = versionedLib.size();
4569                for (int j = 0; j < versionCount; j++) {
4570                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4571                    // Skip packages that are not static shared libs.
4572                    if (!libInfo.isStatic()) {
4573                        break;
4574                    }
4575                    // Important: We skip static shared libs used for some user since
4576                    // in such a case we need to keep the APK on the device. The check for
4577                    // a lib being used for any user is performed by the uninstall call.
4578                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4579                    // Resolve the package name - we use synthetic package names internally
4580                    final String internalPackageName = resolveInternalPackageNameLPr(
4581                            declaringPackage.getPackageName(),
4582                            declaringPackage.getLongVersionCode());
4583                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4584                    // Skip unused static shared libs cached less than the min period
4585                    // to prevent pruning a lib needed by a subsequently installed package.
4586                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4587                        continue;
4588                    }
4589                    if (packagesToDelete == null) {
4590                        packagesToDelete = new ArrayList<>();
4591                    }
4592                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4593                            declaringPackage.getLongVersionCode()));
4594                }
4595            }
4596        }
4597
4598        if (packagesToDelete != null) {
4599            final int packageCount = packagesToDelete.size();
4600            for (int i = 0; i < packageCount; i++) {
4601                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4602                // Delete the package synchronously (will fail of the lib used for any user).
4603                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4604                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4605                                == PackageManager.DELETE_SUCCEEDED) {
4606                    if (volume.getUsableSpace() >= neededSpace) {
4607                        return true;
4608                    }
4609                }
4610            }
4611        }
4612
4613        return false;
4614    }
4615
4616    /**
4617     * Update given flags based on encryption status of current user.
4618     */
4619    private int updateFlags(int flags, int userId) {
4620        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4621                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4622            // Caller expressed an explicit opinion about what encryption
4623            // aware/unaware components they want to see, so fall through and
4624            // give them what they want
4625        } else {
4626            // Caller expressed no opinion, so match based on user state
4627            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4628                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4629            } else {
4630                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4631            }
4632        }
4633        return flags;
4634    }
4635
4636    private UserManagerInternal getUserManagerInternal() {
4637        if (mUserManagerInternal == null) {
4638            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4639        }
4640        return mUserManagerInternal;
4641    }
4642
4643    private ActivityManagerInternal getActivityManagerInternal() {
4644        if (mActivityManagerInternal == null) {
4645            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4646        }
4647        return mActivityManagerInternal;
4648    }
4649
4650
4651    private DeviceIdleController.LocalService getDeviceIdleController() {
4652        if (mDeviceIdleController == null) {
4653            mDeviceIdleController =
4654                    LocalServices.getService(DeviceIdleController.LocalService.class);
4655        }
4656        return mDeviceIdleController;
4657    }
4658
4659    /**
4660     * Update given flags when being used to request {@link PackageInfo}.
4661     */
4662    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4663        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4664        boolean triaged = true;
4665        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4666                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4667            // Caller is asking for component details, so they'd better be
4668            // asking for specific encryption matching behavior, or be triaged
4669            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4670                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4671                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4672                triaged = false;
4673            }
4674        }
4675        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4676                | PackageManager.MATCH_SYSTEM_ONLY
4677                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4678            triaged = false;
4679        }
4680        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4681            mPermissionManager.enforceCrossUserPermission(
4682                    Binder.getCallingUid(), userId, false, false,
4683                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4684                    + Debug.getCallers(5));
4685        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4686                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4687            // If the caller wants all packages and has a restricted profile associated with it,
4688            // then match all users. This is to make sure that launchers that need to access work
4689            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4690            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4691            flags |= PackageManager.MATCH_ANY_USER;
4692        }
4693        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4694            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4695                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4696        }
4697        return updateFlags(flags, userId);
4698    }
4699
4700    /**
4701     * Update given flags when being used to request {@link ApplicationInfo}.
4702     */
4703    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4704        return updateFlagsForPackage(flags, userId, cookie);
4705    }
4706
4707    /**
4708     * Update given flags when being used to request {@link ComponentInfo}.
4709     */
4710    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4711        if (cookie instanceof Intent) {
4712            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4713                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4714            }
4715        }
4716
4717        boolean triaged = true;
4718        // Caller is asking for component details, so they'd better be
4719        // asking for specific encryption matching behavior, or be triaged
4720        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4721                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4722                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4723            triaged = false;
4724        }
4725        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4726            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4727                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4728        }
4729
4730        return updateFlags(flags, userId);
4731    }
4732
4733    /**
4734     * Update given intent when being used to request {@link ResolveInfo}.
4735     */
4736    private Intent updateIntentForResolve(Intent intent) {
4737        if (intent.getSelector() != null) {
4738            intent = intent.getSelector();
4739        }
4740        if (DEBUG_PREFERRED) {
4741            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4742        }
4743        return intent;
4744    }
4745
4746    /**
4747     * Update given flags when being used to request {@link ResolveInfo}.
4748     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4749     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4750     * flag set. However, this flag is only honoured in three circumstances:
4751     * <ul>
4752     * <li>when called from a system process</li>
4753     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4754     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4755     * action and a {@code android.intent.category.BROWSABLE} category</li>
4756     * </ul>
4757     */
4758    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4759        return updateFlagsForResolve(flags, userId, intent, callingUid,
4760                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4761    }
4762    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4763            boolean wantInstantApps) {
4764        return updateFlagsForResolve(flags, userId, intent, callingUid,
4765                wantInstantApps, false /*onlyExposedExplicitly*/);
4766    }
4767    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4768            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4769        // Safe mode means we shouldn't match any third-party components
4770        if (mSafeMode) {
4771            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4772        }
4773        if (getInstantAppPackageName(callingUid) != null) {
4774            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4775            if (onlyExposedExplicitly) {
4776                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4777            }
4778            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4779            flags |= PackageManager.MATCH_INSTANT;
4780        } else {
4781            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4782            final boolean allowMatchInstant = wantInstantApps
4783                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4784            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4785                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4786            if (!allowMatchInstant) {
4787                flags &= ~PackageManager.MATCH_INSTANT;
4788            }
4789        }
4790        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4791    }
4792
4793    @Override
4794    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4795        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4796    }
4797
4798    /**
4799     * Important: The provided filterCallingUid is used exclusively to filter out activities
4800     * that can be seen based on user state. It's typically the original caller uid prior
4801     * to clearing. Because it can only be provided by trusted code, it's value can be
4802     * trusted and will be used as-is; unlike userId which will be validated by this method.
4803     */
4804    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4805            int filterCallingUid, int userId) {
4806        if (!sUserManager.exists(userId)) return null;
4807        flags = updateFlagsForComponent(flags, userId, component);
4808
4809        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4810            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4811                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4812        }
4813
4814        synchronized (mPackages) {
4815            PackageParser.Activity a = mActivities.mActivities.get(component);
4816
4817            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4818            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4819                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4820                if (ps == null) return null;
4821                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4822                    return null;
4823                }
4824                return PackageParser.generateActivityInfo(
4825                        a, flags, ps.readUserState(userId), userId);
4826            }
4827            if (mResolveComponentName.equals(component)) {
4828                return PackageParser.generateActivityInfo(
4829                        mResolveActivity, flags, new PackageUserState(), userId);
4830            }
4831        }
4832        return null;
4833    }
4834
4835    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4836        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4837            return false;
4838        }
4839        final long token = Binder.clearCallingIdentity();
4840        try {
4841            final int callingUserId = UserHandle.getUserId(callingUid);
4842            if (ActivityManager.getCurrentUser() != callingUserId) {
4843                return false;
4844            }
4845            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4846        } finally {
4847            Binder.restoreCallingIdentity(token);
4848        }
4849    }
4850
4851    @Override
4852    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4853            String resolvedType) {
4854        synchronized (mPackages) {
4855            if (component.equals(mResolveComponentName)) {
4856                // The resolver supports EVERYTHING!
4857                return true;
4858            }
4859            final int callingUid = Binder.getCallingUid();
4860            final int callingUserId = UserHandle.getUserId(callingUid);
4861            PackageParser.Activity a = mActivities.mActivities.get(component);
4862            if (a == null) {
4863                return false;
4864            }
4865            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4866            if (ps == null) {
4867                return false;
4868            }
4869            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4870                return false;
4871            }
4872            for (int i=0; i<a.intents.size(); i++) {
4873                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4874                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4875                    return true;
4876                }
4877            }
4878            return false;
4879        }
4880    }
4881
4882    @Override
4883    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4884        if (!sUserManager.exists(userId)) return null;
4885        final int callingUid = Binder.getCallingUid();
4886        flags = updateFlagsForComponent(flags, userId, component);
4887        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4888                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4889        synchronized (mPackages) {
4890            PackageParser.Activity a = mReceivers.mActivities.get(component);
4891            if (DEBUG_PACKAGE_INFO) Log.v(
4892                TAG, "getReceiverInfo " + component + ": " + a);
4893            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4894                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4895                if (ps == null) return null;
4896                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4897                    return null;
4898                }
4899                return PackageParser.generateActivityInfo(
4900                        a, flags, ps.readUserState(userId), userId);
4901            }
4902        }
4903        return null;
4904    }
4905
4906    @Override
4907    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4908            int flags, int userId) {
4909        if (!sUserManager.exists(userId)) return null;
4910        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4911        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4912            return null;
4913        }
4914
4915        flags = updateFlagsForPackage(flags, userId, null);
4916
4917        final boolean canSeeStaticLibraries =
4918                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4919                        == PERMISSION_GRANTED
4920                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4921                        == PERMISSION_GRANTED
4922                || canRequestPackageInstallsInternal(packageName,
4923                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4924                        false  /* throwIfPermNotDeclared*/)
4925                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4926                        == PERMISSION_GRANTED;
4927
4928        synchronized (mPackages) {
4929            List<SharedLibraryInfo> result = null;
4930
4931            final int libCount = mSharedLibraries.size();
4932            for (int i = 0; i < libCount; i++) {
4933                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4934                if (versionedLib == null) {
4935                    continue;
4936                }
4937
4938                final int versionCount = versionedLib.size();
4939                for (int j = 0; j < versionCount; j++) {
4940                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4941                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4942                        break;
4943                    }
4944                    final long identity = Binder.clearCallingIdentity();
4945                    try {
4946                        PackageInfo packageInfo = getPackageInfoVersioned(
4947                                libInfo.getDeclaringPackage(), flags
4948                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4949                        if (packageInfo == null) {
4950                            continue;
4951                        }
4952                    } finally {
4953                        Binder.restoreCallingIdentity(identity);
4954                    }
4955
4956                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4957                            libInfo.getLongVersion(), libInfo.getType(),
4958                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4959                            flags, userId));
4960
4961                    if (result == null) {
4962                        result = new ArrayList<>();
4963                    }
4964                    result.add(resLibInfo);
4965                }
4966            }
4967
4968            return result != null ? new ParceledListSlice<>(result) : null;
4969        }
4970    }
4971
4972    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4973            SharedLibraryInfo libInfo, int flags, int userId) {
4974        List<VersionedPackage> versionedPackages = null;
4975        final int packageCount = mSettings.mPackages.size();
4976        for (int i = 0; i < packageCount; i++) {
4977            PackageSetting ps = mSettings.mPackages.valueAt(i);
4978
4979            if (ps == null) {
4980                continue;
4981            }
4982
4983            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4984                continue;
4985            }
4986
4987            final String libName = libInfo.getName();
4988            if (libInfo.isStatic()) {
4989                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4990                if (libIdx < 0) {
4991                    continue;
4992                }
4993                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
4994                    continue;
4995                }
4996                if (versionedPackages == null) {
4997                    versionedPackages = new ArrayList<>();
4998                }
4999                // If the dependent is a static shared lib, use the public package name
5000                String dependentPackageName = ps.name;
5001                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5002                    dependentPackageName = ps.pkg.manifestPackageName;
5003                }
5004                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5005            } else if (ps.pkg != null) {
5006                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5007                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5008                    if (versionedPackages == null) {
5009                        versionedPackages = new ArrayList<>();
5010                    }
5011                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5012                }
5013            }
5014        }
5015
5016        return versionedPackages;
5017    }
5018
5019    @Override
5020    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5021        if (!sUserManager.exists(userId)) return null;
5022        final int callingUid = Binder.getCallingUid();
5023        flags = updateFlagsForComponent(flags, userId, component);
5024        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5025                false /* requireFullPermission */, false /* checkShell */, "get service info");
5026        synchronized (mPackages) {
5027            PackageParser.Service s = mServices.mServices.get(component);
5028            if (DEBUG_PACKAGE_INFO) Log.v(
5029                TAG, "getServiceInfo " + component + ": " + s);
5030            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5031                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5032                if (ps == null) return null;
5033                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5034                    return null;
5035                }
5036                return PackageParser.generateServiceInfo(
5037                        s, flags, ps.readUserState(userId), userId);
5038            }
5039        }
5040        return null;
5041    }
5042
5043    @Override
5044    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5045        if (!sUserManager.exists(userId)) return null;
5046        final int callingUid = Binder.getCallingUid();
5047        flags = updateFlagsForComponent(flags, userId, component);
5048        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5049                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5050        synchronized (mPackages) {
5051            PackageParser.Provider p = mProviders.mProviders.get(component);
5052            if (DEBUG_PACKAGE_INFO) Log.v(
5053                TAG, "getProviderInfo " + component + ": " + p);
5054            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5055                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5056                if (ps == null) return null;
5057                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5058                    return null;
5059                }
5060                return PackageParser.generateProviderInfo(
5061                        p, flags, ps.readUserState(userId), userId);
5062            }
5063        }
5064        return null;
5065    }
5066
5067    @Override
5068    public String[] getSystemSharedLibraryNames() {
5069        // allow instant applications
5070        synchronized (mPackages) {
5071            Set<String> libs = null;
5072            final int libCount = mSharedLibraries.size();
5073            for (int i = 0; i < libCount; i++) {
5074                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5075                if (versionedLib == null) {
5076                    continue;
5077                }
5078                final int versionCount = versionedLib.size();
5079                for (int j = 0; j < versionCount; j++) {
5080                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5081                    if (!libEntry.info.isStatic()) {
5082                        if (libs == null) {
5083                            libs = new ArraySet<>();
5084                        }
5085                        libs.add(libEntry.info.getName());
5086                        break;
5087                    }
5088                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5089                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5090                            UserHandle.getUserId(Binder.getCallingUid()),
5091                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5092                        if (libs == null) {
5093                            libs = new ArraySet<>();
5094                        }
5095                        libs.add(libEntry.info.getName());
5096                        break;
5097                    }
5098                }
5099            }
5100
5101            if (libs != null) {
5102                String[] libsArray = new String[libs.size()];
5103                libs.toArray(libsArray);
5104                return libsArray;
5105            }
5106
5107            return null;
5108        }
5109    }
5110
5111    @Override
5112    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5113        // allow instant applications
5114        synchronized (mPackages) {
5115            return mServicesSystemSharedLibraryPackageName;
5116        }
5117    }
5118
5119    @Override
5120    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5121        // allow instant applications
5122        synchronized (mPackages) {
5123            return mSharedSystemSharedLibraryPackageName;
5124        }
5125    }
5126
5127    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5128        for (int i = userList.length - 1; i >= 0; --i) {
5129            final int userId = userList[i];
5130            // don't add instant app to the list of updates
5131            if (pkgSetting.getInstantApp(userId)) {
5132                continue;
5133            }
5134            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5135            if (changedPackages == null) {
5136                changedPackages = new SparseArray<>();
5137                mChangedPackages.put(userId, changedPackages);
5138            }
5139            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5140            if (sequenceNumbers == null) {
5141                sequenceNumbers = new HashMap<>();
5142                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5143            }
5144            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5145            if (sequenceNumber != null) {
5146                changedPackages.remove(sequenceNumber);
5147            }
5148            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5149            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5150        }
5151        mChangedPackagesSequenceNumber++;
5152    }
5153
5154    @Override
5155    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5156        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5157            return null;
5158        }
5159        synchronized (mPackages) {
5160            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5161                return null;
5162            }
5163            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5164            if (changedPackages == null) {
5165                return null;
5166            }
5167            final List<String> packageNames =
5168                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5169            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5170                final String packageName = changedPackages.get(i);
5171                if (packageName != null) {
5172                    packageNames.add(packageName);
5173                }
5174            }
5175            return packageNames.isEmpty()
5176                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5177        }
5178    }
5179
5180    @Override
5181    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5182        // allow instant applications
5183        ArrayList<FeatureInfo> res;
5184        synchronized (mAvailableFeatures) {
5185            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5186            res.addAll(mAvailableFeatures.values());
5187        }
5188        final FeatureInfo fi = new FeatureInfo();
5189        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5190                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5191        res.add(fi);
5192
5193        return new ParceledListSlice<>(res);
5194    }
5195
5196    @Override
5197    public boolean hasSystemFeature(String name, int version) {
5198        // allow instant applications
5199        synchronized (mAvailableFeatures) {
5200            final FeatureInfo feat = mAvailableFeatures.get(name);
5201            if (feat == null) {
5202                return false;
5203            } else {
5204                return feat.version >= version;
5205            }
5206        }
5207    }
5208
5209    @Override
5210    public int checkPermission(String permName, String pkgName, int userId) {
5211        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5212    }
5213
5214    @Override
5215    public int checkUidPermission(String permName, int uid) {
5216        synchronized (mPackages) {
5217            final String[] packageNames = getPackagesForUid(uid);
5218            final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0)
5219                    ? mPackages.get(packageNames[0])
5220                    : null;
5221            return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid());
5222        }
5223    }
5224
5225    @Override
5226    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5227        if (UserHandle.getCallingUserId() != userId) {
5228            mContext.enforceCallingPermission(
5229                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5230                    "isPermissionRevokedByPolicy for user " + userId);
5231        }
5232
5233        if (checkPermission(permission, packageName, userId)
5234                == PackageManager.PERMISSION_GRANTED) {
5235            return false;
5236        }
5237
5238        final int callingUid = Binder.getCallingUid();
5239        if (getInstantAppPackageName(callingUid) != null) {
5240            if (!isCallerSameApp(packageName, callingUid)) {
5241                return false;
5242            }
5243        } else {
5244            if (isInstantApp(packageName, userId)) {
5245                return false;
5246            }
5247        }
5248
5249        final long identity = Binder.clearCallingIdentity();
5250        try {
5251            final int flags = getPermissionFlags(permission, packageName, userId);
5252            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5253        } finally {
5254            Binder.restoreCallingIdentity(identity);
5255        }
5256    }
5257
5258    @Override
5259    public String getPermissionControllerPackageName() {
5260        synchronized (mPackages) {
5261            return mRequiredInstallerPackage;
5262        }
5263    }
5264
5265    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5266        return mPermissionManager.addDynamicPermission(
5267                info, async, getCallingUid(), new PermissionCallback() {
5268                    @Override
5269                    public void onPermissionChanged() {
5270                        if (!async) {
5271                            mSettings.writeLPr();
5272                        } else {
5273                            scheduleWriteSettingsLocked();
5274                        }
5275                    }
5276                });
5277    }
5278
5279    @Override
5280    public boolean addPermission(PermissionInfo info) {
5281        synchronized (mPackages) {
5282            return addDynamicPermission(info, false);
5283        }
5284    }
5285
5286    @Override
5287    public boolean addPermissionAsync(PermissionInfo info) {
5288        synchronized (mPackages) {
5289            return addDynamicPermission(info, true);
5290        }
5291    }
5292
5293    @Override
5294    public void removePermission(String permName) {
5295        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5296    }
5297
5298    @Override
5299    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5300        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5301                getCallingUid(), userId, mPermissionCallback);
5302    }
5303
5304    @Override
5305    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5306        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5307                getCallingUid(), userId, mPermissionCallback);
5308    }
5309
5310    @Override
5311    public void resetRuntimePermissions() {
5312        mContext.enforceCallingOrSelfPermission(
5313                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5314                "revokeRuntimePermission");
5315
5316        int callingUid = Binder.getCallingUid();
5317        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5318            mContext.enforceCallingOrSelfPermission(
5319                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5320                    "resetRuntimePermissions");
5321        }
5322
5323        synchronized (mPackages) {
5324            mPermissionManager.updateAllPermissions(
5325                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5326                    mPermissionCallback);
5327            for (int userId : UserManagerService.getInstance().getUserIds()) {
5328                final int packageCount = mPackages.size();
5329                for (int i = 0; i < packageCount; i++) {
5330                    PackageParser.Package pkg = mPackages.valueAt(i);
5331                    if (!(pkg.mExtras instanceof PackageSetting)) {
5332                        continue;
5333                    }
5334                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5335                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5336                }
5337            }
5338        }
5339    }
5340
5341    @Override
5342    public int getPermissionFlags(String permName, String packageName, int userId) {
5343        return mPermissionManager.getPermissionFlags(
5344                permName, packageName, getCallingUid(), userId);
5345    }
5346
5347    @Override
5348    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5349            int flagValues, int userId) {
5350        mPermissionManager.updatePermissionFlags(
5351                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5352                mPermissionCallback);
5353    }
5354
5355    /**
5356     * Update the permission flags for all packages and runtime permissions of a user in order
5357     * to allow device or profile owner to remove POLICY_FIXED.
5358     */
5359    @Override
5360    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5361        synchronized (mPackages) {
5362            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5363                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5364                    mPermissionCallback);
5365            if (changed) {
5366                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5367            }
5368        }
5369    }
5370
5371    @Override
5372    public boolean shouldShowRequestPermissionRationale(String permissionName,
5373            String packageName, int userId) {
5374        if (UserHandle.getCallingUserId() != userId) {
5375            mContext.enforceCallingPermission(
5376                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5377                    "canShowRequestPermissionRationale for user " + userId);
5378        }
5379
5380        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5381        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5382            return false;
5383        }
5384
5385        if (checkPermission(permissionName, packageName, userId)
5386                == PackageManager.PERMISSION_GRANTED) {
5387            return false;
5388        }
5389
5390        final int flags;
5391
5392        final long identity = Binder.clearCallingIdentity();
5393        try {
5394            flags = getPermissionFlags(permissionName,
5395                    packageName, userId);
5396        } finally {
5397            Binder.restoreCallingIdentity(identity);
5398        }
5399
5400        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5401                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5402                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5403
5404        if ((flags & fixedFlags) != 0) {
5405            return false;
5406        }
5407
5408        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5409    }
5410
5411    @Override
5412    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5413        mContext.enforceCallingOrSelfPermission(
5414                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5415                "addOnPermissionsChangeListener");
5416
5417        synchronized (mPackages) {
5418            mOnPermissionChangeListeners.addListenerLocked(listener);
5419        }
5420    }
5421
5422    @Override
5423    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5424        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5425            throw new SecurityException("Instant applications don't have access to this method");
5426        }
5427        synchronized (mPackages) {
5428            mOnPermissionChangeListeners.removeListenerLocked(listener);
5429        }
5430    }
5431
5432    @Override
5433    public boolean isProtectedBroadcast(String actionName) {
5434        // allow instant applications
5435        synchronized (mProtectedBroadcasts) {
5436            if (mProtectedBroadcasts.contains(actionName)) {
5437                return true;
5438            } else if (actionName != null) {
5439                // TODO: remove these terrible hacks
5440                if (actionName.startsWith("android.net.netmon.lingerExpired")
5441                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5442                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5443                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5444                    return true;
5445                }
5446            }
5447        }
5448        return false;
5449    }
5450
5451    @Override
5452    public int checkSignatures(String pkg1, String pkg2) {
5453        synchronized (mPackages) {
5454            final PackageParser.Package p1 = mPackages.get(pkg1);
5455            final PackageParser.Package p2 = mPackages.get(pkg2);
5456            if (p1 == null || p1.mExtras == null
5457                    || p2 == null || p2.mExtras == null) {
5458                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5459            }
5460            final int callingUid = Binder.getCallingUid();
5461            final int callingUserId = UserHandle.getUserId(callingUid);
5462            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5463            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5464            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5465                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5466                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5467            }
5468            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5469        }
5470    }
5471
5472    @Override
5473    public int checkUidSignatures(int uid1, int uid2) {
5474        final int callingUid = Binder.getCallingUid();
5475        final int callingUserId = UserHandle.getUserId(callingUid);
5476        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5477        // Map to base uids.
5478        uid1 = UserHandle.getAppId(uid1);
5479        uid2 = UserHandle.getAppId(uid2);
5480        // reader
5481        synchronized (mPackages) {
5482            Signature[] s1;
5483            Signature[] s2;
5484            Object obj = mSettings.getUserIdLPr(uid1);
5485            if (obj != null) {
5486                if (obj instanceof SharedUserSetting) {
5487                    if (isCallerInstantApp) {
5488                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5489                    }
5490                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5491                } else if (obj instanceof PackageSetting) {
5492                    final PackageSetting ps = (PackageSetting) obj;
5493                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5494                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5495                    }
5496                    s1 = ps.signatures.mSigningDetails.signatures;
5497                } else {
5498                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5499                }
5500            } else {
5501                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5502            }
5503            obj = mSettings.getUserIdLPr(uid2);
5504            if (obj != null) {
5505                if (obj instanceof SharedUserSetting) {
5506                    if (isCallerInstantApp) {
5507                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5508                    }
5509                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5510                } else if (obj instanceof PackageSetting) {
5511                    final PackageSetting ps = (PackageSetting) obj;
5512                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5513                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5514                    }
5515                    s2 = ps.signatures.mSigningDetails.signatures;
5516                } else {
5517                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5518                }
5519            } else {
5520                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5521            }
5522            return compareSignatures(s1, s2);
5523        }
5524    }
5525
5526    @Override
5527    public boolean hasSigningCertificate(
5528            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5529
5530        synchronized (mPackages) {
5531            final PackageParser.Package p = mPackages.get(packageName);
5532            if (p == null || p.mExtras == null) {
5533                return false;
5534            }
5535            final int callingUid = Binder.getCallingUid();
5536            final int callingUserId = UserHandle.getUserId(callingUid);
5537            final PackageSetting ps = (PackageSetting) p.mExtras;
5538            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5539                return false;
5540            }
5541            switch (type) {
5542                case CERT_INPUT_RAW_X509:
5543                    return p.mSigningDetails.hasCertificate(certificate);
5544                case CERT_INPUT_SHA256:
5545                    return p.mSigningDetails.hasSha256Certificate(certificate);
5546                default:
5547                    return false;
5548            }
5549        }
5550    }
5551
5552    @Override
5553    public boolean hasUidSigningCertificate(
5554            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5555        final int callingUid = Binder.getCallingUid();
5556        final int callingUserId = UserHandle.getUserId(callingUid);
5557        // Map to base uids.
5558        uid = UserHandle.getAppId(uid);
5559        // reader
5560        synchronized (mPackages) {
5561            final PackageParser.SigningDetails signingDetails;
5562            final Object obj = mSettings.getUserIdLPr(uid);
5563            if (obj != null) {
5564                if (obj instanceof SharedUserSetting) {
5565                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5566                    if (isCallerInstantApp) {
5567                        return false;
5568                    }
5569                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5570                } else if (obj instanceof PackageSetting) {
5571                    final PackageSetting ps = (PackageSetting) obj;
5572                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5573                        return false;
5574                    }
5575                    signingDetails = ps.signatures.mSigningDetails;
5576                } else {
5577                    return false;
5578                }
5579            } else {
5580                return false;
5581            }
5582            switch (type) {
5583                case CERT_INPUT_RAW_X509:
5584                    return signingDetails.hasCertificate(certificate);
5585                case CERT_INPUT_SHA256:
5586                    return signingDetails.hasSha256Certificate(certificate);
5587                default:
5588                    return false;
5589            }
5590        }
5591    }
5592
5593    /**
5594     * This method should typically only be used when granting or revoking
5595     * permissions, since the app may immediately restart after this call.
5596     * <p>
5597     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5598     * guard your work against the app being relaunched.
5599     */
5600    private void killUid(int appId, int userId, String reason) {
5601        final long identity = Binder.clearCallingIdentity();
5602        try {
5603            IActivityManager am = ActivityManager.getService();
5604            if (am != null) {
5605                try {
5606                    am.killUid(appId, userId, reason);
5607                } catch (RemoteException e) {
5608                    /* ignore - same process */
5609                }
5610            }
5611        } finally {
5612            Binder.restoreCallingIdentity(identity);
5613        }
5614    }
5615
5616    /**
5617     * If the database version for this type of package (internal storage or
5618     * external storage) is less than the version where package signatures
5619     * were updated, return true.
5620     */
5621    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5622        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5623        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5624    }
5625
5626    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5627        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5628        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5629    }
5630
5631    @Override
5632    public List<String> getAllPackages() {
5633        final int callingUid = Binder.getCallingUid();
5634        final int callingUserId = UserHandle.getUserId(callingUid);
5635        synchronized (mPackages) {
5636            if (canViewInstantApps(callingUid, callingUserId)) {
5637                return new ArrayList<String>(mPackages.keySet());
5638            }
5639            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5640            final List<String> result = new ArrayList<>();
5641            if (instantAppPkgName != null) {
5642                // caller is an instant application; filter unexposed applications
5643                for (PackageParser.Package pkg : mPackages.values()) {
5644                    if (!pkg.visibleToInstantApps) {
5645                        continue;
5646                    }
5647                    result.add(pkg.packageName);
5648                }
5649            } else {
5650                // caller is a normal application; filter instant applications
5651                for (PackageParser.Package pkg : mPackages.values()) {
5652                    final PackageSetting ps =
5653                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5654                    if (ps != null
5655                            && ps.getInstantApp(callingUserId)
5656                            && !mInstantAppRegistry.isInstantAccessGranted(
5657                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5658                        continue;
5659                    }
5660                    result.add(pkg.packageName);
5661                }
5662            }
5663            return result;
5664        }
5665    }
5666
5667    @Override
5668    public String[] getPackagesForUid(int uid) {
5669        final int callingUid = Binder.getCallingUid();
5670        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5671        final int userId = UserHandle.getUserId(uid);
5672        uid = UserHandle.getAppId(uid);
5673        // reader
5674        synchronized (mPackages) {
5675            Object obj = mSettings.getUserIdLPr(uid);
5676            if (obj instanceof SharedUserSetting) {
5677                if (isCallerInstantApp) {
5678                    return null;
5679                }
5680                final SharedUserSetting sus = (SharedUserSetting) obj;
5681                final int N = sus.packages.size();
5682                String[] res = new String[N];
5683                final Iterator<PackageSetting> it = sus.packages.iterator();
5684                int i = 0;
5685                while (it.hasNext()) {
5686                    PackageSetting ps = it.next();
5687                    if (ps.getInstalled(userId)) {
5688                        res[i++] = ps.name;
5689                    } else {
5690                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5691                    }
5692                }
5693                return res;
5694            } else if (obj instanceof PackageSetting) {
5695                final PackageSetting ps = (PackageSetting) obj;
5696                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5697                    return new String[]{ps.name};
5698                }
5699            }
5700        }
5701        return null;
5702    }
5703
5704    @Override
5705    public String getNameForUid(int uid) {
5706        final int callingUid = Binder.getCallingUid();
5707        if (getInstantAppPackageName(callingUid) != null) {
5708            return null;
5709        }
5710        synchronized (mPackages) {
5711            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5712            if (obj instanceof SharedUserSetting) {
5713                final SharedUserSetting sus = (SharedUserSetting) obj;
5714                return sus.name + ":" + sus.userId;
5715            } else if (obj instanceof PackageSetting) {
5716                final PackageSetting ps = (PackageSetting) obj;
5717                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5718                    return null;
5719                }
5720                return ps.name;
5721            }
5722            return null;
5723        }
5724    }
5725
5726    @Override
5727    public String[] getNamesForUids(int[] uids) {
5728        if (uids == null || uids.length == 0) {
5729            return null;
5730        }
5731        final int callingUid = Binder.getCallingUid();
5732        if (getInstantAppPackageName(callingUid) != null) {
5733            return null;
5734        }
5735        final String[] names = new String[uids.length];
5736        synchronized (mPackages) {
5737            for (int i = uids.length - 1; i >= 0; i--) {
5738                final int uid = uids[i];
5739                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5740                if (obj instanceof SharedUserSetting) {
5741                    final SharedUserSetting sus = (SharedUserSetting) obj;
5742                    names[i] = "shared:" + sus.name;
5743                } else if (obj instanceof PackageSetting) {
5744                    final PackageSetting ps = (PackageSetting) obj;
5745                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5746                        names[i] = null;
5747                    } else {
5748                        names[i] = ps.name;
5749                    }
5750                } else {
5751                    names[i] = null;
5752                }
5753            }
5754        }
5755        return names;
5756    }
5757
5758    @Override
5759    public int getUidForSharedUser(String sharedUserName) {
5760        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5761            return -1;
5762        }
5763        if (sharedUserName == null) {
5764            return -1;
5765        }
5766        // reader
5767        synchronized (mPackages) {
5768            SharedUserSetting suid;
5769            try {
5770                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5771                if (suid != null) {
5772                    return suid.userId;
5773                }
5774            } catch (PackageManagerException ignore) {
5775                // can't happen, but, still need to catch it
5776            }
5777            return -1;
5778        }
5779    }
5780
5781    @Override
5782    public int getFlagsForUid(int uid) {
5783        final int callingUid = Binder.getCallingUid();
5784        if (getInstantAppPackageName(callingUid) != null) {
5785            return 0;
5786        }
5787        synchronized (mPackages) {
5788            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5789            if (obj instanceof SharedUserSetting) {
5790                final SharedUserSetting sus = (SharedUserSetting) obj;
5791                return sus.pkgFlags;
5792            } else if (obj instanceof PackageSetting) {
5793                final PackageSetting ps = (PackageSetting) obj;
5794                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5795                    return 0;
5796                }
5797                return ps.pkgFlags;
5798            }
5799        }
5800        return 0;
5801    }
5802
5803    @Override
5804    public int getPrivateFlagsForUid(int uid) {
5805        final int callingUid = Binder.getCallingUid();
5806        if (getInstantAppPackageName(callingUid) != null) {
5807            return 0;
5808        }
5809        synchronized (mPackages) {
5810            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5811            if (obj instanceof SharedUserSetting) {
5812                final SharedUserSetting sus = (SharedUserSetting) obj;
5813                return sus.pkgPrivateFlags;
5814            } else if (obj instanceof PackageSetting) {
5815                final PackageSetting ps = (PackageSetting) obj;
5816                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5817                    return 0;
5818                }
5819                return ps.pkgPrivateFlags;
5820            }
5821        }
5822        return 0;
5823    }
5824
5825    @Override
5826    public boolean isUidPrivileged(int uid) {
5827        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5828            return false;
5829        }
5830        uid = UserHandle.getAppId(uid);
5831        // reader
5832        synchronized (mPackages) {
5833            Object obj = mSettings.getUserIdLPr(uid);
5834            if (obj instanceof SharedUserSetting) {
5835                final SharedUserSetting sus = (SharedUserSetting) obj;
5836                final Iterator<PackageSetting> it = sus.packages.iterator();
5837                while (it.hasNext()) {
5838                    if (it.next().isPrivileged()) {
5839                        return true;
5840                    }
5841                }
5842            } else if (obj instanceof PackageSetting) {
5843                final PackageSetting ps = (PackageSetting) obj;
5844                return ps.isPrivileged();
5845            }
5846        }
5847        return false;
5848    }
5849
5850    @Override
5851    public String[] getAppOpPermissionPackages(String permName) {
5852        return mPermissionManager.getAppOpPermissionPackages(permName);
5853    }
5854
5855    @Override
5856    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5857            int flags, int userId) {
5858        return resolveIntentInternal(
5859                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5860    }
5861
5862    /**
5863     * Normally instant apps can only be resolved when they're visible to the caller.
5864     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5865     * since we need to allow the system to start any installed application.
5866     */
5867    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5868            int flags, int userId, boolean resolveForStart) {
5869        try {
5870            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5871
5872            if (!sUserManager.exists(userId)) return null;
5873            final int callingUid = Binder.getCallingUid();
5874            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5875            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5876                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5877
5878            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5879            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5880                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5881            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5882
5883            final ResolveInfo bestChoice =
5884                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5885            return bestChoice;
5886        } finally {
5887            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5888        }
5889    }
5890
5891    @Override
5892    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5893        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5894            throw new SecurityException(
5895                    "findPersistentPreferredActivity can only be run by the system");
5896        }
5897        if (!sUserManager.exists(userId)) {
5898            return null;
5899        }
5900        final int callingUid = Binder.getCallingUid();
5901        intent = updateIntentForResolve(intent);
5902        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5903        final int flags = updateFlagsForResolve(
5904                0, userId, intent, callingUid, false /*includeInstantApps*/);
5905        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5906                userId);
5907        synchronized (mPackages) {
5908            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5909                    userId);
5910        }
5911    }
5912
5913    @Override
5914    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5915            IntentFilter filter, int match, ComponentName activity) {
5916        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5917            return;
5918        }
5919        final int userId = UserHandle.getCallingUserId();
5920        if (DEBUG_PREFERRED) {
5921            Log.v(TAG, "setLastChosenActivity intent=" + intent
5922                + " resolvedType=" + resolvedType
5923                + " flags=" + flags
5924                + " filter=" + filter
5925                + " match=" + match
5926                + " activity=" + activity);
5927            filter.dump(new PrintStreamPrinter(System.out), "    ");
5928        }
5929        intent.setComponent(null);
5930        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5931                userId);
5932        // Find any earlier preferred or last chosen entries and nuke them
5933        findPreferredActivity(intent, resolvedType,
5934                flags, query, 0, false, true, false, userId);
5935        // Add the new activity as the last chosen for this filter
5936        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5937                "Setting last chosen");
5938    }
5939
5940    @Override
5941    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5942        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5943            return null;
5944        }
5945        final int userId = UserHandle.getCallingUserId();
5946        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5947        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5948                userId);
5949        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5950                false, false, false, userId);
5951    }
5952
5953    /**
5954     * Returns whether or not instant apps have been disabled remotely.
5955     */
5956    private boolean areWebInstantAppsDisabled() {
5957        return mWebInstantAppsDisabled;
5958    }
5959
5960    private boolean isInstantAppResolutionAllowed(
5961            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5962            boolean skipPackageCheck) {
5963        if (mInstantAppResolverConnection == null) {
5964            return false;
5965        }
5966        if (mInstantAppInstallerActivity == null) {
5967            return false;
5968        }
5969        if (intent.getComponent() != null) {
5970            return false;
5971        }
5972        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5973            return false;
5974        }
5975        if (!skipPackageCheck && intent.getPackage() != null) {
5976            return false;
5977        }
5978        if (!intent.isWebIntent()) {
5979            // for non web intents, we should not resolve externally if an app already exists to
5980            // handle it or if the caller didn't explicitly request it.
5981            if ((resolvedActivities != null && resolvedActivities.size() != 0)
5982                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
5983                return false;
5984            }
5985        } else {
5986            if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
5987                return false;
5988            } else if (areWebInstantAppsDisabled()) {
5989                return false;
5990            }
5991        }
5992        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5993        // Or if there's already an ephemeral app installed that handles the action
5994        synchronized (mPackages) {
5995            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5996            for (int n = 0; n < count; n++) {
5997                final ResolveInfo info = resolvedActivities.get(n);
5998                final String packageName = info.activityInfo.packageName;
5999                final PackageSetting ps = mSettings.mPackages.get(packageName);
6000                if (ps != null) {
6001                    // only check domain verification status if the app is not a browser
6002                    if (!info.handleAllWebDataURI) {
6003                        // Try to get the status from User settings first
6004                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6005                        final int status = (int) (packedStatus >> 32);
6006                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6007                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6008                            if (DEBUG_INSTANT) {
6009                                Slog.v(TAG, "DENY instant app;"
6010                                    + " pkg: " + packageName + ", status: " + status);
6011                            }
6012                            return false;
6013                        }
6014                    }
6015                    if (ps.getInstantApp(userId)) {
6016                        if (DEBUG_INSTANT) {
6017                            Slog.v(TAG, "DENY instant app installed;"
6018                                    + " pkg: " + packageName);
6019                        }
6020                        return false;
6021                    }
6022                }
6023            }
6024        }
6025        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6026        return true;
6027    }
6028
6029    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6030            Intent origIntent, String resolvedType, String callingPackage,
6031            Bundle verificationBundle, int userId) {
6032        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6033                new InstantAppRequest(responseObj, origIntent, resolvedType,
6034                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6035        mHandler.sendMessage(msg);
6036    }
6037
6038    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6039            int flags, List<ResolveInfo> query, int userId) {
6040        if (query != null) {
6041            final int N = query.size();
6042            if (N == 1) {
6043                return query.get(0);
6044            } else if (N > 1) {
6045                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6046                // If there is more than one activity with the same priority,
6047                // then let the user decide between them.
6048                ResolveInfo r0 = query.get(0);
6049                ResolveInfo r1 = query.get(1);
6050                if (DEBUG_INTENT_MATCHING || debug) {
6051                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6052                            + r1.activityInfo.name + "=" + r1.priority);
6053                }
6054                // If the first activity has a higher priority, or a different
6055                // default, then it is always desirable to pick it.
6056                if (r0.priority != r1.priority
6057                        || r0.preferredOrder != r1.preferredOrder
6058                        || r0.isDefault != r1.isDefault) {
6059                    return query.get(0);
6060                }
6061                // If we have saved a preference for a preferred activity for
6062                // this Intent, use that.
6063                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6064                        flags, query, r0.priority, true, false, debug, userId);
6065                if (ri != null) {
6066                    return ri;
6067                }
6068                // If we have an ephemeral app, use it
6069                for (int i = 0; i < N; i++) {
6070                    ri = query.get(i);
6071                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6072                        final String packageName = ri.activityInfo.packageName;
6073                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6074                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6075                        final int status = (int)(packedStatus >> 32);
6076                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6077                            return ri;
6078                        }
6079                    }
6080                }
6081                ri = new ResolveInfo(mResolveInfo);
6082                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6083                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6084                // If all of the options come from the same package, show the application's
6085                // label and icon instead of the generic resolver's.
6086                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6087                // and then throw away the ResolveInfo itself, meaning that the caller loses
6088                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6089                // a fallback for this case; we only set the target package's resources on
6090                // the ResolveInfo, not the ActivityInfo.
6091                final String intentPackage = intent.getPackage();
6092                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6093                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6094                    ri.resolvePackageName = intentPackage;
6095                    if (userNeedsBadging(userId)) {
6096                        ri.noResourceId = true;
6097                    } else {
6098                        ri.icon = appi.icon;
6099                    }
6100                    ri.iconResourceId = appi.icon;
6101                    ri.labelRes = appi.labelRes;
6102                }
6103                ri.activityInfo.applicationInfo = new ApplicationInfo(
6104                        ri.activityInfo.applicationInfo);
6105                if (userId != 0) {
6106                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6107                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6108                }
6109                // Make sure that the resolver is displayable in car mode
6110                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6111                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6112                return ri;
6113            }
6114        }
6115        return null;
6116    }
6117
6118    /**
6119     * Return true if the given list is not empty and all of its contents have
6120     * an activityInfo with the given package name.
6121     */
6122    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6123        if (ArrayUtils.isEmpty(list)) {
6124            return false;
6125        }
6126        for (int i = 0, N = list.size(); i < N; i++) {
6127            final ResolveInfo ri = list.get(i);
6128            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6129            if (ai == null || !packageName.equals(ai.packageName)) {
6130                return false;
6131            }
6132        }
6133        return true;
6134    }
6135
6136    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6137            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6138        final int N = query.size();
6139        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6140                .get(userId);
6141        // Get the list of persistent preferred activities that handle the intent
6142        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6143        List<PersistentPreferredActivity> pprefs = ppir != null
6144                ? ppir.queryIntent(intent, resolvedType,
6145                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6146                        userId)
6147                : null;
6148        if (pprefs != null && pprefs.size() > 0) {
6149            final int M = pprefs.size();
6150            for (int i=0; i<M; i++) {
6151                final PersistentPreferredActivity ppa = pprefs.get(i);
6152                if (DEBUG_PREFERRED || debug) {
6153                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6154                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6155                            + "\n  component=" + ppa.mComponent);
6156                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6157                }
6158                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6159                        flags | MATCH_DISABLED_COMPONENTS, userId);
6160                if (DEBUG_PREFERRED || debug) {
6161                    Slog.v(TAG, "Found persistent preferred activity:");
6162                    if (ai != null) {
6163                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6164                    } else {
6165                        Slog.v(TAG, "  null");
6166                    }
6167                }
6168                if (ai == null) {
6169                    // This previously registered persistent preferred activity
6170                    // component is no longer known. Ignore it and do NOT remove it.
6171                    continue;
6172                }
6173                for (int j=0; j<N; j++) {
6174                    final ResolveInfo ri = query.get(j);
6175                    if (!ri.activityInfo.applicationInfo.packageName
6176                            .equals(ai.applicationInfo.packageName)) {
6177                        continue;
6178                    }
6179                    if (!ri.activityInfo.name.equals(ai.name)) {
6180                        continue;
6181                    }
6182                    //  Found a persistent preference that can handle the intent.
6183                    if (DEBUG_PREFERRED || debug) {
6184                        Slog.v(TAG, "Returning persistent preferred activity: " +
6185                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6186                    }
6187                    return ri;
6188                }
6189            }
6190        }
6191        return null;
6192    }
6193
6194    // TODO: handle preferred activities missing while user has amnesia
6195    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6196            List<ResolveInfo> query, int priority, boolean always,
6197            boolean removeMatches, boolean debug, int userId) {
6198        if (!sUserManager.exists(userId)) return null;
6199        final int callingUid = Binder.getCallingUid();
6200        flags = updateFlagsForResolve(
6201                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6202        intent = updateIntentForResolve(intent);
6203        // writer
6204        synchronized (mPackages) {
6205            // Try to find a matching persistent preferred activity.
6206            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6207                    debug, userId);
6208
6209            // If a persistent preferred activity matched, use it.
6210            if (pri != null) {
6211                return pri;
6212            }
6213
6214            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6215            // Get the list of preferred activities that handle the intent
6216            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6217            List<PreferredActivity> prefs = pir != null
6218                    ? pir.queryIntent(intent, resolvedType,
6219                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6220                            userId)
6221                    : null;
6222            if (prefs != null && prefs.size() > 0) {
6223                boolean changed = false;
6224                try {
6225                    // First figure out how good the original match set is.
6226                    // We will only allow preferred activities that came
6227                    // from the same match quality.
6228                    int match = 0;
6229
6230                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6231
6232                    final int N = query.size();
6233                    for (int j=0; j<N; j++) {
6234                        final ResolveInfo ri = query.get(j);
6235                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6236                                + ": 0x" + Integer.toHexString(match));
6237                        if (ri.match > match) {
6238                            match = ri.match;
6239                        }
6240                    }
6241
6242                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6243                            + Integer.toHexString(match));
6244
6245                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6246                    final int M = prefs.size();
6247                    for (int i=0; i<M; i++) {
6248                        final PreferredActivity pa = prefs.get(i);
6249                        if (DEBUG_PREFERRED || debug) {
6250                            Slog.v(TAG, "Checking PreferredActivity ds="
6251                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6252                                    + "\n  component=" + pa.mPref.mComponent);
6253                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6254                        }
6255                        if (pa.mPref.mMatch != match) {
6256                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6257                                    + Integer.toHexString(pa.mPref.mMatch));
6258                            continue;
6259                        }
6260                        // If it's not an "always" type preferred activity and that's what we're
6261                        // looking for, skip it.
6262                        if (always && !pa.mPref.mAlways) {
6263                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6264                            continue;
6265                        }
6266                        final ActivityInfo ai = getActivityInfo(
6267                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6268                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6269                                userId);
6270                        if (DEBUG_PREFERRED || debug) {
6271                            Slog.v(TAG, "Found preferred activity:");
6272                            if (ai != null) {
6273                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6274                            } else {
6275                                Slog.v(TAG, "  null");
6276                            }
6277                        }
6278                        if (ai == null) {
6279                            // This previously registered preferred activity
6280                            // component is no longer known.  Most likely an update
6281                            // to the app was installed and in the new version this
6282                            // component no longer exists.  Clean it up by removing
6283                            // it from the preferred activities list, and skip it.
6284                            Slog.w(TAG, "Removing dangling preferred activity: "
6285                                    + pa.mPref.mComponent);
6286                            pir.removeFilter(pa);
6287                            changed = true;
6288                            continue;
6289                        }
6290                        for (int j=0; j<N; j++) {
6291                            final ResolveInfo ri = query.get(j);
6292                            if (!ri.activityInfo.applicationInfo.packageName
6293                                    .equals(ai.applicationInfo.packageName)) {
6294                                continue;
6295                            }
6296                            if (!ri.activityInfo.name.equals(ai.name)) {
6297                                continue;
6298                            }
6299
6300                            if (removeMatches) {
6301                                pir.removeFilter(pa);
6302                                changed = true;
6303                                if (DEBUG_PREFERRED) {
6304                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6305                                }
6306                                break;
6307                            }
6308
6309                            // Okay we found a previously set preferred or last chosen app.
6310                            // If the result set is different from when this
6311                            // was created, and is not a subset of the preferred set, we need to
6312                            // clear it and re-ask the user their preference, if we're looking for
6313                            // an "always" type entry.
6314                            if (always && !pa.mPref.sameSet(query)) {
6315                                if (pa.mPref.isSuperset(query)) {
6316                                    // some components of the set are no longer present in
6317                                    // the query, but the preferred activity can still be reused
6318                                    if (DEBUG_PREFERRED) {
6319                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6320                                                + " still valid as only non-preferred components"
6321                                                + " were removed for " + intent + " type "
6322                                                + resolvedType);
6323                                    }
6324                                    // remove obsolete components and re-add the up-to-date filter
6325                                    PreferredActivity freshPa = new PreferredActivity(pa,
6326                                            pa.mPref.mMatch,
6327                                            pa.mPref.discardObsoleteComponents(query),
6328                                            pa.mPref.mComponent,
6329                                            pa.mPref.mAlways);
6330                                    pir.removeFilter(pa);
6331                                    pir.addFilter(freshPa);
6332                                    changed = true;
6333                                } else {
6334                                    Slog.i(TAG,
6335                                            "Result set changed, dropping preferred activity for "
6336                                                    + intent + " type " + resolvedType);
6337                                    if (DEBUG_PREFERRED) {
6338                                        Slog.v(TAG, "Removing preferred activity since set changed "
6339                                                + pa.mPref.mComponent);
6340                                    }
6341                                    pir.removeFilter(pa);
6342                                    // Re-add the filter as a "last chosen" entry (!always)
6343                                    PreferredActivity lastChosen = new PreferredActivity(
6344                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6345                                    pir.addFilter(lastChosen);
6346                                    changed = true;
6347                                    return null;
6348                                }
6349                            }
6350
6351                            // Yay! Either the set matched or we're looking for the last chosen
6352                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6353                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6354                            return ri;
6355                        }
6356                    }
6357                } finally {
6358                    if (changed) {
6359                        if (DEBUG_PREFERRED) {
6360                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6361                        }
6362                        scheduleWritePackageRestrictionsLocked(userId);
6363                    }
6364                }
6365            }
6366        }
6367        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6368        return null;
6369    }
6370
6371    /*
6372     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6373     */
6374    @Override
6375    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6376            int targetUserId) {
6377        mContext.enforceCallingOrSelfPermission(
6378                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6379        List<CrossProfileIntentFilter> matches =
6380                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6381        if (matches != null) {
6382            int size = matches.size();
6383            for (int i = 0; i < size; i++) {
6384                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6385            }
6386        }
6387        if (intent.hasWebURI()) {
6388            // cross-profile app linking works only towards the parent.
6389            final int callingUid = Binder.getCallingUid();
6390            final UserInfo parent = getProfileParent(sourceUserId);
6391            synchronized(mPackages) {
6392                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6393                        false /*includeInstantApps*/);
6394                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6395                        intent, resolvedType, flags, sourceUserId, parent.id);
6396                return xpDomainInfo != null;
6397            }
6398        }
6399        return false;
6400    }
6401
6402    private UserInfo getProfileParent(int userId) {
6403        final long identity = Binder.clearCallingIdentity();
6404        try {
6405            return sUserManager.getProfileParent(userId);
6406        } finally {
6407            Binder.restoreCallingIdentity(identity);
6408        }
6409    }
6410
6411    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6412            String resolvedType, int userId) {
6413        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6414        if (resolver != null) {
6415            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6416        }
6417        return null;
6418    }
6419
6420    @Override
6421    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6422            String resolvedType, int flags, int userId) {
6423        try {
6424            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6425
6426            return new ParceledListSlice<>(
6427                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6428        } finally {
6429            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6430        }
6431    }
6432
6433    /**
6434     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6435     * instant, returns {@code null}.
6436     */
6437    private String getInstantAppPackageName(int callingUid) {
6438        synchronized (mPackages) {
6439            // If the caller is an isolated app use the owner's uid for the lookup.
6440            if (Process.isIsolated(callingUid)) {
6441                callingUid = mIsolatedOwners.get(callingUid);
6442            }
6443            final int appId = UserHandle.getAppId(callingUid);
6444            final Object obj = mSettings.getUserIdLPr(appId);
6445            if (obj instanceof PackageSetting) {
6446                final PackageSetting ps = (PackageSetting) obj;
6447                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6448                return isInstantApp ? ps.pkg.packageName : null;
6449            }
6450        }
6451        return null;
6452    }
6453
6454    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6455            String resolvedType, int flags, int userId) {
6456        return queryIntentActivitiesInternal(
6457                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6458                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6459    }
6460
6461    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6462            String resolvedType, int flags, int filterCallingUid, int userId,
6463            boolean resolveForStart, boolean allowDynamicSplits) {
6464        if (!sUserManager.exists(userId)) return Collections.emptyList();
6465        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6466        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6467                false /* requireFullPermission */, false /* checkShell */,
6468                "query intent activities");
6469        final String pkgName = intent.getPackage();
6470        ComponentName comp = intent.getComponent();
6471        if (comp == null) {
6472            if (intent.getSelector() != null) {
6473                intent = intent.getSelector();
6474                comp = intent.getComponent();
6475            }
6476        }
6477
6478        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6479                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6480        if (comp != null) {
6481            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6482            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6483            if (ai != null) {
6484                // When specifying an explicit component, we prevent the activity from being
6485                // used when either 1) the calling package is normal and the activity is within
6486                // an ephemeral application or 2) the calling package is ephemeral and the
6487                // activity is not visible to ephemeral applications.
6488                final boolean matchInstantApp =
6489                        (flags & PackageManager.MATCH_INSTANT) != 0;
6490                final boolean matchVisibleToInstantAppOnly =
6491                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6492                final boolean matchExplicitlyVisibleOnly =
6493                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6494                final boolean isCallerInstantApp =
6495                        instantAppPkgName != null;
6496                final boolean isTargetSameInstantApp =
6497                        comp.getPackageName().equals(instantAppPkgName);
6498                final boolean isTargetInstantApp =
6499                        (ai.applicationInfo.privateFlags
6500                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6501                final boolean isTargetVisibleToInstantApp =
6502                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6503                final boolean isTargetExplicitlyVisibleToInstantApp =
6504                        isTargetVisibleToInstantApp
6505                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6506                final boolean isTargetHiddenFromInstantApp =
6507                        !isTargetVisibleToInstantApp
6508                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6509                final boolean blockResolution =
6510                        !isTargetSameInstantApp
6511                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6512                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6513                                        && isTargetHiddenFromInstantApp));
6514                if (!blockResolution) {
6515                    final ResolveInfo ri = new ResolveInfo();
6516                    ri.activityInfo = ai;
6517                    list.add(ri);
6518                }
6519            }
6520            return applyPostResolutionFilter(
6521                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6522        }
6523
6524        // reader
6525        boolean sortResult = false;
6526        boolean addInstant = false;
6527        List<ResolveInfo> result;
6528        synchronized (mPackages) {
6529            if (pkgName == null) {
6530                List<CrossProfileIntentFilter> matchingFilters =
6531                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6532                // Check for results that need to skip the current profile.
6533                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6534                        resolvedType, flags, userId);
6535                if (xpResolveInfo != null) {
6536                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6537                    xpResult.add(xpResolveInfo);
6538                    return applyPostResolutionFilter(
6539                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6540                            allowDynamicSplits, filterCallingUid, userId, intent);
6541                }
6542
6543                // Check for results in the current profile.
6544                result = filterIfNotSystemUser(mActivities.queryIntent(
6545                        intent, resolvedType, flags, userId), userId);
6546                addInstant = isInstantAppResolutionAllowed(intent, result, userId,
6547                        false /*skipPackageCheck*/);
6548                // Check for cross profile results.
6549                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6550                xpResolveInfo = queryCrossProfileIntents(
6551                        matchingFilters, intent, resolvedType, flags, userId,
6552                        hasNonNegativePriorityResult);
6553                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6554                    boolean isVisibleToUser = filterIfNotSystemUser(
6555                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6556                    if (isVisibleToUser) {
6557                        result.add(xpResolveInfo);
6558                        sortResult = true;
6559                    }
6560                }
6561                if (intent.hasWebURI()) {
6562                    CrossProfileDomainInfo xpDomainInfo = null;
6563                    final UserInfo parent = getProfileParent(userId);
6564                    if (parent != null) {
6565                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6566                                flags, userId, parent.id);
6567                    }
6568                    if (xpDomainInfo != null) {
6569                        if (xpResolveInfo != null) {
6570                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6571                            // in the result.
6572                            result.remove(xpResolveInfo);
6573                        }
6574                        if (result.size() == 0 && !addInstant) {
6575                            // No result in current profile, but found candidate in parent user.
6576                            // And we are not going to add emphemeral app, so we can return the
6577                            // result straight away.
6578                            result.add(xpDomainInfo.resolveInfo);
6579                            return applyPostResolutionFilter(result, instantAppPkgName,
6580                                    allowDynamicSplits, filterCallingUid, userId, intent);
6581                        }
6582                    } else if (result.size() <= 1 && !addInstant) {
6583                        // No result in parent user and <= 1 result in current profile, and we
6584                        // are not going to add emphemeral app, so we can return the result without
6585                        // further processing.
6586                        return applyPostResolutionFilter(result, instantAppPkgName,
6587                                allowDynamicSplits, filterCallingUid, userId, intent);
6588                    }
6589                    // We have more than one candidate (combining results from current and parent
6590                    // profile), so we need filtering and sorting.
6591                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6592                            intent, flags, result, xpDomainInfo, userId);
6593                    sortResult = true;
6594                }
6595            } else {
6596                final PackageParser.Package pkg = mPackages.get(pkgName);
6597                result = null;
6598                if (pkg != null) {
6599                    result = filterIfNotSystemUser(
6600                            mActivities.queryIntentForPackage(
6601                                    intent, resolvedType, flags, pkg.activities, userId),
6602                            userId);
6603                }
6604                if (result == null || result.size() == 0) {
6605                    // the caller wants to resolve for a particular package; however, there
6606                    // were no installed results, so, try to find an ephemeral result
6607                    addInstant = isInstantAppResolutionAllowed(
6608                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6609                    if (result == null) {
6610                        result = new ArrayList<>();
6611                    }
6612                }
6613            }
6614        }
6615        if (addInstant) {
6616            result = maybeAddInstantAppInstaller(
6617                    result, intent, resolvedType, flags, userId, resolveForStart);
6618        }
6619        if (sortResult) {
6620            Collections.sort(result, mResolvePrioritySorter);
6621        }
6622        return applyPostResolutionFilter(
6623                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6624    }
6625
6626    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6627            String resolvedType, int flags, int userId, boolean resolveForStart) {
6628        // first, check to see if we've got an instant app already installed
6629        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6630        ResolveInfo localInstantApp = null;
6631        boolean blockResolution = false;
6632        if (!alreadyResolvedLocally) {
6633            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6634                    flags
6635                        | PackageManager.GET_RESOLVED_FILTER
6636                        | PackageManager.MATCH_INSTANT
6637                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6638                    userId);
6639            for (int i = instantApps.size() - 1; i >= 0; --i) {
6640                final ResolveInfo info = instantApps.get(i);
6641                final String packageName = info.activityInfo.packageName;
6642                final PackageSetting ps = mSettings.mPackages.get(packageName);
6643                if (ps.getInstantApp(userId)) {
6644                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6645                    final int status = (int)(packedStatus >> 32);
6646                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6647                        // there's a local instant application installed, but, the user has
6648                        // chosen to never use it; skip resolution and don't acknowledge
6649                        // an instant application is even available
6650                        if (DEBUG_INSTANT) {
6651                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6652                        }
6653                        blockResolution = true;
6654                        break;
6655                    } else {
6656                        // we have a locally installed instant application; skip resolution
6657                        // but acknowledge there's an instant application available
6658                        if (DEBUG_INSTANT) {
6659                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6660                        }
6661                        localInstantApp = info;
6662                        break;
6663                    }
6664                }
6665            }
6666        }
6667        // no app installed, let's see if one's available
6668        AuxiliaryResolveInfo auxiliaryResponse = null;
6669        if (!blockResolution) {
6670            if (localInstantApp == null) {
6671                // we don't have an instant app locally, resolve externally
6672                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6673                final InstantAppRequest requestObject = new InstantAppRequest(
6674                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6675                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6676                        resolveForStart);
6677                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6678                        mInstantAppResolverConnection, requestObject);
6679                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6680            } else {
6681                // we have an instant application locally, but, we can't admit that since
6682                // callers shouldn't be able to determine prior browsing. create a dummy
6683                // auxiliary response so the downstream code behaves as if there's an
6684                // instant application available externally. when it comes time to start
6685                // the instant application, we'll do the right thing.
6686                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6687                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6688                                        ai.packageName, ai.versionCode, null /* splitName */);
6689            }
6690        }
6691        if (intent.isWebIntent() && auxiliaryResponse == null) {
6692            return result;
6693        }
6694        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6695        if (ps == null) {
6696            return result;
6697        }
6698        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6699        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6700                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6701        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6702                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6703        // add a non-generic filter
6704        ephemeralInstaller.filter = new IntentFilter();
6705        if (intent.getAction() != null) {
6706            ephemeralInstaller.filter.addAction(intent.getAction());
6707        }
6708        if (intent.getData() != null && intent.getData().getPath() != null) {
6709            ephemeralInstaller.filter.addDataPath(
6710                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6711        }
6712        ephemeralInstaller.isInstantAppAvailable = true;
6713        // make sure this resolver is the default
6714        ephemeralInstaller.isDefault = true;
6715        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6716        if (DEBUG_INSTANT) {
6717            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6718        }
6719
6720        result.add(ephemeralInstaller);
6721        return result;
6722    }
6723
6724    private static class CrossProfileDomainInfo {
6725        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6726        ResolveInfo resolveInfo;
6727        /* Best domain verification status of the activities found in the other profile */
6728        int bestDomainVerificationStatus;
6729    }
6730
6731    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6732            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6733        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6734                sourceUserId)) {
6735            return null;
6736        }
6737        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6738                resolvedType, flags, parentUserId);
6739
6740        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6741            return null;
6742        }
6743        CrossProfileDomainInfo result = null;
6744        int size = resultTargetUser.size();
6745        for (int i = 0; i < size; i++) {
6746            ResolveInfo riTargetUser = resultTargetUser.get(i);
6747            // Intent filter verification is only for filters that specify a host. So don't return
6748            // those that handle all web uris.
6749            if (riTargetUser.handleAllWebDataURI) {
6750                continue;
6751            }
6752            String packageName = riTargetUser.activityInfo.packageName;
6753            PackageSetting ps = mSettings.mPackages.get(packageName);
6754            if (ps == null) {
6755                continue;
6756            }
6757            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6758            int status = (int)(verificationState >> 32);
6759            if (result == null) {
6760                result = new CrossProfileDomainInfo();
6761                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6762                        sourceUserId, parentUserId);
6763                result.bestDomainVerificationStatus = status;
6764            } else {
6765                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6766                        result.bestDomainVerificationStatus);
6767            }
6768        }
6769        // Don't consider matches with status NEVER across profiles.
6770        if (result != null && result.bestDomainVerificationStatus
6771                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6772            return null;
6773        }
6774        return result;
6775    }
6776
6777    /**
6778     * Verification statuses are ordered from the worse to the best, except for
6779     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6780     */
6781    private int bestDomainVerificationStatus(int status1, int status2) {
6782        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6783            return status2;
6784        }
6785        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6786            return status1;
6787        }
6788        return (int) MathUtils.max(status1, status2);
6789    }
6790
6791    private boolean isUserEnabled(int userId) {
6792        long callingId = Binder.clearCallingIdentity();
6793        try {
6794            UserInfo userInfo = sUserManager.getUserInfo(userId);
6795            return userInfo != null && userInfo.isEnabled();
6796        } finally {
6797            Binder.restoreCallingIdentity(callingId);
6798        }
6799    }
6800
6801    /**
6802     * Filter out activities with systemUserOnly flag set, when current user is not System.
6803     *
6804     * @return filtered list
6805     */
6806    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6807        if (userId == UserHandle.USER_SYSTEM) {
6808            return resolveInfos;
6809        }
6810        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6811            ResolveInfo info = resolveInfos.get(i);
6812            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6813                resolveInfos.remove(i);
6814            }
6815        }
6816        return resolveInfos;
6817    }
6818
6819    /**
6820     * Filters out ephemeral activities.
6821     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6822     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6823     *
6824     * @param resolveInfos The pre-filtered list of resolved activities
6825     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6826     *          is performed.
6827     * @param intent
6828     * @return A filtered list of resolved activities.
6829     */
6830    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6831            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId,
6832            Intent intent) {
6833        final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled();
6834        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6835            final ResolveInfo info = resolveInfos.get(i);
6836            // remove locally resolved instant app web results when disabled
6837            if (info.isInstantAppAvailable && blockInstant) {
6838                resolveInfos.remove(i);
6839                continue;
6840            }
6841            // allow activities that are defined in the provided package
6842            if (allowDynamicSplits
6843                    && info.activityInfo != null
6844                    && info.activityInfo.splitName != null
6845                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6846                            info.activityInfo.splitName)) {
6847                if (mInstantAppInstallerActivity == null) {
6848                    if (DEBUG_INSTALL) {
6849                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6850                    }
6851                    resolveInfos.remove(i);
6852                    continue;
6853                }
6854                // requested activity is defined in a split that hasn't been installed yet.
6855                // add the installer to the resolve list
6856                if (DEBUG_INSTALL) {
6857                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6858                }
6859                final ResolveInfo installerInfo = new ResolveInfo(
6860                        mInstantAppInstallerInfo);
6861                final ComponentName installFailureActivity = findInstallFailureActivity(
6862                        info.activityInfo.packageName,  filterCallingUid, userId);
6863                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6864                        installFailureActivity,
6865                        info.activityInfo.packageName,
6866                        info.activityInfo.applicationInfo.versionCode,
6867                        info.activityInfo.splitName);
6868                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6869                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6870                // add a non-generic filter
6871                installerInfo.filter = new IntentFilter();
6872
6873                // This resolve info may appear in the chooser UI, so let us make it
6874                // look as the one it replaces as far as the user is concerned which
6875                // requires loading the correct label and icon for the resolve info.
6876                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6877                installerInfo.labelRes = info.resolveLabelResId();
6878                installerInfo.icon = info.resolveIconResId();
6879
6880                // propagate priority/preferred order/default
6881                installerInfo.priority = info.priority;
6882                installerInfo.preferredOrder = info.preferredOrder;
6883                installerInfo.isDefault = info.isDefault;
6884                installerInfo.isInstantAppAvailable = true;
6885                resolveInfos.set(i, installerInfo);
6886                continue;
6887            }
6888            // caller is a full app, don't need to apply any other filtering
6889            if (ephemeralPkgName == null) {
6890                continue;
6891            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6892                // caller is same app; don't need to apply any other filtering
6893                continue;
6894            }
6895            // allow activities that have been explicitly exposed to ephemeral apps
6896            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6897            if (!isEphemeralApp
6898                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6899                continue;
6900            }
6901            resolveInfos.remove(i);
6902        }
6903        return resolveInfos;
6904    }
6905
6906    /**
6907     * Returns the activity component that can handle install failures.
6908     * <p>By default, the instant application installer handles failures. However, an
6909     * application may want to handle failures on its own. Applications do this by
6910     * creating an activity with an intent filter that handles the action
6911     * {@link Intent#ACTION_INSTALL_FAILURE}.
6912     */
6913    private @Nullable ComponentName findInstallFailureActivity(
6914            String packageName, int filterCallingUid, int userId) {
6915        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6916        failureActivityIntent.setPackage(packageName);
6917        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6918        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6919                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6920                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6921        final int NR = result.size();
6922        if (NR > 0) {
6923            for (int i = 0; i < NR; i++) {
6924                final ResolveInfo info = result.get(i);
6925                if (info.activityInfo.splitName != null) {
6926                    continue;
6927                }
6928                return new ComponentName(packageName, info.activityInfo.name);
6929            }
6930        }
6931        return null;
6932    }
6933
6934    /**
6935     * @param resolveInfos list of resolve infos in descending priority order
6936     * @return if the list contains a resolve info with non-negative priority
6937     */
6938    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6939        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6940    }
6941
6942    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6943            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6944            int userId) {
6945        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6946
6947        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6948            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6949                    candidates.size());
6950        }
6951
6952        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6953        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6954        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6955        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6956        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6957        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6958
6959        synchronized (mPackages) {
6960            final int count = candidates.size();
6961            // First, try to use linked apps. Partition the candidates into four lists:
6962            // one for the final results, one for the "do not use ever", one for "undefined status"
6963            // and finally one for "browser app type".
6964            for (int n=0; n<count; n++) {
6965                ResolveInfo info = candidates.get(n);
6966                String packageName = info.activityInfo.packageName;
6967                PackageSetting ps = mSettings.mPackages.get(packageName);
6968                if (ps != null) {
6969                    // Add to the special match all list (Browser use case)
6970                    if (info.handleAllWebDataURI) {
6971                        matchAllList.add(info);
6972                        continue;
6973                    }
6974                    // Try to get the status from User settings first
6975                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6976                    int status = (int)(packedStatus >> 32);
6977                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6978                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6979                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6980                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6981                                    + " : linkgen=" + linkGeneration);
6982                        }
6983                        // Use link-enabled generation as preferredOrder, i.e.
6984                        // prefer newly-enabled over earlier-enabled.
6985                        info.preferredOrder = linkGeneration;
6986                        alwaysList.add(info);
6987                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6988                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6989                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6990                        }
6991                        neverList.add(info);
6992                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6993                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6994                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6995                        }
6996                        alwaysAskList.add(info);
6997                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6998                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6999                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7000                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7001                        }
7002                        undefinedList.add(info);
7003                    }
7004                }
7005            }
7006
7007            // We'll want to include browser possibilities in a few cases
7008            boolean includeBrowser = false;
7009
7010            // First try to add the "always" resolution(s) for the current user, if any
7011            if (alwaysList.size() > 0) {
7012                result.addAll(alwaysList);
7013            } else {
7014                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7015                result.addAll(undefinedList);
7016                // Maybe add one for the other profile.
7017                if (xpDomainInfo != null && (
7018                        xpDomainInfo.bestDomainVerificationStatus
7019                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7020                    result.add(xpDomainInfo.resolveInfo);
7021                }
7022                includeBrowser = true;
7023            }
7024
7025            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7026            // If there were 'always' entries their preferred order has been set, so we also
7027            // back that off to make the alternatives equivalent
7028            if (alwaysAskList.size() > 0) {
7029                for (ResolveInfo i : result) {
7030                    i.preferredOrder = 0;
7031                }
7032                result.addAll(alwaysAskList);
7033                includeBrowser = true;
7034            }
7035
7036            if (includeBrowser) {
7037                // Also add browsers (all of them or only the default one)
7038                if (DEBUG_DOMAIN_VERIFICATION) {
7039                    Slog.v(TAG, "   ...including browsers in candidate set");
7040                }
7041                if ((matchFlags & MATCH_ALL) != 0) {
7042                    result.addAll(matchAllList);
7043                } else {
7044                    // Browser/generic handling case.  If there's a default browser, go straight
7045                    // to that (but only if there is no other higher-priority match).
7046                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7047                    int maxMatchPrio = 0;
7048                    ResolveInfo defaultBrowserMatch = null;
7049                    final int numCandidates = matchAllList.size();
7050                    for (int n = 0; n < numCandidates; n++) {
7051                        ResolveInfo info = matchAllList.get(n);
7052                        // track the highest overall match priority...
7053                        if (info.priority > maxMatchPrio) {
7054                            maxMatchPrio = info.priority;
7055                        }
7056                        // ...and the highest-priority default browser match
7057                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7058                            if (defaultBrowserMatch == null
7059                                    || (defaultBrowserMatch.priority < info.priority)) {
7060                                if (debug) {
7061                                    Slog.v(TAG, "Considering default browser match " + info);
7062                                }
7063                                defaultBrowserMatch = info;
7064                            }
7065                        }
7066                    }
7067                    if (defaultBrowserMatch != null
7068                            && defaultBrowserMatch.priority >= maxMatchPrio
7069                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7070                    {
7071                        if (debug) {
7072                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7073                        }
7074                        result.add(defaultBrowserMatch);
7075                    } else {
7076                        result.addAll(matchAllList);
7077                    }
7078                }
7079
7080                // If there is nothing selected, add all candidates and remove the ones that the user
7081                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7082                if (result.size() == 0) {
7083                    result.addAll(candidates);
7084                    result.removeAll(neverList);
7085                }
7086            }
7087        }
7088        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7089            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7090                    result.size());
7091            for (ResolveInfo info : result) {
7092                Slog.v(TAG, "  + " + info.activityInfo);
7093            }
7094        }
7095        return result;
7096    }
7097
7098    // Returns a packed value as a long:
7099    //
7100    // high 'int'-sized word: link status: undefined/ask/never/always.
7101    // low 'int'-sized word: relative priority among 'always' results.
7102    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7103        long result = ps.getDomainVerificationStatusForUser(userId);
7104        // if none available, get the master status
7105        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7106            if (ps.getIntentFilterVerificationInfo() != null) {
7107                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7108            }
7109        }
7110        return result;
7111    }
7112
7113    private ResolveInfo querySkipCurrentProfileIntents(
7114            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7115            int flags, int sourceUserId) {
7116        if (matchingFilters != null) {
7117            int size = matchingFilters.size();
7118            for (int i = 0; i < size; i ++) {
7119                CrossProfileIntentFilter filter = matchingFilters.get(i);
7120                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7121                    // Checking if there are activities in the target user that can handle the
7122                    // intent.
7123                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7124                            resolvedType, flags, sourceUserId);
7125                    if (resolveInfo != null) {
7126                        return resolveInfo;
7127                    }
7128                }
7129            }
7130        }
7131        return null;
7132    }
7133
7134    // Return matching ResolveInfo in target user if any.
7135    private ResolveInfo queryCrossProfileIntents(
7136            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7137            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7138        if (matchingFilters != null) {
7139            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7140            // match the same intent. For performance reasons, it is better not to
7141            // run queryIntent twice for the same userId
7142            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7143            int size = matchingFilters.size();
7144            for (int i = 0; i < size; i++) {
7145                CrossProfileIntentFilter filter = matchingFilters.get(i);
7146                int targetUserId = filter.getTargetUserId();
7147                boolean skipCurrentProfile =
7148                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7149                boolean skipCurrentProfileIfNoMatchFound =
7150                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7151                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7152                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7153                    // Checking if there are activities in the target user that can handle the
7154                    // intent.
7155                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7156                            resolvedType, flags, sourceUserId);
7157                    if (resolveInfo != null) return resolveInfo;
7158                    alreadyTriedUserIds.put(targetUserId, true);
7159                }
7160            }
7161        }
7162        return null;
7163    }
7164
7165    /**
7166     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7167     * will forward the intent to the filter's target user.
7168     * Otherwise, returns null.
7169     */
7170    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7171            String resolvedType, int flags, int sourceUserId) {
7172        int targetUserId = filter.getTargetUserId();
7173        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7174                resolvedType, flags, targetUserId);
7175        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7176            // If all the matches in the target profile are suspended, return null.
7177            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7178                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7179                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7180                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7181                            targetUserId);
7182                }
7183            }
7184        }
7185        return null;
7186    }
7187
7188    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7189            int sourceUserId, int targetUserId) {
7190        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7191        long ident = Binder.clearCallingIdentity();
7192        boolean targetIsProfile;
7193        try {
7194            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7195        } finally {
7196            Binder.restoreCallingIdentity(ident);
7197        }
7198        String className;
7199        if (targetIsProfile) {
7200            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7201        } else {
7202            className = FORWARD_INTENT_TO_PARENT;
7203        }
7204        ComponentName forwardingActivityComponentName = new ComponentName(
7205                mAndroidApplication.packageName, className);
7206        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7207                sourceUserId);
7208        if (!targetIsProfile) {
7209            forwardingActivityInfo.showUserIcon = targetUserId;
7210            forwardingResolveInfo.noResourceId = true;
7211        }
7212        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7213        forwardingResolveInfo.priority = 0;
7214        forwardingResolveInfo.preferredOrder = 0;
7215        forwardingResolveInfo.match = 0;
7216        forwardingResolveInfo.isDefault = true;
7217        forwardingResolveInfo.filter = filter;
7218        forwardingResolveInfo.targetUserId = targetUserId;
7219        return forwardingResolveInfo;
7220    }
7221
7222    @Override
7223    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7224            Intent[] specifics, String[] specificTypes, Intent intent,
7225            String resolvedType, int flags, int userId) {
7226        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7227                specificTypes, intent, resolvedType, flags, userId));
7228    }
7229
7230    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7231            Intent[] specifics, String[] specificTypes, Intent intent,
7232            String resolvedType, int flags, int userId) {
7233        if (!sUserManager.exists(userId)) return Collections.emptyList();
7234        final int callingUid = Binder.getCallingUid();
7235        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7236                false /*includeInstantApps*/);
7237        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7238                false /*requireFullPermission*/, false /*checkShell*/,
7239                "query intent activity options");
7240        final String resultsAction = intent.getAction();
7241
7242        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7243                | PackageManager.GET_RESOLVED_FILTER, userId);
7244
7245        if (DEBUG_INTENT_MATCHING) {
7246            Log.v(TAG, "Query " + intent + ": " + results);
7247        }
7248
7249        int specificsPos = 0;
7250        int N;
7251
7252        // todo: note that the algorithm used here is O(N^2).  This
7253        // isn't a problem in our current environment, but if we start running
7254        // into situations where we have more than 5 or 10 matches then this
7255        // should probably be changed to something smarter...
7256
7257        // First we go through and resolve each of the specific items
7258        // that were supplied, taking care of removing any corresponding
7259        // duplicate items in the generic resolve list.
7260        if (specifics != null) {
7261            for (int i=0; i<specifics.length; i++) {
7262                final Intent sintent = specifics[i];
7263                if (sintent == null) {
7264                    continue;
7265                }
7266
7267                if (DEBUG_INTENT_MATCHING) {
7268                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7269                }
7270
7271                String action = sintent.getAction();
7272                if (resultsAction != null && resultsAction.equals(action)) {
7273                    // If this action was explicitly requested, then don't
7274                    // remove things that have it.
7275                    action = null;
7276                }
7277
7278                ResolveInfo ri = null;
7279                ActivityInfo ai = null;
7280
7281                ComponentName comp = sintent.getComponent();
7282                if (comp == null) {
7283                    ri = resolveIntent(
7284                        sintent,
7285                        specificTypes != null ? specificTypes[i] : null,
7286                            flags, userId);
7287                    if (ri == null) {
7288                        continue;
7289                    }
7290                    if (ri == mResolveInfo) {
7291                        // ACK!  Must do something better with this.
7292                    }
7293                    ai = ri.activityInfo;
7294                    comp = new ComponentName(ai.applicationInfo.packageName,
7295                            ai.name);
7296                } else {
7297                    ai = getActivityInfo(comp, flags, userId);
7298                    if (ai == null) {
7299                        continue;
7300                    }
7301                }
7302
7303                // Look for any generic query activities that are duplicates
7304                // of this specific one, and remove them from the results.
7305                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7306                N = results.size();
7307                int j;
7308                for (j=specificsPos; j<N; j++) {
7309                    ResolveInfo sri = results.get(j);
7310                    if ((sri.activityInfo.name.equals(comp.getClassName())
7311                            && sri.activityInfo.applicationInfo.packageName.equals(
7312                                    comp.getPackageName()))
7313                        || (action != null && sri.filter.matchAction(action))) {
7314                        results.remove(j);
7315                        if (DEBUG_INTENT_MATCHING) Log.v(
7316                            TAG, "Removing duplicate item from " + j
7317                            + " due to specific " + specificsPos);
7318                        if (ri == null) {
7319                            ri = sri;
7320                        }
7321                        j--;
7322                        N--;
7323                    }
7324                }
7325
7326                // Add this specific item to its proper place.
7327                if (ri == null) {
7328                    ri = new ResolveInfo();
7329                    ri.activityInfo = ai;
7330                }
7331                results.add(specificsPos, ri);
7332                ri.specificIndex = i;
7333                specificsPos++;
7334            }
7335        }
7336
7337        // Now we go through the remaining generic results and remove any
7338        // duplicate actions that are found here.
7339        N = results.size();
7340        for (int i=specificsPos; i<N-1; i++) {
7341            final ResolveInfo rii = results.get(i);
7342            if (rii.filter == null) {
7343                continue;
7344            }
7345
7346            // Iterate over all of the actions of this result's intent
7347            // filter...  typically this should be just one.
7348            final Iterator<String> it = rii.filter.actionsIterator();
7349            if (it == null) {
7350                continue;
7351            }
7352            while (it.hasNext()) {
7353                final String action = it.next();
7354                if (resultsAction != null && resultsAction.equals(action)) {
7355                    // If this action was explicitly requested, then don't
7356                    // remove things that have it.
7357                    continue;
7358                }
7359                for (int j=i+1; j<N; j++) {
7360                    final ResolveInfo rij = results.get(j);
7361                    if (rij.filter != null && rij.filter.hasAction(action)) {
7362                        results.remove(j);
7363                        if (DEBUG_INTENT_MATCHING) Log.v(
7364                            TAG, "Removing duplicate item from " + j
7365                            + " due to action " + action + " at " + i);
7366                        j--;
7367                        N--;
7368                    }
7369                }
7370            }
7371
7372            // If the caller didn't request filter information, drop it now
7373            // so we don't have to marshall/unmarshall it.
7374            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7375                rii.filter = null;
7376            }
7377        }
7378
7379        // Filter out the caller activity if so requested.
7380        if (caller != null) {
7381            N = results.size();
7382            for (int i=0; i<N; i++) {
7383                ActivityInfo ainfo = results.get(i).activityInfo;
7384                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7385                        && caller.getClassName().equals(ainfo.name)) {
7386                    results.remove(i);
7387                    break;
7388                }
7389            }
7390        }
7391
7392        // If the caller didn't request filter information,
7393        // drop them now so we don't have to
7394        // marshall/unmarshall it.
7395        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7396            N = results.size();
7397            for (int i=0; i<N; i++) {
7398                results.get(i).filter = null;
7399            }
7400        }
7401
7402        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7403        return results;
7404    }
7405
7406    @Override
7407    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7408            String resolvedType, int flags, int userId) {
7409        return new ParceledListSlice<>(
7410                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7411                        false /*allowDynamicSplits*/));
7412    }
7413
7414    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7415            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7416        if (!sUserManager.exists(userId)) return Collections.emptyList();
7417        final int callingUid = Binder.getCallingUid();
7418        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7419                false /*requireFullPermission*/, false /*checkShell*/,
7420                "query intent receivers");
7421        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7422        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7423                false /*includeInstantApps*/);
7424        ComponentName comp = intent.getComponent();
7425        if (comp == null) {
7426            if (intent.getSelector() != null) {
7427                intent = intent.getSelector();
7428                comp = intent.getComponent();
7429            }
7430        }
7431        if (comp != null) {
7432            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7433            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7434            if (ai != null) {
7435                // When specifying an explicit component, we prevent the activity from being
7436                // used when either 1) the calling package is normal and the activity is within
7437                // an instant application or 2) the calling package is ephemeral and the
7438                // activity is not visible to instant applications.
7439                final boolean matchInstantApp =
7440                        (flags & PackageManager.MATCH_INSTANT) != 0;
7441                final boolean matchVisibleToInstantAppOnly =
7442                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7443                final boolean matchExplicitlyVisibleOnly =
7444                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7445                final boolean isCallerInstantApp =
7446                        instantAppPkgName != null;
7447                final boolean isTargetSameInstantApp =
7448                        comp.getPackageName().equals(instantAppPkgName);
7449                final boolean isTargetInstantApp =
7450                        (ai.applicationInfo.privateFlags
7451                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7452                final boolean isTargetVisibleToInstantApp =
7453                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7454                final boolean isTargetExplicitlyVisibleToInstantApp =
7455                        isTargetVisibleToInstantApp
7456                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7457                final boolean isTargetHiddenFromInstantApp =
7458                        !isTargetVisibleToInstantApp
7459                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7460                final boolean blockResolution =
7461                        !isTargetSameInstantApp
7462                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7463                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7464                                        && isTargetHiddenFromInstantApp));
7465                if (!blockResolution) {
7466                    ResolveInfo ri = new ResolveInfo();
7467                    ri.activityInfo = ai;
7468                    list.add(ri);
7469                }
7470            }
7471            return applyPostResolutionFilter(
7472                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7473        }
7474
7475        // reader
7476        synchronized (mPackages) {
7477            String pkgName = intent.getPackage();
7478            if (pkgName == null) {
7479                final List<ResolveInfo> result =
7480                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7481                return applyPostResolutionFilter(
7482                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7483            }
7484            final PackageParser.Package pkg = mPackages.get(pkgName);
7485            if (pkg != null) {
7486                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7487                        intent, resolvedType, flags, pkg.receivers, userId);
7488                return applyPostResolutionFilter(
7489                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7490            }
7491            return Collections.emptyList();
7492        }
7493    }
7494
7495    @Override
7496    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7497        final int callingUid = Binder.getCallingUid();
7498        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7499    }
7500
7501    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7502            int userId, int callingUid) {
7503        if (!sUserManager.exists(userId)) return null;
7504        flags = updateFlagsForResolve(
7505                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7506        List<ResolveInfo> query = queryIntentServicesInternal(
7507                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7508        if (query != null) {
7509            if (query.size() >= 1) {
7510                // If there is more than one service with the same priority,
7511                // just arbitrarily pick the first one.
7512                return query.get(0);
7513            }
7514        }
7515        return null;
7516    }
7517
7518    @Override
7519    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7520            String resolvedType, int flags, int userId) {
7521        final int callingUid = Binder.getCallingUid();
7522        return new ParceledListSlice<>(queryIntentServicesInternal(
7523                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7524    }
7525
7526    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7527            String resolvedType, int flags, int userId, int callingUid,
7528            boolean includeInstantApps) {
7529        if (!sUserManager.exists(userId)) return Collections.emptyList();
7530        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7531                false /*requireFullPermission*/, false /*checkShell*/,
7532                "query intent receivers");
7533        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7534        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7535        ComponentName comp = intent.getComponent();
7536        if (comp == null) {
7537            if (intent.getSelector() != null) {
7538                intent = intent.getSelector();
7539                comp = intent.getComponent();
7540            }
7541        }
7542        if (comp != null) {
7543            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7544            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7545            if (si != null) {
7546                // When specifying an explicit component, we prevent the service from being
7547                // used when either 1) the service is in an instant application and the
7548                // caller is not the same instant application or 2) the calling package is
7549                // ephemeral and the activity is not visible to ephemeral applications.
7550                final boolean matchInstantApp =
7551                        (flags & PackageManager.MATCH_INSTANT) != 0;
7552                final boolean matchVisibleToInstantAppOnly =
7553                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7554                final boolean isCallerInstantApp =
7555                        instantAppPkgName != null;
7556                final boolean isTargetSameInstantApp =
7557                        comp.getPackageName().equals(instantAppPkgName);
7558                final boolean isTargetInstantApp =
7559                        (si.applicationInfo.privateFlags
7560                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7561                final boolean isTargetHiddenFromInstantApp =
7562                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7563                final boolean blockResolution =
7564                        !isTargetSameInstantApp
7565                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7566                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7567                                        && isTargetHiddenFromInstantApp));
7568                if (!blockResolution) {
7569                    final ResolveInfo ri = new ResolveInfo();
7570                    ri.serviceInfo = si;
7571                    list.add(ri);
7572                }
7573            }
7574            return list;
7575        }
7576
7577        // reader
7578        synchronized (mPackages) {
7579            String pkgName = intent.getPackage();
7580            if (pkgName == null) {
7581                return applyPostServiceResolutionFilter(
7582                        mServices.queryIntent(intent, resolvedType, flags, userId),
7583                        instantAppPkgName);
7584            }
7585            final PackageParser.Package pkg = mPackages.get(pkgName);
7586            if (pkg != null) {
7587                return applyPostServiceResolutionFilter(
7588                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7589                                userId),
7590                        instantAppPkgName);
7591            }
7592            return Collections.emptyList();
7593        }
7594    }
7595
7596    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7597            String instantAppPkgName) {
7598        if (instantAppPkgName == null) {
7599            return resolveInfos;
7600        }
7601        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7602            final ResolveInfo info = resolveInfos.get(i);
7603            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7604            // allow services that are defined in the provided package
7605            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7606                if (info.serviceInfo.splitName != null
7607                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7608                                info.serviceInfo.splitName)) {
7609                    // requested service is defined in a split that hasn't been installed yet.
7610                    // add the installer to the resolve list
7611                    if (DEBUG_INSTANT) {
7612                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7613                    }
7614                    final ResolveInfo installerInfo = new ResolveInfo(
7615                            mInstantAppInstallerInfo);
7616                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7617                            null /* installFailureActivity */,
7618                            info.serviceInfo.packageName,
7619                            info.serviceInfo.applicationInfo.versionCode,
7620                            info.serviceInfo.splitName);
7621                    // make sure this resolver is the default
7622                    installerInfo.isDefault = true;
7623                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7624                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7625                    // add a non-generic filter
7626                    installerInfo.filter = new IntentFilter();
7627                    // load resources from the correct package
7628                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7629                    resolveInfos.set(i, installerInfo);
7630                }
7631                continue;
7632            }
7633            // allow services that have been explicitly exposed to ephemeral apps
7634            if (!isEphemeralApp
7635                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7636                continue;
7637            }
7638            resolveInfos.remove(i);
7639        }
7640        return resolveInfos;
7641    }
7642
7643    @Override
7644    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7645            String resolvedType, int flags, int userId) {
7646        return new ParceledListSlice<>(
7647                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7648    }
7649
7650    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7651            Intent intent, String resolvedType, int flags, int userId) {
7652        if (!sUserManager.exists(userId)) return Collections.emptyList();
7653        final int callingUid = Binder.getCallingUid();
7654        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7655        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7656                false /*includeInstantApps*/);
7657        ComponentName comp = intent.getComponent();
7658        if (comp == null) {
7659            if (intent.getSelector() != null) {
7660                intent = intent.getSelector();
7661                comp = intent.getComponent();
7662            }
7663        }
7664        if (comp != null) {
7665            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7666            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7667            if (pi != null) {
7668                // When specifying an explicit component, we prevent the provider from being
7669                // used when either 1) the provider is in an instant application and the
7670                // caller is not the same instant application or 2) the calling package is an
7671                // instant application and the provider is not visible to instant applications.
7672                final boolean matchInstantApp =
7673                        (flags & PackageManager.MATCH_INSTANT) != 0;
7674                final boolean matchVisibleToInstantAppOnly =
7675                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7676                final boolean isCallerInstantApp =
7677                        instantAppPkgName != null;
7678                final boolean isTargetSameInstantApp =
7679                        comp.getPackageName().equals(instantAppPkgName);
7680                final boolean isTargetInstantApp =
7681                        (pi.applicationInfo.privateFlags
7682                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7683                final boolean isTargetHiddenFromInstantApp =
7684                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7685                final boolean blockResolution =
7686                        !isTargetSameInstantApp
7687                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7688                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7689                                        && isTargetHiddenFromInstantApp));
7690                if (!blockResolution) {
7691                    final ResolveInfo ri = new ResolveInfo();
7692                    ri.providerInfo = pi;
7693                    list.add(ri);
7694                }
7695            }
7696            return list;
7697        }
7698
7699        // reader
7700        synchronized (mPackages) {
7701            String pkgName = intent.getPackage();
7702            if (pkgName == null) {
7703                return applyPostContentProviderResolutionFilter(
7704                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7705                        instantAppPkgName);
7706            }
7707            final PackageParser.Package pkg = mPackages.get(pkgName);
7708            if (pkg != null) {
7709                return applyPostContentProviderResolutionFilter(
7710                        mProviders.queryIntentForPackage(
7711                        intent, resolvedType, flags, pkg.providers, userId),
7712                        instantAppPkgName);
7713            }
7714            return Collections.emptyList();
7715        }
7716    }
7717
7718    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7719            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7720        if (instantAppPkgName == null) {
7721            return resolveInfos;
7722        }
7723        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7724            final ResolveInfo info = resolveInfos.get(i);
7725            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7726            // allow providers that are defined in the provided package
7727            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7728                if (info.providerInfo.splitName != null
7729                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7730                                info.providerInfo.splitName)) {
7731                    // requested provider is defined in a split that hasn't been installed yet.
7732                    // add the installer to the resolve list
7733                    if (DEBUG_INSTANT) {
7734                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7735                    }
7736                    final ResolveInfo installerInfo = new ResolveInfo(
7737                            mInstantAppInstallerInfo);
7738                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7739                            null /*failureActivity*/,
7740                            info.providerInfo.packageName,
7741                            info.providerInfo.applicationInfo.versionCode,
7742                            info.providerInfo.splitName);
7743                    // make sure this resolver is the default
7744                    installerInfo.isDefault = true;
7745                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7746                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7747                    // add a non-generic filter
7748                    installerInfo.filter = new IntentFilter();
7749                    // load resources from the correct package
7750                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7751                    resolveInfos.set(i, installerInfo);
7752                }
7753                continue;
7754            }
7755            // allow providers that have been explicitly exposed to instant applications
7756            if (!isEphemeralApp
7757                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7758                continue;
7759            }
7760            resolveInfos.remove(i);
7761        }
7762        return resolveInfos;
7763    }
7764
7765    @Override
7766    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7767        final int callingUid = Binder.getCallingUid();
7768        if (getInstantAppPackageName(callingUid) != null) {
7769            return ParceledListSlice.emptyList();
7770        }
7771        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7772        flags = updateFlagsForPackage(flags, userId, null);
7773        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7774        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7775                true /* requireFullPermission */, false /* checkShell */,
7776                "get installed packages");
7777
7778        // writer
7779        synchronized (mPackages) {
7780            ArrayList<PackageInfo> list;
7781            if (listUninstalled) {
7782                list = new ArrayList<>(mSettings.mPackages.size());
7783                for (PackageSetting ps : mSettings.mPackages.values()) {
7784                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7785                        continue;
7786                    }
7787                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7788                        continue;
7789                    }
7790                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7791                    if (pi != null) {
7792                        list.add(pi);
7793                    }
7794                }
7795            } else {
7796                list = new ArrayList<>(mPackages.size());
7797                for (PackageParser.Package p : mPackages.values()) {
7798                    final PackageSetting ps = (PackageSetting) p.mExtras;
7799                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7800                        continue;
7801                    }
7802                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7803                        continue;
7804                    }
7805                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7806                            p.mExtras, flags, userId);
7807                    if (pi != null) {
7808                        list.add(pi);
7809                    }
7810                }
7811            }
7812
7813            return new ParceledListSlice<>(list);
7814        }
7815    }
7816
7817    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7818            String[] permissions, boolean[] tmp, int flags, int userId) {
7819        int numMatch = 0;
7820        final PermissionsState permissionsState = ps.getPermissionsState();
7821        for (int i=0; i<permissions.length; i++) {
7822            final String permission = permissions[i];
7823            if (permissionsState.hasPermission(permission, userId)) {
7824                tmp[i] = true;
7825                numMatch++;
7826            } else {
7827                tmp[i] = false;
7828            }
7829        }
7830        if (numMatch == 0) {
7831            return;
7832        }
7833        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7834
7835        // The above might return null in cases of uninstalled apps or install-state
7836        // skew across users/profiles.
7837        if (pi != null) {
7838            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7839                if (numMatch == permissions.length) {
7840                    pi.requestedPermissions = permissions;
7841                } else {
7842                    pi.requestedPermissions = new String[numMatch];
7843                    numMatch = 0;
7844                    for (int i=0; i<permissions.length; i++) {
7845                        if (tmp[i]) {
7846                            pi.requestedPermissions[numMatch] = permissions[i];
7847                            numMatch++;
7848                        }
7849                    }
7850                }
7851            }
7852            list.add(pi);
7853        }
7854    }
7855
7856    @Override
7857    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7858            String[] permissions, int flags, int userId) {
7859        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7860        flags = updateFlagsForPackage(flags, userId, permissions);
7861        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7862                true /* requireFullPermission */, false /* checkShell */,
7863                "get packages holding permissions");
7864        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7865
7866        // writer
7867        synchronized (mPackages) {
7868            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7869            boolean[] tmpBools = new boolean[permissions.length];
7870            if (listUninstalled) {
7871                for (PackageSetting ps : mSettings.mPackages.values()) {
7872                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7873                            userId);
7874                }
7875            } else {
7876                for (PackageParser.Package pkg : mPackages.values()) {
7877                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7878                    if (ps != null) {
7879                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7880                                userId);
7881                    }
7882                }
7883            }
7884
7885            return new ParceledListSlice<PackageInfo>(list);
7886        }
7887    }
7888
7889    @Override
7890    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7891        final int callingUid = Binder.getCallingUid();
7892        if (getInstantAppPackageName(callingUid) != null) {
7893            return ParceledListSlice.emptyList();
7894        }
7895        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7896        flags = updateFlagsForApplication(flags, userId, null);
7897        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7898
7899        // writer
7900        synchronized (mPackages) {
7901            ArrayList<ApplicationInfo> list;
7902            if (listUninstalled) {
7903                list = new ArrayList<>(mSettings.mPackages.size());
7904                for (PackageSetting ps : mSettings.mPackages.values()) {
7905                    ApplicationInfo ai;
7906                    int effectiveFlags = flags;
7907                    if (ps.isSystem()) {
7908                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7909                    }
7910                    if (ps.pkg != null) {
7911                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7912                            continue;
7913                        }
7914                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7915                            continue;
7916                        }
7917                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7918                                ps.readUserState(userId), userId);
7919                        if (ai != null) {
7920                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7921                        }
7922                    } else {
7923                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7924                        // and already converts to externally visible package name
7925                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7926                                callingUid, effectiveFlags, userId);
7927                    }
7928                    if (ai != null) {
7929                        list.add(ai);
7930                    }
7931                }
7932            } else {
7933                list = new ArrayList<>(mPackages.size());
7934                for (PackageParser.Package p : mPackages.values()) {
7935                    if (p.mExtras != null) {
7936                        PackageSetting ps = (PackageSetting) p.mExtras;
7937                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7938                            continue;
7939                        }
7940                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7941                            continue;
7942                        }
7943                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7944                                ps.readUserState(userId), userId);
7945                        if (ai != null) {
7946                            ai.packageName = resolveExternalPackageNameLPr(p);
7947                            list.add(ai);
7948                        }
7949                    }
7950                }
7951            }
7952
7953            return new ParceledListSlice<>(list);
7954        }
7955    }
7956
7957    @Override
7958    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7959        if (HIDE_EPHEMERAL_APIS) {
7960            return null;
7961        }
7962        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7963            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7964                    "getEphemeralApplications");
7965        }
7966        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7967                true /* requireFullPermission */, false /* checkShell */,
7968                "getEphemeralApplications");
7969        synchronized (mPackages) {
7970            List<InstantAppInfo> instantApps = mInstantAppRegistry
7971                    .getInstantAppsLPr(userId);
7972            if (instantApps != null) {
7973                return new ParceledListSlice<>(instantApps);
7974            }
7975        }
7976        return null;
7977    }
7978
7979    @Override
7980    public boolean isInstantApp(String packageName, int userId) {
7981        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7982                true /* requireFullPermission */, false /* checkShell */,
7983                "isInstantApp");
7984        if (HIDE_EPHEMERAL_APIS) {
7985            return false;
7986        }
7987
7988        synchronized (mPackages) {
7989            int callingUid = Binder.getCallingUid();
7990            if (Process.isIsolated(callingUid)) {
7991                callingUid = mIsolatedOwners.get(callingUid);
7992            }
7993            final PackageSetting ps = mSettings.mPackages.get(packageName);
7994            PackageParser.Package pkg = mPackages.get(packageName);
7995            final boolean returnAllowed =
7996                    ps != null
7997                    && (isCallerSameApp(packageName, callingUid)
7998                            || canViewInstantApps(callingUid, userId)
7999                            || mInstantAppRegistry.isInstantAccessGranted(
8000                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8001            if (returnAllowed) {
8002                return ps.getInstantApp(userId);
8003            }
8004        }
8005        return false;
8006    }
8007
8008    @Override
8009    public byte[] getInstantAppCookie(String packageName, int userId) {
8010        if (HIDE_EPHEMERAL_APIS) {
8011            return null;
8012        }
8013
8014        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8015                true /* requireFullPermission */, false /* checkShell */,
8016                "getInstantAppCookie");
8017        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8018            return null;
8019        }
8020        synchronized (mPackages) {
8021            return mInstantAppRegistry.getInstantAppCookieLPw(
8022                    packageName, userId);
8023        }
8024    }
8025
8026    @Override
8027    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8028        if (HIDE_EPHEMERAL_APIS) {
8029            return true;
8030        }
8031
8032        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8033                true /* requireFullPermission */, true /* checkShell */,
8034                "setInstantAppCookie");
8035        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8036            return false;
8037        }
8038        synchronized (mPackages) {
8039            return mInstantAppRegistry.setInstantAppCookieLPw(
8040                    packageName, cookie, userId);
8041        }
8042    }
8043
8044    @Override
8045    public Bitmap getInstantAppIcon(String packageName, int userId) {
8046        if (HIDE_EPHEMERAL_APIS) {
8047            return null;
8048        }
8049
8050        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8051            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8052                    "getInstantAppIcon");
8053        }
8054        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8055                true /* requireFullPermission */, false /* checkShell */,
8056                "getInstantAppIcon");
8057
8058        synchronized (mPackages) {
8059            return mInstantAppRegistry.getInstantAppIconLPw(
8060                    packageName, userId);
8061        }
8062    }
8063
8064    private boolean isCallerSameApp(String packageName, int uid) {
8065        PackageParser.Package pkg = mPackages.get(packageName);
8066        return pkg != null
8067                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8068    }
8069
8070    @Override
8071    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8072        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8073            return ParceledListSlice.emptyList();
8074        }
8075        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8076    }
8077
8078    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8079        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8080
8081        // reader
8082        synchronized (mPackages) {
8083            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8084            final int userId = UserHandle.getCallingUserId();
8085            while (i.hasNext()) {
8086                final PackageParser.Package p = i.next();
8087                if (p.applicationInfo == null) continue;
8088
8089                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8090                        && !p.applicationInfo.isDirectBootAware();
8091                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8092                        && p.applicationInfo.isDirectBootAware();
8093
8094                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8095                        && (!mSafeMode || isSystemApp(p))
8096                        && (matchesUnaware || matchesAware)) {
8097                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8098                    if (ps != null) {
8099                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8100                                ps.readUserState(userId), userId);
8101                        if (ai != null) {
8102                            finalList.add(ai);
8103                        }
8104                    }
8105                }
8106            }
8107        }
8108
8109        return finalList;
8110    }
8111
8112    @Override
8113    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8114        return resolveContentProviderInternal(name, flags, userId);
8115    }
8116
8117    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8118        if (!sUserManager.exists(userId)) return null;
8119        flags = updateFlagsForComponent(flags, userId, name);
8120        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8121        // reader
8122        synchronized (mPackages) {
8123            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8124            PackageSetting ps = provider != null
8125                    ? mSettings.mPackages.get(provider.owner.packageName)
8126                    : null;
8127            if (ps != null) {
8128                final boolean isInstantApp = ps.getInstantApp(userId);
8129                // normal application; filter out instant application provider
8130                if (instantAppPkgName == null && isInstantApp) {
8131                    return null;
8132                }
8133                // instant application; filter out other instant applications
8134                if (instantAppPkgName != null
8135                        && isInstantApp
8136                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8137                    return null;
8138                }
8139                // instant application; filter out non-exposed provider
8140                if (instantAppPkgName != null
8141                        && !isInstantApp
8142                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8143                    return null;
8144                }
8145                // provider not enabled
8146                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8147                    return null;
8148                }
8149                return PackageParser.generateProviderInfo(
8150                        provider, flags, ps.readUserState(userId), userId);
8151            }
8152            return null;
8153        }
8154    }
8155
8156    /**
8157     * @deprecated
8158     */
8159    @Deprecated
8160    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8161        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8162            return;
8163        }
8164        // reader
8165        synchronized (mPackages) {
8166            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8167                    .entrySet().iterator();
8168            final int userId = UserHandle.getCallingUserId();
8169            while (i.hasNext()) {
8170                Map.Entry<String, PackageParser.Provider> entry = i.next();
8171                PackageParser.Provider p = entry.getValue();
8172                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8173
8174                if (ps != null && p.syncable
8175                        && (!mSafeMode || (p.info.applicationInfo.flags
8176                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8177                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8178                            ps.readUserState(userId), userId);
8179                    if (info != null) {
8180                        outNames.add(entry.getKey());
8181                        outInfo.add(info);
8182                    }
8183                }
8184            }
8185        }
8186    }
8187
8188    @Override
8189    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8190            int uid, int flags, String metaDataKey) {
8191        final int callingUid = Binder.getCallingUid();
8192        final int userId = processName != null ? UserHandle.getUserId(uid)
8193                : UserHandle.getCallingUserId();
8194        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8195        flags = updateFlagsForComponent(flags, userId, processName);
8196        ArrayList<ProviderInfo> finalList = null;
8197        // reader
8198        synchronized (mPackages) {
8199            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8200            while (i.hasNext()) {
8201                final PackageParser.Provider p = i.next();
8202                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8203                if (ps != null && p.info.authority != null
8204                        && (processName == null
8205                                || (p.info.processName.equals(processName)
8206                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8207                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8208
8209                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8210                    // parameter.
8211                    if (metaDataKey != null
8212                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8213                        continue;
8214                    }
8215                    final ComponentName component =
8216                            new ComponentName(p.info.packageName, p.info.name);
8217                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8218                        continue;
8219                    }
8220                    if (finalList == null) {
8221                        finalList = new ArrayList<ProviderInfo>(3);
8222                    }
8223                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8224                            ps.readUserState(userId), userId);
8225                    if (info != null) {
8226                        finalList.add(info);
8227                    }
8228                }
8229            }
8230        }
8231
8232        if (finalList != null) {
8233            Collections.sort(finalList, mProviderInitOrderSorter);
8234            return new ParceledListSlice<ProviderInfo>(finalList);
8235        }
8236
8237        return ParceledListSlice.emptyList();
8238    }
8239
8240    @Override
8241    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8242        // reader
8243        synchronized (mPackages) {
8244            final int callingUid = Binder.getCallingUid();
8245            final int callingUserId = UserHandle.getUserId(callingUid);
8246            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8247            if (ps == null) return null;
8248            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8249                return null;
8250            }
8251            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8252            return PackageParser.generateInstrumentationInfo(i, flags);
8253        }
8254    }
8255
8256    @Override
8257    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8258            String targetPackage, int flags) {
8259        final int callingUid = Binder.getCallingUid();
8260        final int callingUserId = UserHandle.getUserId(callingUid);
8261        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8262        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8263            return ParceledListSlice.emptyList();
8264        }
8265        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8266    }
8267
8268    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8269            int flags) {
8270        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8271
8272        // reader
8273        synchronized (mPackages) {
8274            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8275            while (i.hasNext()) {
8276                final PackageParser.Instrumentation p = i.next();
8277                if (targetPackage == null
8278                        || targetPackage.equals(p.info.targetPackage)) {
8279                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8280                            flags);
8281                    if (ii != null) {
8282                        finalList.add(ii);
8283                    }
8284                }
8285            }
8286        }
8287
8288        return finalList;
8289    }
8290
8291    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8292        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8293        try {
8294            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8295        } finally {
8296            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8297        }
8298    }
8299
8300    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8301        final File[] files = scanDir.listFiles();
8302        if (ArrayUtils.isEmpty(files)) {
8303            Log.d(TAG, "No files in app dir " + scanDir);
8304            return;
8305        }
8306
8307        if (DEBUG_PACKAGE_SCANNING) {
8308            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8309                    + " flags=0x" + Integer.toHexString(parseFlags));
8310        }
8311        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8312                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8313                mParallelPackageParserCallback)) {
8314            // Submit files for parsing in parallel
8315            int fileCount = 0;
8316            for (File file : files) {
8317                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8318                        && !PackageInstallerService.isStageName(file.getName());
8319                if (!isPackage) {
8320                    // Ignore entries which are not packages
8321                    continue;
8322                }
8323                parallelPackageParser.submit(file, parseFlags);
8324                fileCount++;
8325            }
8326
8327            // Process results one by one
8328            for (; fileCount > 0; fileCount--) {
8329                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8330                Throwable throwable = parseResult.throwable;
8331                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8332
8333                if (throwable == null) {
8334                    // TODO(toddke): move lower in the scan chain
8335                    // Static shared libraries have synthetic package names
8336                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8337                        renameStaticSharedLibraryPackage(parseResult.pkg);
8338                    }
8339                    try {
8340                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8341                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8342                                    currentTime, null);
8343                        }
8344                    } catch (PackageManagerException e) {
8345                        errorCode = e.error;
8346                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8347                    }
8348                } else if (throwable instanceof PackageParser.PackageParserException) {
8349                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8350                            throwable;
8351                    errorCode = e.error;
8352                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8353                } else {
8354                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8355                            + parseResult.scanFile, throwable);
8356                }
8357
8358                // Delete invalid userdata apps
8359                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8360                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8361                    logCriticalInfo(Log.WARN,
8362                            "Deleting invalid package at " + parseResult.scanFile);
8363                    removeCodePathLI(parseResult.scanFile);
8364                }
8365            }
8366        }
8367    }
8368
8369    public static void reportSettingsProblem(int priority, String msg) {
8370        logCriticalInfo(priority, msg);
8371    }
8372
8373    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8374            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8375        // When upgrading from pre-N MR1, verify the package time stamp using the package
8376        // directory and not the APK file.
8377        final long lastModifiedTime = mIsPreNMR1Upgrade
8378                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8379        if (ps != null && !forceCollect
8380                && ps.codePathString.equals(pkg.codePath)
8381                && ps.timeStamp == lastModifiedTime
8382                && !isCompatSignatureUpdateNeeded(pkg)
8383                && !isRecoverSignatureUpdateNeeded(pkg)) {
8384            if (ps.signatures.mSigningDetails.signatures != null
8385                    && ps.signatures.mSigningDetails.signatures.length != 0
8386                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8387                            != SignatureSchemeVersion.UNKNOWN) {
8388                // Optimization: reuse the existing cached signing data
8389                // if the package appears to be unchanged.
8390                pkg.mSigningDetails =
8391                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8392                return;
8393            }
8394
8395            Slog.w(TAG, "PackageSetting for " + ps.name
8396                    + " is missing signatures.  Collecting certs again to recover them.");
8397        } else {
8398            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8399                    (forceCollect ? " (forced)" : ""));
8400        }
8401
8402        try {
8403            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8404            PackageParser.collectCertificates(pkg, skipVerify);
8405        } catch (PackageParserException e) {
8406            throw PackageManagerException.from(e);
8407        } finally {
8408            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8409        }
8410    }
8411
8412    /**
8413     *  Traces a package scan.
8414     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8415     */
8416    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8417            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8418        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8419        try {
8420            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8421        } finally {
8422            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8423        }
8424    }
8425
8426    /**
8427     *  Scans a package and returns the newly parsed package.
8428     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8429     */
8430    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8431            long currentTime, UserHandle user) throws PackageManagerException {
8432        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8433        PackageParser pp = new PackageParser();
8434        pp.setSeparateProcesses(mSeparateProcesses);
8435        pp.setOnlyCoreApps(mOnlyCore);
8436        pp.setDisplayMetrics(mMetrics);
8437        pp.setCallback(mPackageParserCallback);
8438
8439        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8440        final PackageParser.Package pkg;
8441        try {
8442            pkg = pp.parsePackage(scanFile, parseFlags);
8443        } catch (PackageParserException e) {
8444            throw PackageManagerException.from(e);
8445        } finally {
8446            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8447        }
8448
8449        // Static shared libraries have synthetic package names
8450        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8451            renameStaticSharedLibraryPackage(pkg);
8452        }
8453
8454        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8455    }
8456
8457    /**
8458     *  Scans a package and returns the newly parsed package.
8459     *  @throws PackageManagerException on a parse error.
8460     */
8461    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8462            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8463            @Nullable UserHandle user)
8464                    throws PackageManagerException {
8465        // If the package has children and this is the first dive in the function
8466        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8467        // packages (parent and children) would be successfully scanned before the
8468        // actual scan since scanning mutates internal state and we want to atomically
8469        // install the package and its children.
8470        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8471            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8472                scanFlags |= SCAN_CHECK_ONLY;
8473            }
8474        } else {
8475            scanFlags &= ~SCAN_CHECK_ONLY;
8476        }
8477
8478        // Scan the parent
8479        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8480                scanFlags, currentTime, user);
8481
8482        // Scan the children
8483        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8484        for (int i = 0; i < childCount; i++) {
8485            PackageParser.Package childPackage = pkg.childPackages.get(i);
8486            addForInitLI(childPackage, parseFlags, scanFlags,
8487                    currentTime, user);
8488        }
8489
8490
8491        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8492            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8493        }
8494
8495        return scannedPkg;
8496    }
8497
8498    /**
8499     * Returns if full apk verification can be skipped for the whole package, including the splits.
8500     */
8501    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8502        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8503            return false;
8504        }
8505        // TODO: Allow base and splits to be verified individually.
8506        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8507            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8508                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8509                    return false;
8510                }
8511            }
8512        }
8513        return true;
8514    }
8515
8516    /**
8517     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8518     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8519     * match one in a trusted source, and should be done separately.
8520     */
8521    private boolean canSkipFullApkVerification(String apkPath) {
8522        byte[] rootHashObserved = null;
8523        try {
8524            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8525            if (rootHashObserved == null) {
8526                return false;  // APK does not contain Merkle tree root hash.
8527            }
8528            synchronized (mInstallLock) {
8529                // Returns whether the observed root hash matches what kernel has.
8530                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8531                return true;
8532            }
8533        } catch (InstallerException | IOException | DigestException |
8534                NoSuchAlgorithmException e) {
8535            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8536        }
8537        return false;
8538    }
8539
8540    /**
8541     * Adds a new package to the internal data structures during platform initialization.
8542     * <p>After adding, the package is known to the system and available for querying.
8543     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8544     * etc...], additional checks are performed. Basic verification [such as ensuring
8545     * matching signatures, checking version codes, etc...] occurs if the package is
8546     * identical to a previously known package. If the package fails a signature check,
8547     * the version installed on /data will be removed. If the version of the new package
8548     * is less than or equal than the version on /data, it will be ignored.
8549     * <p>Regardless of the package location, the results are applied to the internal
8550     * structures and the package is made available to the rest of the system.
8551     * <p>NOTE: The return value should be removed. It's the passed in package object.
8552     */
8553    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8554            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8555            @Nullable UserHandle user)
8556                    throws PackageManagerException {
8557        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8558        final String renamedPkgName;
8559        final PackageSetting disabledPkgSetting;
8560        final boolean isSystemPkgUpdated;
8561        final boolean pkgAlreadyExists;
8562        PackageSetting pkgSetting;
8563
8564        // NOTE: installPackageLI() has the same code to setup the package's
8565        // application info. This probably should be done lower in the call
8566        // stack [such as scanPackageOnly()]. However, we verify the application
8567        // info prior to that [in scanPackageNew()] and thus have to setup
8568        // the application info early.
8569        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8570        pkg.setApplicationInfoCodePath(pkg.codePath);
8571        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8572        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8573        pkg.setApplicationInfoResourcePath(pkg.codePath);
8574        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8575        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8576
8577        synchronized (mPackages) {
8578            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8579            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8580            if (realPkgName != null) {
8581                ensurePackageRenamed(pkg, renamedPkgName);
8582            }
8583            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8584            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8585            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8586            pkgAlreadyExists = pkgSetting != null;
8587            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8588            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8589            isSystemPkgUpdated = disabledPkgSetting != null;
8590
8591            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8592                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8593            }
8594
8595            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8596                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8597                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8598                    : null;
8599            if (DEBUG_PACKAGE_SCANNING
8600                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8601                    && sharedUserSetting != null) {
8602                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8603                        + " (uid=" + sharedUserSetting.userId + "):"
8604                        + " packages=" + sharedUserSetting.packages);
8605            }
8606
8607            if (scanSystemPartition) {
8608                // Potentially prune child packages. If the application on the /system
8609                // partition has been updated via OTA, but, is still disabled by a
8610                // version on /data, cycle through all of its children packages and
8611                // remove children that are no longer defined.
8612                if (isSystemPkgUpdated) {
8613                    final int scannedChildCount = (pkg.childPackages != null)
8614                            ? pkg.childPackages.size() : 0;
8615                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8616                            ? disabledPkgSetting.childPackageNames.size() : 0;
8617                    for (int i = 0; i < disabledChildCount; i++) {
8618                        String disabledChildPackageName =
8619                                disabledPkgSetting.childPackageNames.get(i);
8620                        boolean disabledPackageAvailable = false;
8621                        for (int j = 0; j < scannedChildCount; j++) {
8622                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8623                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8624                                disabledPackageAvailable = true;
8625                                break;
8626                            }
8627                        }
8628                        if (!disabledPackageAvailable) {
8629                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8630                        }
8631                    }
8632                    // we're updating the disabled package, so, scan it as the package setting
8633                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
8634                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8635                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8636                            (pkg == mPlatformPackage), user);
8637                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8638                }
8639            }
8640        }
8641
8642        final boolean newPkgChangedPaths =
8643                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8644        final boolean newPkgVersionGreater =
8645                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8646        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8647                && newPkgChangedPaths && newPkgVersionGreater;
8648        if (isSystemPkgBetter) {
8649            // The version of the application on /system is greater than the version on
8650            // /data. Switch back to the application on /system.
8651            // It's safe to assume the application on /system will correctly scan. If not,
8652            // there won't be a working copy of the application.
8653            synchronized (mPackages) {
8654                // just remove the loaded entries from package lists
8655                mPackages.remove(pkgSetting.name);
8656            }
8657
8658            logCriticalInfo(Log.WARN,
8659                    "System package updated;"
8660                    + " name: " + pkgSetting.name
8661                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8662                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8663
8664            final InstallArgs args = createInstallArgsForExisting(
8665                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8666                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8667            args.cleanUpResourcesLI();
8668            synchronized (mPackages) {
8669                mSettings.enableSystemPackageLPw(pkgSetting.name);
8670            }
8671        }
8672
8673        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8674            // The version of the application on the /system partition is less than or
8675            // equal to the version on the /data partition. Throw an exception and use
8676            // the application already installed on the /data partition.
8677            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8678                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8679                    + " better than this " + pkg.getLongVersionCode());
8680        }
8681
8682        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8683        // force re-collecting certificate.
8684        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8685                disabledPkgSetting);
8686        // Full APK verification can be skipped during certificate collection, only if the file is
8687        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8688        // cases, only data in Signing Block is verified instead of the whole file.
8689        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8690                (forceCollect && canSkipFullPackageVerification(pkg));
8691        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8692
8693        boolean shouldHideSystemApp = false;
8694        // A new application appeared on /system, but, we already have a copy of
8695        // the application installed on /data.
8696        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8697                && !pkgSetting.isSystem()) {
8698
8699            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8700                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
8701                logCriticalInfo(Log.WARN,
8702                        "System package signature mismatch;"
8703                        + " name: " + pkgSetting.name);
8704                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8705                        "scanPackageInternalLI")) {
8706                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8707                }
8708                pkgSetting = null;
8709            } else if (newPkgVersionGreater) {
8710                // The application on /system is newer than the application on /data.
8711                // Simply remove the application on /data [keeping application data]
8712                // and replace it with the version on /system.
8713                logCriticalInfo(Log.WARN,
8714                        "System package enabled;"
8715                        + " name: " + pkgSetting.name
8716                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8717                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8718                InstallArgs args = createInstallArgsForExisting(
8719                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8720                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8721                synchronized (mInstallLock) {
8722                    args.cleanUpResourcesLI();
8723                }
8724            } else {
8725                // The application on /system is older than the application on /data. Hide
8726                // the application on /system and the version on /data will be scanned later
8727                // and re-added like an update.
8728                shouldHideSystemApp = true;
8729                logCriticalInfo(Log.INFO,
8730                        "System package disabled;"
8731                        + " name: " + pkgSetting.name
8732                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8733                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8734            }
8735        }
8736
8737        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8738                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8739
8740        if (shouldHideSystemApp) {
8741            synchronized (mPackages) {
8742                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8743            }
8744        }
8745        return scannedPkg;
8746    }
8747
8748    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8749        // Derive the new package synthetic package name
8750        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8751                + pkg.staticSharedLibVersion);
8752    }
8753
8754    private static String fixProcessName(String defProcessName,
8755            String processName) {
8756        if (processName == null) {
8757            return defProcessName;
8758        }
8759        return processName;
8760    }
8761
8762    /**
8763     * Enforces that only the system UID or root's UID can call a method exposed
8764     * via Binder.
8765     *
8766     * @param message used as message if SecurityException is thrown
8767     * @throws SecurityException if the caller is not system or root
8768     */
8769    private static final void enforceSystemOrRoot(String message) {
8770        final int uid = Binder.getCallingUid();
8771        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8772            throw new SecurityException(message);
8773        }
8774    }
8775
8776    @Override
8777    public void performFstrimIfNeeded() {
8778        enforceSystemOrRoot("Only the system can request fstrim");
8779
8780        // Before everything else, see whether we need to fstrim.
8781        try {
8782            IStorageManager sm = PackageHelper.getStorageManager();
8783            if (sm != null) {
8784                boolean doTrim = false;
8785                final long interval = android.provider.Settings.Global.getLong(
8786                        mContext.getContentResolver(),
8787                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8788                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8789                if (interval > 0) {
8790                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8791                    if (timeSinceLast > interval) {
8792                        doTrim = true;
8793                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8794                                + "; running immediately");
8795                    }
8796                }
8797                if (doTrim) {
8798                    final boolean dexOptDialogShown;
8799                    synchronized (mPackages) {
8800                        dexOptDialogShown = mDexOptDialogShown;
8801                    }
8802                    if (!isFirstBoot() && dexOptDialogShown) {
8803                        try {
8804                            ActivityManager.getService().showBootMessage(
8805                                    mContext.getResources().getString(
8806                                            R.string.android_upgrading_fstrim), true);
8807                        } catch (RemoteException e) {
8808                        }
8809                    }
8810                    sm.runMaintenance();
8811                }
8812            } else {
8813                Slog.e(TAG, "storageManager service unavailable!");
8814            }
8815        } catch (RemoteException e) {
8816            // Can't happen; StorageManagerService is local
8817        }
8818    }
8819
8820    @Override
8821    public void updatePackagesIfNeeded() {
8822        enforceSystemOrRoot("Only the system can request package update");
8823
8824        // We need to re-extract after an OTA.
8825        boolean causeUpgrade = isUpgrade();
8826
8827        // First boot or factory reset.
8828        // Note: we also handle devices that are upgrading to N right now as if it is their
8829        //       first boot, as they do not have profile data.
8830        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8831
8832        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8833        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8834
8835        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8836            return;
8837        }
8838
8839        List<PackageParser.Package> pkgs;
8840        synchronized (mPackages) {
8841            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8842        }
8843
8844        final long startTime = System.nanoTime();
8845        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8846                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
8847                    false /* bootComplete */);
8848
8849        final int elapsedTimeSeconds =
8850                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8851
8852        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8853        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8854        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8855        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8856        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8857    }
8858
8859    /*
8860     * Return the prebuilt profile path given a package base code path.
8861     */
8862    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8863        return pkg.baseCodePath + ".prof";
8864    }
8865
8866    /**
8867     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8868     * containing statistics about the invocation. The array consists of three elements,
8869     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8870     * and {@code numberOfPackagesFailed}.
8871     */
8872    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8873            final int compilationReason, boolean bootComplete) {
8874
8875        int numberOfPackagesVisited = 0;
8876        int numberOfPackagesOptimized = 0;
8877        int numberOfPackagesSkipped = 0;
8878        int numberOfPackagesFailed = 0;
8879        final int numberOfPackagesToDexopt = pkgs.size();
8880
8881        for (PackageParser.Package pkg : pkgs) {
8882            numberOfPackagesVisited++;
8883
8884            boolean useProfileForDexopt = false;
8885
8886            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8887                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8888                // that are already compiled.
8889                File profileFile = new File(getPrebuildProfilePath(pkg));
8890                // Copy profile if it exists.
8891                if (profileFile.exists()) {
8892                    try {
8893                        // We could also do this lazily before calling dexopt in
8894                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8895                        // is that we don't have a good way to say "do this only once".
8896                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8897                                pkg.applicationInfo.uid, pkg.packageName,
8898                                ArtManager.getProfileName(null))) {
8899                            Log.e(TAG, "Installer failed to copy system profile!");
8900                        } else {
8901                            // Disabled as this causes speed-profile compilation during first boot
8902                            // even if things are already compiled.
8903                            // useProfileForDexopt = true;
8904                        }
8905                    } catch (Exception e) {
8906                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8907                                e);
8908                    }
8909                } else {
8910                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8911                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8912                    // minimize the number off apps being speed-profile compiled during first boot.
8913                    // The other paths will not change the filter.
8914                    if (disabledPs != null && disabledPs.pkg.isStub) {
8915                        // The package is the stub one, remove the stub suffix to get the normal
8916                        // package and APK names.
8917                        String systemProfilePath =
8918                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8919                        profileFile = new File(systemProfilePath);
8920                        // If we have a profile for a compressed APK, copy it to the reference
8921                        // location.
8922                        // Note that copying the profile here will cause it to override the
8923                        // reference profile every OTA even though the existing reference profile
8924                        // may have more data. We can't copy during decompression since the
8925                        // directories are not set up at that point.
8926                        if (profileFile.exists()) {
8927                            try {
8928                                // We could also do this lazily before calling dexopt in
8929                                // PackageDexOptimizer to prevent this happening on first boot. The
8930                                // issue is that we don't have a good way to say "do this only
8931                                // once".
8932                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8933                                        pkg.applicationInfo.uid, pkg.packageName,
8934                                        ArtManager.getProfileName(null))) {
8935                                    Log.e(TAG, "Failed to copy system profile for stub package!");
8936                                } else {
8937                                    useProfileForDexopt = true;
8938                                }
8939                            } catch (Exception e) {
8940                                Log.e(TAG, "Failed to copy profile " +
8941                                        profileFile.getAbsolutePath() + " ", e);
8942                            }
8943                        }
8944                    }
8945                }
8946            }
8947
8948            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8949                if (DEBUG_DEXOPT) {
8950                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8951                }
8952                numberOfPackagesSkipped++;
8953                continue;
8954            }
8955
8956            if (DEBUG_DEXOPT) {
8957                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8958                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8959            }
8960
8961            if (showDialog) {
8962                try {
8963                    ActivityManager.getService().showBootMessage(
8964                            mContext.getResources().getString(R.string.android_upgrading_apk,
8965                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8966                } catch (RemoteException e) {
8967                }
8968                synchronized (mPackages) {
8969                    mDexOptDialogShown = true;
8970                }
8971            }
8972
8973            int pkgCompilationReason = compilationReason;
8974            if (useProfileForDexopt) {
8975                // Use background dexopt mode to try and use the profile. Note that this does not
8976                // guarantee usage of the profile.
8977                pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT;
8978            }
8979
8980            // checkProfiles is false to avoid merging profiles during boot which
8981            // might interfere with background compilation (b/28612421).
8982            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8983            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8984            // trade-off worth doing to save boot time work.
8985            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
8986            if (compilationReason == REASON_FIRST_BOOT) {
8987                // TODO: This doesn't cover the upgrade case, we should check for this too.
8988                dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE;
8989            }
8990            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
8991                    pkg.packageName,
8992                    pkgCompilationReason,
8993                    dexoptFlags));
8994
8995            switch (primaryDexOptStaus) {
8996                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8997                    numberOfPackagesOptimized++;
8998                    break;
8999                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9000                    numberOfPackagesSkipped++;
9001                    break;
9002                case PackageDexOptimizer.DEX_OPT_FAILED:
9003                    numberOfPackagesFailed++;
9004                    break;
9005                default:
9006                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9007                    break;
9008            }
9009        }
9010
9011        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9012                numberOfPackagesFailed };
9013    }
9014
9015    @Override
9016    public void notifyPackageUse(String packageName, int reason) {
9017        synchronized (mPackages) {
9018            final int callingUid = Binder.getCallingUid();
9019            final int callingUserId = UserHandle.getUserId(callingUid);
9020            if (getInstantAppPackageName(callingUid) != null) {
9021                if (!isCallerSameApp(packageName, callingUid)) {
9022                    return;
9023                }
9024            } else {
9025                if (isInstantApp(packageName, callingUserId)) {
9026                    return;
9027                }
9028            }
9029            notifyPackageUseLocked(packageName, reason);
9030        }
9031    }
9032
9033    @GuardedBy("mPackages")
9034    private void notifyPackageUseLocked(String packageName, int reason) {
9035        final PackageParser.Package p = mPackages.get(packageName);
9036        if (p == null) {
9037            return;
9038        }
9039        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9040    }
9041
9042    @Override
9043    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9044            List<String> classPaths, String loaderIsa) {
9045        int userId = UserHandle.getCallingUserId();
9046        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9047        if (ai == null) {
9048            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9049                + loadingPackageName + ", user=" + userId);
9050            return;
9051        }
9052        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9053    }
9054
9055    @Override
9056    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9057            IDexModuleRegisterCallback callback) {
9058        int userId = UserHandle.getCallingUserId();
9059        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9060        DexManager.RegisterDexModuleResult result;
9061        if (ai == null) {
9062            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9063                     " calling user. package=" + packageName + ", user=" + userId);
9064            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9065        } else {
9066            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9067        }
9068
9069        if (callback != null) {
9070            mHandler.post(() -> {
9071                try {
9072                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9073                } catch (RemoteException e) {
9074                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9075                }
9076            });
9077        }
9078    }
9079
9080    /**
9081     * Ask the package manager to perform a dex-opt with the given compiler filter.
9082     *
9083     * Note: exposed only for the shell command to allow moving packages explicitly to a
9084     *       definite state.
9085     */
9086    @Override
9087    public boolean performDexOptMode(String packageName,
9088            boolean checkProfiles, String targetCompilerFilter, boolean force,
9089            boolean bootComplete, String splitName) {
9090        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9091                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9092                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9093        return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN,
9094                targetCompilerFilter, splitName, flags));
9095    }
9096
9097    /**
9098     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9099     * secondary dex files belonging to the given package.
9100     *
9101     * Note: exposed only for the shell command to allow moving packages explicitly to a
9102     *       definite state.
9103     */
9104    @Override
9105    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9106            boolean force) {
9107        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9108                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9109                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9110                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9111        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9112    }
9113
9114    /*package*/ boolean performDexOpt(DexoptOptions options) {
9115        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9116            return false;
9117        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9118            return false;
9119        }
9120
9121        if (options.isDexoptOnlySecondaryDex()) {
9122            return mDexManager.dexoptSecondaryDex(options);
9123        } else {
9124            int dexoptStatus = performDexOptWithStatus(options);
9125            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9126        }
9127    }
9128
9129    /**
9130     * Perform dexopt on the given package and return one of following result:
9131     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9132     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9133     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9134     */
9135    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9136        return performDexOptTraced(options);
9137    }
9138
9139    private int performDexOptTraced(DexoptOptions options) {
9140        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9141        try {
9142            return performDexOptInternal(options);
9143        } finally {
9144            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9145        }
9146    }
9147
9148    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9149    // if the package can now be considered up to date for the given filter.
9150    private int performDexOptInternal(DexoptOptions options) {
9151        PackageParser.Package p;
9152        synchronized (mPackages) {
9153            p = mPackages.get(options.getPackageName());
9154            if (p == null) {
9155                // Package could not be found. Report failure.
9156                return PackageDexOptimizer.DEX_OPT_FAILED;
9157            }
9158            mPackageUsage.maybeWriteAsync(mPackages);
9159            mCompilerStats.maybeWriteAsync();
9160        }
9161        long callingId = Binder.clearCallingIdentity();
9162        try {
9163            synchronized (mInstallLock) {
9164                return performDexOptInternalWithDependenciesLI(p, options);
9165            }
9166        } finally {
9167            Binder.restoreCallingIdentity(callingId);
9168        }
9169    }
9170
9171    public ArraySet<String> getOptimizablePackages() {
9172        ArraySet<String> pkgs = new ArraySet<String>();
9173        synchronized (mPackages) {
9174            for (PackageParser.Package p : mPackages.values()) {
9175                if (PackageDexOptimizer.canOptimizePackage(p)) {
9176                    pkgs.add(p.packageName);
9177                }
9178            }
9179        }
9180        return pkgs;
9181    }
9182
9183    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9184            DexoptOptions options) {
9185        // Select the dex optimizer based on the force parameter.
9186        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9187        //       allocate an object here.
9188        PackageDexOptimizer pdo = options.isForce()
9189                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9190                : mPackageDexOptimizer;
9191
9192        // Dexopt all dependencies first. Note: we ignore the return value and march on
9193        // on errors.
9194        // Note that we are going to call performDexOpt on those libraries as many times as
9195        // they are referenced in packages. When we do a batch of performDexOpt (for example
9196        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9197        // and the first package that uses the library will dexopt it. The
9198        // others will see that the compiled code for the library is up to date.
9199        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9200        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9201        if (!deps.isEmpty()) {
9202            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9203                    options.getCompilationReason(), options.getCompilerFilter(),
9204                    options.getSplitName(),
9205                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9206            for (PackageParser.Package depPackage : deps) {
9207                // TODO: Analyze and investigate if we (should) profile libraries.
9208                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9209                        getOrCreateCompilerPackageStats(depPackage),
9210                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9211            }
9212        }
9213        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9214                getOrCreateCompilerPackageStats(p),
9215                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9216    }
9217
9218    /**
9219     * Reconcile the information we have about the secondary dex files belonging to
9220     * {@code packagName} and the actual dex files. For all dex files that were
9221     * deleted, update the internal records and delete the generated oat files.
9222     */
9223    @Override
9224    public void reconcileSecondaryDexFiles(String packageName) {
9225        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9226            return;
9227        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9228            return;
9229        }
9230        mDexManager.reconcileSecondaryDexFiles(packageName);
9231    }
9232
9233    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9234    // a reference there.
9235    /*package*/ DexManager getDexManager() {
9236        return mDexManager;
9237    }
9238
9239    /**
9240     * Execute the background dexopt job immediately.
9241     */
9242    @Override
9243    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9244        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9245            return false;
9246        }
9247        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9248    }
9249
9250    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9251        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9252                || p.usesStaticLibraries != null) {
9253            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9254            Set<String> collectedNames = new HashSet<>();
9255            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9256
9257            retValue.remove(p);
9258
9259            return retValue;
9260        } else {
9261            return Collections.emptyList();
9262        }
9263    }
9264
9265    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9266            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9267        if (!collectedNames.contains(p.packageName)) {
9268            collectedNames.add(p.packageName);
9269            collected.add(p);
9270
9271            if (p.usesLibraries != null) {
9272                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9273                        null, collected, collectedNames);
9274            }
9275            if (p.usesOptionalLibraries != null) {
9276                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9277                        null, collected, collectedNames);
9278            }
9279            if (p.usesStaticLibraries != null) {
9280                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9281                        p.usesStaticLibrariesVersions, collected, collectedNames);
9282            }
9283        }
9284    }
9285
9286    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9287            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9288        final int libNameCount = libs.size();
9289        for (int i = 0; i < libNameCount; i++) {
9290            String libName = libs.get(i);
9291            long version = (versions != null && versions.length == libNameCount)
9292                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9293            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9294            if (libPkg != null) {
9295                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9296            }
9297        }
9298    }
9299
9300    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9301        synchronized (mPackages) {
9302            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9303            if (libEntry != null) {
9304                return mPackages.get(libEntry.apk);
9305            }
9306            return null;
9307        }
9308    }
9309
9310    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9311        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9312        if (versionedLib == null) {
9313            return null;
9314        }
9315        return versionedLib.get(version);
9316    }
9317
9318    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9319        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9320                pkg.staticSharedLibName);
9321        if (versionedLib == null) {
9322            return null;
9323        }
9324        long previousLibVersion = -1;
9325        final int versionCount = versionedLib.size();
9326        for (int i = 0; i < versionCount; i++) {
9327            final long libVersion = versionedLib.keyAt(i);
9328            if (libVersion < pkg.staticSharedLibVersion) {
9329                previousLibVersion = Math.max(previousLibVersion, libVersion);
9330            }
9331        }
9332        if (previousLibVersion >= 0) {
9333            return versionedLib.get(previousLibVersion);
9334        }
9335        return null;
9336    }
9337
9338    public void shutdown() {
9339        mPackageUsage.writeNow(mPackages);
9340        mCompilerStats.writeNow();
9341        mDexManager.writePackageDexUsageNow();
9342    }
9343
9344    @Override
9345    public void dumpProfiles(String packageName) {
9346        PackageParser.Package pkg;
9347        synchronized (mPackages) {
9348            pkg = mPackages.get(packageName);
9349            if (pkg == null) {
9350                throw new IllegalArgumentException("Unknown package: " + packageName);
9351            }
9352        }
9353        /* Only the shell, root, or the app user should be able to dump profiles. */
9354        int callingUid = Binder.getCallingUid();
9355        if (callingUid != Process.SHELL_UID &&
9356            callingUid != Process.ROOT_UID &&
9357            callingUid != pkg.applicationInfo.uid) {
9358            throw new SecurityException("dumpProfiles");
9359        }
9360
9361        synchronized (mInstallLock) {
9362            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9363            mArtManagerService.dumpProfiles(pkg);
9364            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9365        }
9366    }
9367
9368    @Override
9369    public void forceDexOpt(String packageName) {
9370        enforceSystemOrRoot("forceDexOpt");
9371
9372        PackageParser.Package pkg;
9373        synchronized (mPackages) {
9374            pkg = mPackages.get(packageName);
9375            if (pkg == null) {
9376                throw new IllegalArgumentException("Unknown package: " + packageName);
9377            }
9378        }
9379
9380        synchronized (mInstallLock) {
9381            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9382
9383            // Whoever is calling forceDexOpt wants a compiled package.
9384            // Don't use profiles since that may cause compilation to be skipped.
9385            final int res = performDexOptInternalWithDependenciesLI(
9386                    pkg,
9387                    new DexoptOptions(packageName,
9388                            getDefaultCompilerFilter(),
9389                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9390
9391            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9392            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9393                throw new IllegalStateException("Failed to dexopt: " + res);
9394            }
9395        }
9396    }
9397
9398    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9399        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9400            Slog.w(TAG, "Unable to update from " + oldPkg.name
9401                    + " to " + newPkg.packageName
9402                    + ": old package not in system partition");
9403            return false;
9404        } else if (mPackages.get(oldPkg.name) != null) {
9405            Slog.w(TAG, "Unable to update from " + oldPkg.name
9406                    + " to " + newPkg.packageName
9407                    + ": old package still exists");
9408            return false;
9409        }
9410        return true;
9411    }
9412
9413    void removeCodePathLI(File codePath) {
9414        if (codePath.isDirectory()) {
9415            try {
9416                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9417            } catch (InstallerException e) {
9418                Slog.w(TAG, "Failed to remove code path", e);
9419            }
9420        } else {
9421            codePath.delete();
9422        }
9423    }
9424
9425    private int[] resolveUserIds(int userId) {
9426        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9427    }
9428
9429    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9430        if (pkg == null) {
9431            Slog.wtf(TAG, "Package was null!", new Throwable());
9432            return;
9433        }
9434        clearAppDataLeafLIF(pkg, userId, flags);
9435        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9436        for (int i = 0; i < childCount; i++) {
9437            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9438        }
9439
9440        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9441    }
9442
9443    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9444        final PackageSetting ps;
9445        synchronized (mPackages) {
9446            ps = mSettings.mPackages.get(pkg.packageName);
9447        }
9448        for (int realUserId : resolveUserIds(userId)) {
9449            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9450            try {
9451                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9452                        ceDataInode);
9453            } catch (InstallerException e) {
9454                Slog.w(TAG, String.valueOf(e));
9455            }
9456        }
9457    }
9458
9459    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9460        if (pkg == null) {
9461            Slog.wtf(TAG, "Package was null!", new Throwable());
9462            return;
9463        }
9464        destroyAppDataLeafLIF(pkg, userId, flags);
9465        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9466        for (int i = 0; i < childCount; i++) {
9467            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9468        }
9469    }
9470
9471    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9472        final PackageSetting ps;
9473        synchronized (mPackages) {
9474            ps = mSettings.mPackages.get(pkg.packageName);
9475        }
9476        for (int realUserId : resolveUserIds(userId)) {
9477            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9478            try {
9479                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9480                        ceDataInode);
9481            } catch (InstallerException e) {
9482                Slog.w(TAG, String.valueOf(e));
9483            }
9484            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9485        }
9486    }
9487
9488    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9489        if (pkg == null) {
9490            Slog.wtf(TAG, "Package was null!", new Throwable());
9491            return;
9492        }
9493        destroyAppProfilesLeafLIF(pkg);
9494        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9495        for (int i = 0; i < childCount; i++) {
9496            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9497        }
9498    }
9499
9500    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9501        try {
9502            mInstaller.destroyAppProfiles(pkg.packageName);
9503        } catch (InstallerException e) {
9504            Slog.w(TAG, String.valueOf(e));
9505        }
9506    }
9507
9508    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9509        if (pkg == null) {
9510            Slog.wtf(TAG, "Package was null!", new Throwable());
9511            return;
9512        }
9513        mArtManagerService.clearAppProfiles(pkg);
9514        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9515        for (int i = 0; i < childCount; i++) {
9516            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9517        }
9518    }
9519
9520    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9521            long lastUpdateTime) {
9522        // Set parent install/update time
9523        PackageSetting ps = (PackageSetting) pkg.mExtras;
9524        if (ps != null) {
9525            ps.firstInstallTime = firstInstallTime;
9526            ps.lastUpdateTime = lastUpdateTime;
9527        }
9528        // Set children install/update time
9529        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9530        for (int i = 0; i < childCount; i++) {
9531            PackageParser.Package childPkg = pkg.childPackages.get(i);
9532            ps = (PackageSetting) childPkg.mExtras;
9533            if (ps != null) {
9534                ps.firstInstallTime = firstInstallTime;
9535                ps.lastUpdateTime = lastUpdateTime;
9536            }
9537        }
9538    }
9539
9540    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9541            SharedLibraryEntry file,
9542            PackageParser.Package changingLib) {
9543        if (file.path != null) {
9544            usesLibraryFiles.add(file.path);
9545            return;
9546        }
9547        PackageParser.Package p = mPackages.get(file.apk);
9548        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9549            // If we are doing this while in the middle of updating a library apk,
9550            // then we need to make sure to use that new apk for determining the
9551            // dependencies here.  (We haven't yet finished committing the new apk
9552            // to the package manager state.)
9553            if (p == null || p.packageName.equals(changingLib.packageName)) {
9554                p = changingLib;
9555            }
9556        }
9557        if (p != null) {
9558            usesLibraryFiles.addAll(p.getAllCodePaths());
9559            if (p.usesLibraryFiles != null) {
9560                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9561            }
9562        }
9563    }
9564
9565    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9566            PackageParser.Package changingLib) throws PackageManagerException {
9567        if (pkg == null) {
9568            return;
9569        }
9570        // The collection used here must maintain the order of addition (so
9571        // that libraries are searched in the correct order) and must have no
9572        // duplicates.
9573        Set<String> usesLibraryFiles = null;
9574        if (pkg.usesLibraries != null) {
9575            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9576                    null, null, pkg.packageName, changingLib, true,
9577                    pkg.applicationInfo.targetSdkVersion, null);
9578        }
9579        if (pkg.usesStaticLibraries != null) {
9580            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9581                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9582                    pkg.packageName, changingLib, true,
9583                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9584        }
9585        if (pkg.usesOptionalLibraries != null) {
9586            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9587                    null, null, pkg.packageName, changingLib, false,
9588                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9589        }
9590        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9591            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9592        } else {
9593            pkg.usesLibraryFiles = null;
9594        }
9595    }
9596
9597    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9598            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9599            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9600            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9601            throws PackageManagerException {
9602        final int libCount = requestedLibraries.size();
9603        for (int i = 0; i < libCount; i++) {
9604            final String libName = requestedLibraries.get(i);
9605            final long libVersion = requiredVersions != null ? requiredVersions[i]
9606                    : SharedLibraryInfo.VERSION_UNDEFINED;
9607            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9608            if (libEntry == null) {
9609                if (required) {
9610                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9611                            "Package " + packageName + " requires unavailable shared library "
9612                                    + libName + "; failing!");
9613                } else if (DEBUG_SHARED_LIBRARIES) {
9614                    Slog.i(TAG, "Package " + packageName
9615                            + " desires unavailable shared library "
9616                            + libName + "; ignoring!");
9617                }
9618            } else {
9619                if (requiredVersions != null && requiredCertDigests != null) {
9620                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9621                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9622                            "Package " + packageName + " requires unavailable static shared"
9623                                    + " library " + libName + " version "
9624                                    + libEntry.info.getLongVersion() + "; failing!");
9625                    }
9626
9627                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9628                    if (libPkg == null) {
9629                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9630                                "Package " + packageName + " requires unavailable static shared"
9631                                        + " library; failing!");
9632                    }
9633
9634                    final String[] expectedCertDigests = requiredCertDigests[i];
9635
9636
9637                    if (expectedCertDigests.length > 1) {
9638
9639                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9640                        final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9641                                ? PackageUtils.computeSignaturesSha256Digests(
9642                                libPkg.mSigningDetails.signatures)
9643                                : PackageUtils.computeSignaturesSha256Digests(
9644                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9645
9646                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9647                        // target O we don't parse the "additional-certificate" tags similarly
9648                        // how we only consider all certs only for apps targeting O (see above).
9649                        // Therefore, the size check is safe to make.
9650                        if (expectedCertDigests.length != libCertDigests.length) {
9651                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9652                                    "Package " + packageName + " requires differently signed" +
9653                                            " static shared library; failing!");
9654                        }
9655
9656                        // Use a predictable order as signature order may vary
9657                        Arrays.sort(libCertDigests);
9658                        Arrays.sort(expectedCertDigests);
9659
9660                        final int certCount = libCertDigests.length;
9661                        for (int j = 0; j < certCount; j++) {
9662                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9663                                throw new PackageManagerException(
9664                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9665                                        "Package " + packageName + " requires differently signed" +
9666                                                " static shared library; failing!");
9667                            }
9668                        }
9669                    } else {
9670
9671                        // lib signing cert could have rotated beyond the one expected, check to see
9672                        // if the new one has been blessed by the old
9673                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9674                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9675                            throw new PackageManagerException(
9676                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9677                                    "Package " + packageName + " requires differently signed" +
9678                                            " static shared library; failing!");
9679                        }
9680                    }
9681                }
9682
9683                if (outUsedLibraries == null) {
9684                    // Use LinkedHashSet to preserve the order of files added to
9685                    // usesLibraryFiles while eliminating duplicates.
9686                    outUsedLibraries = new LinkedHashSet<>();
9687                }
9688                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9689            }
9690        }
9691        return outUsedLibraries;
9692    }
9693
9694    private static boolean hasString(List<String> list, List<String> which) {
9695        if (list == null) {
9696            return false;
9697        }
9698        for (int i=list.size()-1; i>=0; i--) {
9699            for (int j=which.size()-1; j>=0; j--) {
9700                if (which.get(j).equals(list.get(i))) {
9701                    return true;
9702                }
9703            }
9704        }
9705        return false;
9706    }
9707
9708    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9709            PackageParser.Package changingPkg) {
9710        ArrayList<PackageParser.Package> res = null;
9711        for (PackageParser.Package pkg : mPackages.values()) {
9712            if (changingPkg != null
9713                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9714                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9715                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9716                            changingPkg.staticSharedLibName)) {
9717                return null;
9718            }
9719            if (res == null) {
9720                res = new ArrayList<>();
9721            }
9722            res.add(pkg);
9723            try {
9724                updateSharedLibrariesLPr(pkg, changingPkg);
9725            } catch (PackageManagerException e) {
9726                // If a system app update or an app and a required lib missing we
9727                // delete the package and for updated system apps keep the data as
9728                // it is better for the user to reinstall than to be in an limbo
9729                // state. Also libs disappearing under an app should never happen
9730                // - just in case.
9731                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9732                    final int flags = pkg.isUpdatedSystemApp()
9733                            ? PackageManager.DELETE_KEEP_DATA : 0;
9734                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9735                            flags , null, true, null);
9736                }
9737                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9738            }
9739        }
9740        return res;
9741    }
9742
9743    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9744            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9745            @Nullable UserHandle user) throws PackageManagerException {
9746        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9747        // If the package has children and this is the first dive in the function
9748        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9749        // whether all packages (parent and children) would be successfully scanned
9750        // before the actual scan since scanning mutates internal state and we want
9751        // to atomically install the package and its children.
9752        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9753            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9754                scanFlags |= SCAN_CHECK_ONLY;
9755            }
9756        } else {
9757            scanFlags &= ~SCAN_CHECK_ONLY;
9758        }
9759
9760        final PackageParser.Package scannedPkg;
9761        try {
9762            // Scan the parent
9763            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9764            // Scan the children
9765            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9766            for (int i = 0; i < childCount; i++) {
9767                PackageParser.Package childPkg = pkg.childPackages.get(i);
9768                scanPackageNewLI(childPkg, parseFlags,
9769                        scanFlags, currentTime, user);
9770            }
9771        } finally {
9772            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9773        }
9774
9775        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9776            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9777        }
9778
9779        return scannedPkg;
9780    }
9781
9782    /** The result of a package scan. */
9783    private static class ScanResult {
9784        /** Whether or not the package scan was successful */
9785        public final boolean success;
9786        /**
9787         * The final package settings. This may be the same object passed in
9788         * the {@link ScanRequest}, but, with modified values.
9789         */
9790        @Nullable public final PackageSetting pkgSetting;
9791        /** ABI code paths that have changed in the package scan */
9792        @Nullable public final List<String> changedAbiCodePath;
9793        public ScanResult(
9794                boolean success,
9795                @Nullable PackageSetting pkgSetting,
9796                @Nullable List<String> changedAbiCodePath) {
9797            this.success = success;
9798            this.pkgSetting = pkgSetting;
9799            this.changedAbiCodePath = changedAbiCodePath;
9800        }
9801    }
9802
9803    /** A package to be scanned */
9804    private static class ScanRequest {
9805        /** The parsed package */
9806        @NonNull public final PackageParser.Package pkg;
9807        /** Shared user settings, if the package has a shared user */
9808        @Nullable public final SharedUserSetting sharedUserSetting;
9809        /**
9810         * Package settings of the currently installed version.
9811         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9812         * during scan.
9813         */
9814        @Nullable public final PackageSetting pkgSetting;
9815        /** A copy of the settings for the currently installed version */
9816        @Nullable public final PackageSetting oldPkgSetting;
9817        /** Package settings for the disabled version on the /system partition */
9818        @Nullable public final PackageSetting disabledPkgSetting;
9819        /** Package settings for the installed version under its original package name */
9820        @Nullable public final PackageSetting originalPkgSetting;
9821        /** The real package name of a renamed application */
9822        @Nullable public final String realPkgName;
9823        public final @ParseFlags int parseFlags;
9824        public final @ScanFlags int scanFlags;
9825        /** The user for which the package is being scanned */
9826        @Nullable public final UserHandle user;
9827        /** Whether or not the platform package is being scanned */
9828        public final boolean isPlatformPackage;
9829        public ScanRequest(
9830                @NonNull PackageParser.Package pkg,
9831                @Nullable SharedUserSetting sharedUserSetting,
9832                @Nullable PackageSetting pkgSetting,
9833                @Nullable PackageSetting disabledPkgSetting,
9834                @Nullable PackageSetting originalPkgSetting,
9835                @Nullable String realPkgName,
9836                @ParseFlags int parseFlags,
9837                @ScanFlags int scanFlags,
9838                boolean isPlatformPackage,
9839                @Nullable UserHandle user) {
9840            this.pkg = pkg;
9841            this.pkgSetting = pkgSetting;
9842            this.sharedUserSetting = sharedUserSetting;
9843            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9844            this.disabledPkgSetting = disabledPkgSetting;
9845            this.originalPkgSetting = originalPkgSetting;
9846            this.realPkgName = realPkgName;
9847            this.parseFlags = parseFlags;
9848            this.scanFlags = scanFlags;
9849            this.isPlatformPackage = isPlatformPackage;
9850            this.user = user;
9851        }
9852    }
9853
9854    /**
9855     * Returns the actual scan flags depending upon the state of the other settings.
9856     * <p>Updated system applications will not have the following flags set
9857     * by default and need to be adjusted after the fact:
9858     * <ul>
9859     * <li>{@link #SCAN_AS_SYSTEM}</li>
9860     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9861     * <li>{@link #SCAN_AS_OEM}</li>
9862     * <li>{@link #SCAN_AS_VENDOR}</li>
9863     * <li>{@link #SCAN_AS_PRODUCT}</li>
9864     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9865     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9866     * </ul>
9867     */
9868    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9869            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9870            PackageParser.Package pkg) {
9871        if (disabledPkgSetting != null) {
9872            // updated system application, must at least have SCAN_AS_SYSTEM
9873            scanFlags |= SCAN_AS_SYSTEM;
9874            if ((disabledPkgSetting.pkgPrivateFlags
9875                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9876                scanFlags |= SCAN_AS_PRIVILEGED;
9877            }
9878            if ((disabledPkgSetting.pkgPrivateFlags
9879                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9880                scanFlags |= SCAN_AS_OEM;
9881            }
9882            if ((disabledPkgSetting.pkgPrivateFlags
9883                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9884                scanFlags |= SCAN_AS_VENDOR;
9885            }
9886            if ((disabledPkgSetting.pkgPrivateFlags
9887                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9888                scanFlags |= SCAN_AS_PRODUCT;
9889            }
9890        }
9891        if (pkgSetting != null) {
9892            final int userId = ((user == null) ? 0 : user.getIdentifier());
9893            if (pkgSetting.getInstantApp(userId)) {
9894                scanFlags |= SCAN_AS_INSTANT_APP;
9895            }
9896            if (pkgSetting.getVirtulalPreload(userId)) {
9897                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9898            }
9899        }
9900
9901        // Scan as privileged apps that share a user with a priv-app.
9902        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9903                && (pkg.mSharedUserId != null)) {
9904            SharedUserSetting sharedUserSetting = null;
9905            try {
9906                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9907            } catch (PackageManagerException ignore) {}
9908            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9909                // Exempt SharedUsers signed with the platform key.
9910                // TODO(b/72378145) Fix this exemption. Force signature apps
9911                // to whitelist their privileged permissions just like other
9912                // priv-apps.
9913                synchronized (mPackages) {
9914                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9915                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
9916                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
9917                        scanFlags |= SCAN_AS_PRIVILEGED;
9918                    }
9919                }
9920            }
9921        }
9922
9923        return scanFlags;
9924    }
9925
9926    @GuardedBy("mInstallLock")
9927    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
9928            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9929            @Nullable UserHandle user) throws PackageManagerException {
9930
9931        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9932        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
9933        if (realPkgName != null) {
9934            ensurePackageRenamed(pkg, renamedPkgName);
9935        }
9936        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
9937        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9938        final PackageSetting disabledPkgSetting =
9939                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9940
9941        if (mTransferedPackages.contains(pkg.packageName)) {
9942            Slog.w(TAG, "Package " + pkg.packageName
9943                    + " was transferred to another, but its .apk remains");
9944        }
9945
9946        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
9947        synchronized (mPackages) {
9948            applyPolicy(pkg, parseFlags, scanFlags);
9949            assertPackageIsValid(pkg, parseFlags, scanFlags);
9950
9951            SharedUserSetting sharedUserSetting = null;
9952            if (pkg.mSharedUserId != null) {
9953                // SIDE EFFECTS; may potentially allocate a new shared user
9954                sharedUserSetting = mSettings.getSharedUserLPw(
9955                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9956                if (DEBUG_PACKAGE_SCANNING) {
9957                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
9958                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
9959                                + " (uid=" + sharedUserSetting.userId + "):"
9960                                + " packages=" + sharedUserSetting.packages);
9961                }
9962            }
9963
9964            boolean scanSucceeded = false;
9965            try {
9966                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
9967                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
9968                        (pkg == mPlatformPackage), user);
9969                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
9970                if (result.success) {
9971                    commitScanResultsLocked(request, result);
9972                }
9973                scanSucceeded = true;
9974            } finally {
9975                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9976                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
9977                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9978                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9979                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9980                  }
9981            }
9982        }
9983        return pkg;
9984    }
9985
9986    /**
9987     * Commits the package scan and modifies system state.
9988     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
9989     * of committing the package, leaving the system in an inconsistent state.
9990     * This needs to be fixed so, once we get to this point, no errors are
9991     * possible and the system is not left in an inconsistent state.
9992     */
9993    @GuardedBy("mPackages")
9994    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
9995            throws PackageManagerException {
9996        final PackageParser.Package pkg = request.pkg;
9997        final @ParseFlags int parseFlags = request.parseFlags;
9998        final @ScanFlags int scanFlags = request.scanFlags;
9999        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10000        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10001        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10002        final UserHandle user = request.user;
10003        final String realPkgName = request.realPkgName;
10004        final PackageSetting pkgSetting = result.pkgSetting;
10005        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10006        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10007
10008        if (newPkgSettingCreated) {
10009            if (originalPkgSetting != null) {
10010                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10011            }
10012            // THROWS: when we can't allocate a user id. add call to check if there's
10013            // enough space to ensure we won't throw; otherwise, don't modify state
10014            mSettings.addUserToSettingLPw(pkgSetting);
10015
10016            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10017                mTransferedPackages.add(originalPkgSetting.name);
10018            }
10019        }
10020        // TODO(toddke): Consider a method specifically for modifying the Package object
10021        // post scan; or, moving this stuff out of the Package object since it has nothing
10022        // to do with the package on disk.
10023        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10024        // for creating the application ID. If we did this earlier, we would be saving the
10025        // correct ID.
10026        pkg.applicationInfo.uid = pkgSetting.appId;
10027
10028        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10029
10030        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10031            mTransferedPackages.add(pkg.packageName);
10032        }
10033
10034        // THROWS: when requested libraries that can't be found. it only changes
10035        // the state of the passed in pkg object, so, move to the top of the method
10036        // and allow it to abort
10037        if ((scanFlags & SCAN_BOOTING) == 0
10038                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10039            // Check all shared libraries and map to their actual file path.
10040            // We only do this here for apps not on a system dir, because those
10041            // are the only ones that can fail an install due to this.  We
10042            // will take care of the system apps by updating all of their
10043            // library paths after the scan is done. Also during the initial
10044            // scan don't update any libs as we do this wholesale after all
10045            // apps are scanned to avoid dependency based scanning.
10046            updateSharedLibrariesLPr(pkg, null);
10047        }
10048
10049        // All versions of a static shared library are referenced with the same
10050        // package name. Internally, we use a synthetic package name to allow
10051        // multiple versions of the same shared library to be installed. So,
10052        // we need to generate the synthetic package name of the latest shared
10053        // library in order to compare signatures.
10054        PackageSetting signatureCheckPs = pkgSetting;
10055        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10056            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10057            if (libraryEntry != null) {
10058                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10059            }
10060        }
10061
10062        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10063        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10064            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10065                // We just determined the app is signed correctly, so bring
10066                // over the latest parsed certs.
10067                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10068            } else {
10069                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10070                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10071                            "Package " + pkg.packageName + " upgrade keys do not match the "
10072                                    + "previously installed version");
10073                } else {
10074                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10075                    String msg = "System package " + pkg.packageName
10076                            + " signature changed; retaining data.";
10077                    reportSettingsProblem(Log.WARN, msg);
10078                }
10079            }
10080        } else {
10081            try {
10082                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10083                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10084                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10085                        pkg.mSigningDetails, compareCompat, compareRecover);
10086                // The new KeySets will be re-added later in the scanning process.
10087                if (compatMatch) {
10088                    synchronized (mPackages) {
10089                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10090                    }
10091                }
10092                // We just determined the app is signed correctly, so bring
10093                // over the latest parsed certs.
10094                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10095
10096
10097                // if this is is a sharedUser, check to see if the new package is signed by a newer
10098                // signing certificate than the existing one, and if so, copy over the new details
10099                if (signatureCheckPs.sharedUser != null
10100                        && pkg.mSigningDetails.hasAncestor(
10101                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10102                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10103                }
10104            } catch (PackageManagerException e) {
10105                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10106                    throw e;
10107                }
10108                // The signature has changed, but this package is in the system
10109                // image...  let's recover!
10110                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10111                // However...  if this package is part of a shared user, but it
10112                // doesn't match the signature of the shared user, let's fail.
10113                // What this means is that you can't change the signatures
10114                // associated with an overall shared user, which doesn't seem all
10115                // that unreasonable.
10116                if (signatureCheckPs.sharedUser != null) {
10117                    if (compareSignatures(
10118                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10119                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10120                        throw new PackageManagerException(
10121                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10122                                "Signature mismatch for shared user: "
10123                                        + pkgSetting.sharedUser);
10124                    }
10125                }
10126                // File a report about this.
10127                String msg = "System package " + pkg.packageName
10128                        + " signature changed; retaining data.";
10129                reportSettingsProblem(Log.WARN, msg);
10130            } catch (IllegalArgumentException e) {
10131
10132                // should never happen: certs matched when checking, but not when comparing
10133                // old to new for sharedUser
10134                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10135                        "Signing certificates comparison made on incomparable signing details"
10136                        + " but somehow passed verifySignatures!");
10137            }
10138        }
10139
10140        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10141            // This package wants to adopt ownership of permissions from
10142            // another package.
10143            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10144                final String origName = pkg.mAdoptPermissions.get(i);
10145                final PackageSetting orig = mSettings.getPackageLPr(origName);
10146                if (orig != null) {
10147                    if (verifyPackageUpdateLPr(orig, pkg)) {
10148                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10149                                + pkg.packageName);
10150                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10151                    }
10152                }
10153            }
10154        }
10155
10156        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10157            for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
10158                final String codePathString = changedAbiCodePath.get(i);
10159                try {
10160                    mInstaller.rmdex(codePathString,
10161                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10162                } catch (InstallerException ignored) {
10163                }
10164            }
10165        }
10166
10167        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10168            if (oldPkgSetting != null) {
10169                synchronized (mPackages) {
10170                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10171                }
10172            }
10173        } else {
10174            final int userId = user == null ? 0 : user.getIdentifier();
10175            // Modify state for the given package setting
10176            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10177                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10178            if (pkgSetting.getInstantApp(userId)) {
10179                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10180            }
10181        }
10182    }
10183
10184    /**
10185     * Returns the "real" name of the package.
10186     * <p>This may differ from the package's actual name if the application has already
10187     * been installed under one of this package's original names.
10188     */
10189    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10190            @Nullable String renamedPkgName) {
10191        if (isPackageRenamed(pkg, renamedPkgName)) {
10192            return pkg.mRealPackage;
10193        }
10194        return null;
10195    }
10196
10197    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10198    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10199            @Nullable String renamedPkgName) {
10200        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10201    }
10202
10203    /**
10204     * Returns the original package setting.
10205     * <p>A package can migrate its name during an update. In this scenario, a package
10206     * designates a set of names that it considers as one of its original names.
10207     * <p>An original package must be signed identically and it must have the same
10208     * shared user [if any].
10209     */
10210    @GuardedBy("mPackages")
10211    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10212            @Nullable String renamedPkgName) {
10213        if (!isPackageRenamed(pkg, renamedPkgName)) {
10214            return null;
10215        }
10216        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10217            final PackageSetting originalPs =
10218                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10219            if (originalPs != null) {
10220                // the package is already installed under its original name...
10221                // but, should we use it?
10222                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10223                    // the new package is incompatible with the original
10224                    continue;
10225                } else if (originalPs.sharedUser != null) {
10226                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10227                        // the shared user id is incompatible with the original
10228                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10229                                + " to " + pkg.packageName + ": old uid "
10230                                + originalPs.sharedUser.name
10231                                + " differs from " + pkg.mSharedUserId);
10232                        continue;
10233                    }
10234                    // TODO: Add case when shared user id is added [b/28144775]
10235                } else {
10236                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10237                            + pkg.packageName + " to old name " + originalPs.name);
10238                }
10239                return originalPs;
10240            }
10241        }
10242        return null;
10243    }
10244
10245    /**
10246     * Renames the package if it was installed under a different name.
10247     * <p>When we've already installed the package under an original name, update
10248     * the new package so we can continue to have the old name.
10249     */
10250    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10251            @NonNull String renamedPackageName) {
10252        if (pkg.mOriginalPackages == null
10253                || !pkg.mOriginalPackages.contains(renamedPackageName)
10254                || pkg.packageName.equals(renamedPackageName)) {
10255            return;
10256        }
10257        pkg.setPackageName(renamedPackageName);
10258    }
10259
10260    /**
10261     * Just scans the package without any side effects.
10262     * <p>Not entirely true at the moment. There is still one side effect -- this
10263     * method potentially modifies a live {@link PackageSetting} object representing
10264     * the package being scanned. This will be resolved in the future.
10265     *
10266     * @param request Information about the package to be scanned
10267     * @param isUnderFactoryTest Whether or not the device is under factory test
10268     * @param currentTime The current time, in millis
10269     * @return The results of the scan
10270     */
10271    @GuardedBy("mInstallLock")
10272    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10273            boolean isUnderFactoryTest, long currentTime)
10274                    throws PackageManagerException {
10275        final PackageParser.Package pkg = request.pkg;
10276        PackageSetting pkgSetting = request.pkgSetting;
10277        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10278        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10279        final @ParseFlags int parseFlags = request.parseFlags;
10280        final @ScanFlags int scanFlags = request.scanFlags;
10281        final String realPkgName = request.realPkgName;
10282        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10283        final UserHandle user = request.user;
10284        final boolean isPlatformPackage = request.isPlatformPackage;
10285
10286        List<String> changedAbiCodePath = null;
10287
10288        if (DEBUG_PACKAGE_SCANNING) {
10289            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10290                Log.d(TAG, "Scanning package " + pkg.packageName);
10291        }
10292
10293        if (Build.IS_DEBUGGABLE &&
10294                pkg.isPrivileged() &&
10295                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10296            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10297        }
10298
10299        // Initialize package source and resource directories
10300        final File scanFile = new File(pkg.codePath);
10301        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10302        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10303
10304        // We keep references to the derived CPU Abis from settings in oder to reuse
10305        // them in the case where we're not upgrading or booting for the first time.
10306        String primaryCpuAbiFromSettings = null;
10307        String secondaryCpuAbiFromSettings = null;
10308        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10309
10310        if (!needToDeriveAbi) {
10311            if (pkgSetting != null) {
10312                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10313                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10314            } else {
10315                // Re-scanning a system package after uninstalling updates; need to derive ABI
10316                needToDeriveAbi = true;
10317            }
10318        }
10319
10320        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10321            PackageManagerService.reportSettingsProblem(Log.WARN,
10322                    "Package " + pkg.packageName + " shared user changed from "
10323                            + (pkgSetting.sharedUser != null
10324                            ? pkgSetting.sharedUser.name : "<nothing>")
10325                            + " to "
10326                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10327                            + "; replacing with new");
10328            pkgSetting = null;
10329        }
10330
10331        String[] usesStaticLibraries = null;
10332        if (pkg.usesStaticLibraries != null) {
10333            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10334            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10335        }
10336        final boolean createNewPackage = (pkgSetting == null);
10337        if (createNewPackage) {
10338            final String parentPackageName = (pkg.parentPackage != null)
10339                    ? pkg.parentPackage.packageName : null;
10340            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10341            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10342            // REMOVE SharedUserSetting from method; update in a separate call
10343            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10344                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10345                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10346                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10347                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10348                    user, true /*allowInstall*/, instantApp, virtualPreload,
10349                    parentPackageName, pkg.getChildPackageNames(),
10350                    UserManagerService.getInstance(), usesStaticLibraries,
10351                    pkg.usesStaticLibrariesVersions);
10352        } else {
10353            // REMOVE SharedUserSetting from method; update in a separate call.
10354            //
10355            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10356            // secondaryCpuAbi are not known at this point so we always update them
10357            // to null here, only to reset them at a later point.
10358            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10359                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10360                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10361                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10362                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10363                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10364        }
10365        if (createNewPackage && originalPkgSetting != null) {
10366            // This is the initial transition from the original package, so,
10367            // fix up the new package's name now. We must do this after looking
10368            // up the package under its new name, so getPackageLP takes care of
10369            // fiddling things correctly.
10370            pkg.setPackageName(originalPkgSetting.name);
10371
10372            // File a report about this.
10373            String msg = "New package " + pkgSetting.realName
10374                    + " renamed to replace old package " + pkgSetting.name;
10375            reportSettingsProblem(Log.WARN, msg);
10376        }
10377
10378        if (disabledPkgSetting != null) {
10379            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10380        }
10381
10382        // SELinux sandboxes become more restrictive as targetSdkVersion increases.
10383        // To ensure that apps with sharedUserId are placed in the same selinux domain
10384        // without breaking any assumptions about access, put them into the least
10385        // restrictive targetSdkVersion=25 domain.
10386        // TODO(b/72290969): Base this on the actual targetSdkVersion(s) of the apps within the
10387        // sharedUserSetting, instead of defaulting to the least restrictive domain.
10388        final int targetSdk = (sharedUserSetting != null) ? 25
10389                : pkg.applicationInfo.targetSdkVersion;
10390        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10391        // They currently can be if the sharedUser apps are signed with the platform key.
10392        final boolean isPrivileged = (sharedUserSetting != null) ?
10393            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10394
10395        SELinuxMMAC.assignSeInfoValue(pkg, isPrivileged, targetSdk);
10396
10397        pkg.mExtras = pkgSetting;
10398        pkg.applicationInfo.processName = fixProcessName(
10399                pkg.applicationInfo.packageName,
10400                pkg.applicationInfo.processName);
10401
10402        if (!isPlatformPackage) {
10403            // Get all of our default paths setup
10404            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10405        }
10406
10407        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10408
10409        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10410            if (needToDeriveAbi) {
10411                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10412                final boolean extractNativeLibs = !pkg.isLibrary();
10413                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10414                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10415
10416                // Some system apps still use directory structure for native libraries
10417                // in which case we might end up not detecting abi solely based on apk
10418                // structure. Try to detect abi based on directory structure.
10419                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10420                        pkg.applicationInfo.primaryCpuAbi == null) {
10421                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10422                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10423                }
10424            } else {
10425                // This is not a first boot or an upgrade, don't bother deriving the
10426                // ABI during the scan. Instead, trust the value that was stored in the
10427                // package setting.
10428                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10429                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10430
10431                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10432
10433                if (DEBUG_ABI_SELECTION) {
10434                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10435                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10436                            pkg.applicationInfo.secondaryCpuAbi);
10437                }
10438            }
10439        } else {
10440            if ((scanFlags & SCAN_MOVE) != 0) {
10441                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10442                // but we already have this packages package info in the PackageSetting. We just
10443                // use that and derive the native library path based on the new codepath.
10444                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10445                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10446            }
10447
10448            // Set native library paths again. For moves, the path will be updated based on the
10449            // ABIs we've determined above. For non-moves, the path will be updated based on the
10450            // ABIs we determined during compilation, but the path will depend on the final
10451            // package path (after the rename away from the stage path).
10452            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10453        }
10454
10455        // This is a special case for the "system" package, where the ABI is
10456        // dictated by the zygote configuration (and init.rc). We should keep track
10457        // of this ABI so that we can deal with "normal" applications that run under
10458        // the same UID correctly.
10459        if (isPlatformPackage) {
10460            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10461                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10462        }
10463
10464        // If there's a mismatch between the abi-override in the package setting
10465        // and the abiOverride specified for the install. Warn about this because we
10466        // would've already compiled the app without taking the package setting into
10467        // account.
10468        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10469            if (cpuAbiOverride == null && pkg.packageName != null) {
10470                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10471                        " for package " + pkg.packageName);
10472            }
10473        }
10474
10475        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10476        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10477        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10478
10479        // Copy the derived override back to the parsed package, so that we can
10480        // update the package settings accordingly.
10481        pkg.cpuAbiOverride = cpuAbiOverride;
10482
10483        if (DEBUG_ABI_SELECTION) {
10484            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10485                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10486                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10487        }
10488
10489        // Push the derived path down into PackageSettings so we know what to
10490        // clean up at uninstall time.
10491        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10492
10493        if (DEBUG_ABI_SELECTION) {
10494            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10495                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10496                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10497        }
10498
10499        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10500            // We don't do this here during boot because we can do it all
10501            // at once after scanning all existing packages.
10502            //
10503            // We also do this *before* we perform dexopt on this package, so that
10504            // we can avoid redundant dexopts, and also to make sure we've got the
10505            // code and package path correct.
10506            changedAbiCodePath =
10507                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10508        }
10509
10510        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10511                android.Manifest.permission.FACTORY_TEST)) {
10512            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10513        }
10514
10515        if (isSystemApp(pkg)) {
10516            pkgSetting.isOrphaned = true;
10517        }
10518
10519        // Take care of first install / last update times.
10520        final long scanFileTime = getLastModifiedTime(pkg);
10521        if (currentTime != 0) {
10522            if (pkgSetting.firstInstallTime == 0) {
10523                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10524            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10525                pkgSetting.lastUpdateTime = currentTime;
10526            }
10527        } else if (pkgSetting.firstInstallTime == 0) {
10528            // We need *something*.  Take time time stamp of the file.
10529            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10530        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10531            if (scanFileTime != pkgSetting.timeStamp) {
10532                // A package on the system image has changed; consider this
10533                // to be an update.
10534                pkgSetting.lastUpdateTime = scanFileTime;
10535            }
10536        }
10537        pkgSetting.setTimeStamp(scanFileTime);
10538
10539        pkgSetting.pkg = pkg;
10540        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10541        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10542            pkgSetting.versionCode = pkg.getLongVersionCode();
10543        }
10544        // Update volume if needed
10545        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10546        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10547            Slog.i(PackageManagerService.TAG,
10548                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10549                    + " package " + pkg.packageName
10550                    + " volume from " + pkgSetting.volumeUuid
10551                    + " to " + volumeUuid);
10552            pkgSetting.volumeUuid = volumeUuid;
10553        }
10554
10555        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10556    }
10557
10558    /**
10559     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10560     */
10561    private static boolean apkHasCode(String fileName) {
10562        StrictJarFile jarFile = null;
10563        try {
10564            jarFile = new StrictJarFile(fileName,
10565                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10566            return jarFile.findEntry("classes.dex") != null;
10567        } catch (IOException ignore) {
10568        } finally {
10569            try {
10570                if (jarFile != null) {
10571                    jarFile.close();
10572                }
10573            } catch (IOException ignore) {}
10574        }
10575        return false;
10576    }
10577
10578    /**
10579     * Enforces code policy for the package. This ensures that if an APK has
10580     * declared hasCode="true" in its manifest that the APK actually contains
10581     * code.
10582     *
10583     * @throws PackageManagerException If bytecode could not be found when it should exist
10584     */
10585    private static void assertCodePolicy(PackageParser.Package pkg)
10586            throws PackageManagerException {
10587        final boolean shouldHaveCode =
10588                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10589        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10590            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10591                    "Package " + pkg.baseCodePath + " code is missing");
10592        }
10593
10594        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10595            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10596                final boolean splitShouldHaveCode =
10597                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10598                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10599                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10600                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10601                }
10602            }
10603        }
10604    }
10605
10606    /**
10607     * Applies policy to the parsed package based upon the given policy flags.
10608     * Ensures the package is in a good state.
10609     * <p>
10610     * Implementation detail: This method must NOT have any side effect. It would
10611     * ideally be static, but, it requires locks to read system state.
10612     */
10613    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10614            final @ScanFlags int scanFlags) {
10615        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10616            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10617            if (pkg.applicationInfo.isDirectBootAware()) {
10618                // we're direct boot aware; set for all components
10619                for (PackageParser.Service s : pkg.services) {
10620                    s.info.encryptionAware = s.info.directBootAware = true;
10621                }
10622                for (PackageParser.Provider p : pkg.providers) {
10623                    p.info.encryptionAware = p.info.directBootAware = true;
10624                }
10625                for (PackageParser.Activity a : pkg.activities) {
10626                    a.info.encryptionAware = a.info.directBootAware = true;
10627                }
10628                for (PackageParser.Activity r : pkg.receivers) {
10629                    r.info.encryptionAware = r.info.directBootAware = true;
10630                }
10631            }
10632            if (compressedFileExists(pkg.codePath)) {
10633                pkg.isStub = true;
10634            }
10635        } else {
10636            // non system apps can't be flagged as core
10637            pkg.coreApp = false;
10638            // clear flags not applicable to regular apps
10639            pkg.applicationInfo.flags &=
10640                    ~ApplicationInfo.FLAG_PERSISTENT;
10641            pkg.applicationInfo.privateFlags &=
10642                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10643            pkg.applicationInfo.privateFlags &=
10644                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10645            // cap permission priorities
10646            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10647                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10648                    pkg.permissionGroups.get(i).info.priority = 0;
10649                }
10650            }
10651        }
10652        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10653            // clear protected broadcasts
10654            pkg.protectedBroadcasts = null;
10655            // ignore export request for single user receivers
10656            if (pkg.receivers != null) {
10657                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10658                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10659                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10660                        receiver.info.exported = false;
10661                    }
10662                }
10663            }
10664            // ignore export request for single user services
10665            if (pkg.services != null) {
10666                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10667                    final PackageParser.Service service = pkg.services.get(i);
10668                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10669                        service.info.exported = false;
10670                    }
10671                }
10672            }
10673            // ignore export request for single user providers
10674            if (pkg.providers != null) {
10675                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10676                    final PackageParser.Provider provider = pkg.providers.get(i);
10677                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10678                        provider.info.exported = false;
10679                    }
10680                }
10681            }
10682        }
10683
10684        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10685            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10686        }
10687
10688        if ((scanFlags & SCAN_AS_OEM) != 0) {
10689            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10690        }
10691
10692        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10693            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10694        }
10695
10696        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10697            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10698        }
10699
10700        if (!isSystemApp(pkg)) {
10701            // Only system apps can use these features.
10702            pkg.mOriginalPackages = null;
10703            pkg.mRealPackage = null;
10704            pkg.mAdoptPermissions = null;
10705        }
10706    }
10707
10708    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10709            throws PackageManagerException {
10710        if (object == null) {
10711            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10712        }
10713        return object;
10714    }
10715
10716    /**
10717     * Asserts the parsed package is valid according to the given policy. If the
10718     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10719     * <p>
10720     * Implementation detail: This method must NOT have any side effects. It would
10721     * ideally be static, but, it requires locks to read system state.
10722     *
10723     * @throws PackageManagerException If the package fails any of the validation checks
10724     */
10725    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10726            final @ScanFlags int scanFlags)
10727                    throws PackageManagerException {
10728        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10729            assertCodePolicy(pkg);
10730        }
10731
10732        if (pkg.applicationInfo.getCodePath() == null ||
10733                pkg.applicationInfo.getResourcePath() == null) {
10734            // Bail out. The resource and code paths haven't been set.
10735            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10736                    "Code and resource paths haven't been set correctly");
10737        }
10738
10739        // Make sure we're not adding any bogus keyset info
10740        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10741        ksms.assertScannedPackageValid(pkg);
10742
10743        synchronized (mPackages) {
10744            // The special "android" package can only be defined once
10745            if (pkg.packageName.equals("android")) {
10746                if (mAndroidApplication != null) {
10747                    Slog.w(TAG, "*************************************************");
10748                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10749                    Slog.w(TAG, " codePath=" + pkg.codePath);
10750                    Slog.w(TAG, "*************************************************");
10751                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10752                            "Core android package being redefined.  Skipping.");
10753                }
10754            }
10755
10756            // A package name must be unique; don't allow duplicates
10757            if (mPackages.containsKey(pkg.packageName)) {
10758                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10759                        "Application package " + pkg.packageName
10760                        + " already installed.  Skipping duplicate.");
10761            }
10762
10763            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10764                // Static libs have a synthetic package name containing the version
10765                // but we still want the base name to be unique.
10766                if (mPackages.containsKey(pkg.manifestPackageName)) {
10767                    throw new PackageManagerException(
10768                            "Duplicate static shared lib provider package");
10769                }
10770
10771                // Static shared libraries should have at least O target SDK
10772                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10773                    throw new PackageManagerException(
10774                            "Packages declaring static-shared libs must target O SDK or higher");
10775                }
10776
10777                // Package declaring static a shared lib cannot be instant apps
10778                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10779                    throw new PackageManagerException(
10780                            "Packages declaring static-shared libs cannot be instant apps");
10781                }
10782
10783                // Package declaring static a shared lib cannot be renamed since the package
10784                // name is synthetic and apps can't code around package manager internals.
10785                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10786                    throw new PackageManagerException(
10787                            "Packages declaring static-shared libs cannot be renamed");
10788                }
10789
10790                // Package declaring static a shared lib cannot declare child packages
10791                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10792                    throw new PackageManagerException(
10793                            "Packages declaring static-shared libs cannot have child packages");
10794                }
10795
10796                // Package declaring static a shared lib cannot declare dynamic libs
10797                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10798                    throw new PackageManagerException(
10799                            "Packages declaring static-shared libs cannot declare dynamic libs");
10800                }
10801
10802                // Package declaring static a shared lib cannot declare shared users
10803                if (pkg.mSharedUserId != null) {
10804                    throw new PackageManagerException(
10805                            "Packages declaring static-shared libs cannot declare shared users");
10806                }
10807
10808                // Static shared libs cannot declare activities
10809                if (!pkg.activities.isEmpty()) {
10810                    throw new PackageManagerException(
10811                            "Static shared libs cannot declare activities");
10812                }
10813
10814                // Static shared libs cannot declare services
10815                if (!pkg.services.isEmpty()) {
10816                    throw new PackageManagerException(
10817                            "Static shared libs cannot declare services");
10818                }
10819
10820                // Static shared libs cannot declare providers
10821                if (!pkg.providers.isEmpty()) {
10822                    throw new PackageManagerException(
10823                            "Static shared libs cannot declare content providers");
10824                }
10825
10826                // Static shared libs cannot declare receivers
10827                if (!pkg.receivers.isEmpty()) {
10828                    throw new PackageManagerException(
10829                            "Static shared libs cannot declare broadcast receivers");
10830                }
10831
10832                // Static shared libs cannot declare permission groups
10833                if (!pkg.permissionGroups.isEmpty()) {
10834                    throw new PackageManagerException(
10835                            "Static shared libs cannot declare permission groups");
10836                }
10837
10838                // Static shared libs cannot declare permissions
10839                if (!pkg.permissions.isEmpty()) {
10840                    throw new PackageManagerException(
10841                            "Static shared libs cannot declare permissions");
10842                }
10843
10844                // Static shared libs cannot declare protected broadcasts
10845                if (pkg.protectedBroadcasts != null) {
10846                    throw new PackageManagerException(
10847                            "Static shared libs cannot declare protected broadcasts");
10848                }
10849
10850                // Static shared libs cannot be overlay targets
10851                if (pkg.mOverlayTarget != null) {
10852                    throw new PackageManagerException(
10853                            "Static shared libs cannot be overlay targets");
10854                }
10855
10856                // The version codes must be ordered as lib versions
10857                long minVersionCode = Long.MIN_VALUE;
10858                long maxVersionCode = Long.MAX_VALUE;
10859
10860                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10861                        pkg.staticSharedLibName);
10862                if (versionedLib != null) {
10863                    final int versionCount = versionedLib.size();
10864                    for (int i = 0; i < versionCount; i++) {
10865                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10866                        final long libVersionCode = libInfo.getDeclaringPackage()
10867                                .getLongVersionCode();
10868                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10869                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10870                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10871                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10872                        } else {
10873                            minVersionCode = maxVersionCode = libVersionCode;
10874                            break;
10875                        }
10876                    }
10877                }
10878                if (pkg.getLongVersionCode() < minVersionCode
10879                        || pkg.getLongVersionCode() > maxVersionCode) {
10880                    throw new PackageManagerException("Static shared"
10881                            + " lib version codes must be ordered as lib versions");
10882                }
10883            }
10884
10885            // Only privileged apps and updated privileged apps can add child packages.
10886            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10887                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10888                    throw new PackageManagerException("Only privileged apps can add child "
10889                            + "packages. Ignoring package " + pkg.packageName);
10890                }
10891                final int childCount = pkg.childPackages.size();
10892                for (int i = 0; i < childCount; i++) {
10893                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10894                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10895                            childPkg.packageName)) {
10896                        throw new PackageManagerException("Can't override child of "
10897                                + "another disabled app. Ignoring package " + pkg.packageName);
10898                    }
10899                }
10900            }
10901
10902            // If we're only installing presumed-existing packages, require that the
10903            // scanned APK is both already known and at the path previously established
10904            // for it.  Previously unknown packages we pick up normally, but if we have an
10905            // a priori expectation about this package's install presence, enforce it.
10906            // With a singular exception for new system packages. When an OTA contains
10907            // a new system package, we allow the codepath to change from a system location
10908            // to the user-installed location. If we don't allow this change, any newer,
10909            // user-installed version of the application will be ignored.
10910            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10911                if (mExpectingBetter.containsKey(pkg.packageName)) {
10912                    logCriticalInfo(Log.WARN,
10913                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10914                } else {
10915                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10916                    if (known != null) {
10917                        if (DEBUG_PACKAGE_SCANNING) {
10918                            Log.d(TAG, "Examining " + pkg.codePath
10919                                    + " and requiring known paths " + known.codePathString
10920                                    + " & " + known.resourcePathString);
10921                        }
10922                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10923                                || !pkg.applicationInfo.getResourcePath().equals(
10924                                        known.resourcePathString)) {
10925                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10926                                    "Application package " + pkg.packageName
10927                                    + " found at " + pkg.applicationInfo.getCodePath()
10928                                    + " but expected at " + known.codePathString
10929                                    + "; ignoring.");
10930                        }
10931                    } else {
10932                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10933                                "Application package " + pkg.packageName
10934                                + " not found; ignoring.");
10935                    }
10936                }
10937            }
10938
10939            // Verify that this new package doesn't have any content providers
10940            // that conflict with existing packages.  Only do this if the
10941            // package isn't already installed, since we don't want to break
10942            // things that are installed.
10943            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10944                final int N = pkg.providers.size();
10945                int i;
10946                for (i=0; i<N; i++) {
10947                    PackageParser.Provider p = pkg.providers.get(i);
10948                    if (p.info.authority != null) {
10949                        String names[] = p.info.authority.split(";");
10950                        for (int j = 0; j < names.length; j++) {
10951                            if (mProvidersByAuthority.containsKey(names[j])) {
10952                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10953                                final String otherPackageName =
10954                                        ((other != null && other.getComponentName() != null) ?
10955                                                other.getComponentName().getPackageName() : "?");
10956                                throw new PackageManagerException(
10957                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10958                                        "Can't install because provider name " + names[j]
10959                                                + " (in package " + pkg.applicationInfo.packageName
10960                                                + ") is already used by " + otherPackageName);
10961                            }
10962                        }
10963                    }
10964                }
10965            }
10966
10967            // Verify that packages sharing a user with a privileged app are marked as privileged.
10968            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
10969                SharedUserSetting sharedUserSetting = null;
10970                try {
10971                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
10972                } catch (PackageManagerException ignore) {}
10973                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
10974                    // Exempt SharedUsers signed with the platform key.
10975                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
10976                    if ((platformPkgSetting.signatures.mSigningDetails
10977                            != PackageParser.SigningDetails.UNKNOWN)
10978                            && (compareSignatures(
10979                                    platformPkgSetting.signatures.mSigningDetails.signatures,
10980                                    pkg.mSigningDetails.signatures)
10981                                            != PackageManager.SIGNATURE_MATCH)) {
10982                        throw new PackageManagerException("Apps that share a user with a " +
10983                                "privileged app must themselves be marked as privileged. " +
10984                                pkg.packageName + " shares privileged user " +
10985                                pkg.mSharedUserId + ".");
10986                    }
10987                }
10988            }
10989
10990            // Apply policies specific for runtime resource overlays (RROs).
10991            if (pkg.mOverlayTarget != null) {
10992                // System overlays have some restrictions on their use of the 'static' state.
10993                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10994                    // We are scanning a system overlay. This can be the first scan of the
10995                    // system/vendor/oem partition, or an update to the system overlay.
10996                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10997                        // This must be an update to a system overlay.
10998                        final PackageSetting previousPkg = assertNotNull(
10999                                mSettings.getPackageLPr(pkg.packageName),
11000                                "previous package state not present");
11001
11002                        // Static overlays cannot be updated.
11003                        if (previousPkg.pkg.mOverlayIsStatic) {
11004                            throw new PackageManagerException("Overlay " + pkg.packageName +
11005                                    " is static and cannot be upgraded.");
11006                        // Non-static overlays cannot be converted to static overlays.
11007                        } else if (pkg.mOverlayIsStatic) {
11008                            throw new PackageManagerException("Overlay " + pkg.packageName +
11009                                    " cannot be upgraded into a static overlay.");
11010                        }
11011                    }
11012                } else {
11013                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11014                    if (pkg.mOverlayIsStatic) {
11015                        throw new PackageManagerException("Overlay " + pkg.packageName +
11016                                " is static but not pre-installed.");
11017                    }
11018
11019                    // The only case where we allow installation of a non-system overlay is when
11020                    // its signature is signed with the platform certificate.
11021                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11022                    if ((platformPkgSetting.signatures.mSigningDetails
11023                            != PackageParser.SigningDetails.UNKNOWN)
11024                            && (compareSignatures(
11025                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11026                                    pkg.mSigningDetails.signatures)
11027                                            != PackageManager.SIGNATURE_MATCH)) {
11028                        throw new PackageManagerException("Overlay " + pkg.packageName +
11029                                " must be signed with the platform certificate.");
11030                    }
11031                }
11032            }
11033        }
11034    }
11035
11036    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11037            int type, String declaringPackageName, long declaringVersionCode) {
11038        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11039        if (versionedLib == null) {
11040            versionedLib = new LongSparseArray<>();
11041            mSharedLibraries.put(name, versionedLib);
11042            if (type == SharedLibraryInfo.TYPE_STATIC) {
11043                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11044            }
11045        } else if (versionedLib.indexOfKey(version) >= 0) {
11046            return false;
11047        }
11048        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11049                version, type, declaringPackageName, declaringVersionCode);
11050        versionedLib.put(version, libEntry);
11051        return true;
11052    }
11053
11054    private boolean removeSharedLibraryLPw(String name, long version) {
11055        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11056        if (versionedLib == null) {
11057            return false;
11058        }
11059        final int libIdx = versionedLib.indexOfKey(version);
11060        if (libIdx < 0) {
11061            return false;
11062        }
11063        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11064        versionedLib.remove(version);
11065        if (versionedLib.size() <= 0) {
11066            mSharedLibraries.remove(name);
11067            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11068                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11069                        .getPackageName());
11070            }
11071        }
11072        return true;
11073    }
11074
11075    /**
11076     * Adds a scanned package to the system. When this method is finished, the package will
11077     * be available for query, resolution, etc...
11078     */
11079    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11080            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
11081        final String pkgName = pkg.packageName;
11082        if (mCustomResolverComponentName != null &&
11083                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11084            setUpCustomResolverActivity(pkg);
11085        }
11086
11087        if (pkg.packageName.equals("android")) {
11088            synchronized (mPackages) {
11089                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11090                    // Set up information for our fall-back user intent resolution activity.
11091                    mPlatformPackage = pkg;
11092                    pkg.mVersionCode = mSdkVersion;
11093                    pkg.mVersionCodeMajor = 0;
11094                    mAndroidApplication = pkg.applicationInfo;
11095                    if (!mResolverReplaced) {
11096                        mResolveActivity.applicationInfo = mAndroidApplication;
11097                        mResolveActivity.name = ResolverActivity.class.getName();
11098                        mResolveActivity.packageName = mAndroidApplication.packageName;
11099                        mResolveActivity.processName = "system:ui";
11100                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11101                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11102                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11103                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11104                        mResolveActivity.exported = true;
11105                        mResolveActivity.enabled = true;
11106                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11107                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11108                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11109                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11110                                | ActivityInfo.CONFIG_ORIENTATION
11111                                | ActivityInfo.CONFIG_KEYBOARD
11112                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11113                        mResolveInfo.activityInfo = mResolveActivity;
11114                        mResolveInfo.priority = 0;
11115                        mResolveInfo.preferredOrder = 0;
11116                        mResolveInfo.match = 0;
11117                        mResolveComponentName = new ComponentName(
11118                                mAndroidApplication.packageName, mResolveActivity.name);
11119                    }
11120                }
11121            }
11122        }
11123
11124        ArrayList<PackageParser.Package> clientLibPkgs = null;
11125        // writer
11126        synchronized (mPackages) {
11127            boolean hasStaticSharedLibs = false;
11128
11129            // Any app can add new static shared libraries
11130            if (pkg.staticSharedLibName != null) {
11131                // Static shared libs don't allow renaming as they have synthetic package
11132                // names to allow install of multiple versions, so use name from manifest.
11133                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11134                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11135                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11136                    hasStaticSharedLibs = true;
11137                } else {
11138                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11139                                + pkg.staticSharedLibName + " already exists; skipping");
11140                }
11141                // Static shared libs cannot be updated once installed since they
11142                // use synthetic package name which includes the version code, so
11143                // not need to update other packages's shared lib dependencies.
11144            }
11145
11146            if (!hasStaticSharedLibs
11147                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11148                // Only system apps can add new dynamic shared libraries.
11149                if (pkg.libraryNames != null) {
11150                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11151                        String name = pkg.libraryNames.get(i);
11152                        boolean allowed = false;
11153                        if (pkg.isUpdatedSystemApp()) {
11154                            // New library entries can only be added through the
11155                            // system image.  This is important to get rid of a lot
11156                            // of nasty edge cases: for example if we allowed a non-
11157                            // system update of the app to add a library, then uninstalling
11158                            // the update would make the library go away, and assumptions
11159                            // we made such as through app install filtering would now
11160                            // have allowed apps on the device which aren't compatible
11161                            // with it.  Better to just have the restriction here, be
11162                            // conservative, and create many fewer cases that can negatively
11163                            // impact the user experience.
11164                            final PackageSetting sysPs = mSettings
11165                                    .getDisabledSystemPkgLPr(pkg.packageName);
11166                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11167                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11168                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11169                                        allowed = true;
11170                                        break;
11171                                    }
11172                                }
11173                            }
11174                        } else {
11175                            allowed = true;
11176                        }
11177                        if (allowed) {
11178                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11179                                    SharedLibraryInfo.VERSION_UNDEFINED,
11180                                    SharedLibraryInfo.TYPE_DYNAMIC,
11181                                    pkg.packageName, pkg.getLongVersionCode())) {
11182                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11183                                        + name + " already exists; skipping");
11184                            }
11185                        } else {
11186                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11187                                    + name + " that is not declared on system image; skipping");
11188                        }
11189                    }
11190
11191                    if ((scanFlags & SCAN_BOOTING) == 0) {
11192                        // If we are not booting, we need to update any applications
11193                        // that are clients of our shared library.  If we are booting,
11194                        // this will all be done once the scan is complete.
11195                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11196                    }
11197                }
11198            }
11199        }
11200
11201        if ((scanFlags & SCAN_BOOTING) != 0) {
11202            // No apps can run during boot scan, so they don't need to be frozen
11203        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11204            // Caller asked to not kill app, so it's probably not frozen
11205        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11206            // Caller asked us to ignore frozen check for some reason; they
11207            // probably didn't know the package name
11208        } else {
11209            // We're doing major surgery on this package, so it better be frozen
11210            // right now to keep it from launching
11211            checkPackageFrozen(pkgName);
11212        }
11213
11214        // Also need to kill any apps that are dependent on the library.
11215        if (clientLibPkgs != null) {
11216            for (int i=0; i<clientLibPkgs.size(); i++) {
11217                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11218                killApplication(clientPkg.applicationInfo.packageName,
11219                        clientPkg.applicationInfo.uid, "update lib");
11220            }
11221        }
11222
11223        // writer
11224        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11225
11226        synchronized (mPackages) {
11227            // We don't expect installation to fail beyond this point
11228
11229            // Add the new setting to mSettings
11230            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11231            // Add the new setting to mPackages
11232            mPackages.put(pkg.applicationInfo.packageName, pkg);
11233            // Make sure we don't accidentally delete its data.
11234            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11235            while (iter.hasNext()) {
11236                PackageCleanItem item = iter.next();
11237                if (pkgName.equals(item.packageName)) {
11238                    iter.remove();
11239                }
11240            }
11241
11242            // Add the package's KeySets to the global KeySetManagerService
11243            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11244            ksms.addScannedPackageLPw(pkg);
11245
11246            int N = pkg.providers.size();
11247            StringBuilder r = null;
11248            int i;
11249            for (i=0; i<N; i++) {
11250                PackageParser.Provider p = pkg.providers.get(i);
11251                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11252                        p.info.processName);
11253                mProviders.addProvider(p);
11254                p.syncable = p.info.isSyncable;
11255                if (p.info.authority != null) {
11256                    String names[] = p.info.authority.split(";");
11257                    p.info.authority = null;
11258                    for (int j = 0; j < names.length; j++) {
11259                        if (j == 1 && p.syncable) {
11260                            // We only want the first authority for a provider to possibly be
11261                            // syncable, so if we already added this provider using a different
11262                            // authority clear the syncable flag. We copy the provider before
11263                            // changing it because the mProviders object contains a reference
11264                            // to a provider that we don't want to change.
11265                            // Only do this for the second authority since the resulting provider
11266                            // object can be the same for all future authorities for this provider.
11267                            p = new PackageParser.Provider(p);
11268                            p.syncable = false;
11269                        }
11270                        if (!mProvidersByAuthority.containsKey(names[j])) {
11271                            mProvidersByAuthority.put(names[j], p);
11272                            if (p.info.authority == null) {
11273                                p.info.authority = names[j];
11274                            } else {
11275                                p.info.authority = p.info.authority + ";" + names[j];
11276                            }
11277                            if (DEBUG_PACKAGE_SCANNING) {
11278                                if (chatty)
11279                                    Log.d(TAG, "Registered content provider: " + names[j]
11280                                            + ", className = " + p.info.name + ", isSyncable = "
11281                                            + p.info.isSyncable);
11282                            }
11283                        } else {
11284                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11285                            Slog.w(TAG, "Skipping provider name " + names[j] +
11286                                    " (in package " + pkg.applicationInfo.packageName +
11287                                    "): name already used by "
11288                                    + ((other != null && other.getComponentName() != null)
11289                                            ? other.getComponentName().getPackageName() : "?"));
11290                        }
11291                    }
11292                }
11293                if (chatty) {
11294                    if (r == null) {
11295                        r = new StringBuilder(256);
11296                    } else {
11297                        r.append(' ');
11298                    }
11299                    r.append(p.info.name);
11300                }
11301            }
11302            if (r != null) {
11303                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11304            }
11305
11306            N = pkg.services.size();
11307            r = null;
11308            for (i=0; i<N; i++) {
11309                PackageParser.Service s = pkg.services.get(i);
11310                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11311                        s.info.processName);
11312                mServices.addService(s);
11313                if (chatty) {
11314                    if (r == null) {
11315                        r = new StringBuilder(256);
11316                    } else {
11317                        r.append(' ');
11318                    }
11319                    r.append(s.info.name);
11320                }
11321            }
11322            if (r != null) {
11323                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11324            }
11325
11326            N = pkg.receivers.size();
11327            r = null;
11328            for (i=0; i<N; i++) {
11329                PackageParser.Activity a = pkg.receivers.get(i);
11330                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11331                        a.info.processName);
11332                mReceivers.addActivity(a, "receiver");
11333                if (chatty) {
11334                    if (r == null) {
11335                        r = new StringBuilder(256);
11336                    } else {
11337                        r.append(' ');
11338                    }
11339                    r.append(a.info.name);
11340                }
11341            }
11342            if (r != null) {
11343                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11344            }
11345
11346            N = pkg.activities.size();
11347            r = null;
11348            for (i=0; i<N; i++) {
11349                PackageParser.Activity a = pkg.activities.get(i);
11350                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11351                        a.info.processName);
11352                mActivities.addActivity(a, "activity");
11353                if (chatty) {
11354                    if (r == null) {
11355                        r = new StringBuilder(256);
11356                    } else {
11357                        r.append(' ');
11358                    }
11359                    r.append(a.info.name);
11360                }
11361            }
11362            if (r != null) {
11363                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11364            }
11365
11366            // Don't allow ephemeral applications to define new permissions groups.
11367            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11368                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11369                        + " ignored: instant apps cannot define new permission groups.");
11370            } else {
11371                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11372            }
11373
11374            // Don't allow ephemeral applications to define new permissions.
11375            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11376                Slog.w(TAG, "Permissions from package " + pkg.packageName
11377                        + " ignored: instant apps cannot define new permissions.");
11378            } else {
11379                mPermissionManager.addAllPermissions(pkg, chatty);
11380            }
11381
11382            N = pkg.instrumentation.size();
11383            r = null;
11384            for (i=0; i<N; i++) {
11385                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11386                a.info.packageName = pkg.applicationInfo.packageName;
11387                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11388                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11389                a.info.splitNames = pkg.splitNames;
11390                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11391                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11392                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11393                a.info.dataDir = pkg.applicationInfo.dataDir;
11394                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11395                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11396                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11397                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11398                mInstrumentation.put(a.getComponentName(), a);
11399                if (chatty) {
11400                    if (r == null) {
11401                        r = new StringBuilder(256);
11402                    } else {
11403                        r.append(' ');
11404                    }
11405                    r.append(a.info.name);
11406                }
11407            }
11408            if (r != null) {
11409                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11410            }
11411
11412            if (pkg.protectedBroadcasts != null) {
11413                N = pkg.protectedBroadcasts.size();
11414                synchronized (mProtectedBroadcasts) {
11415                    for (i = 0; i < N; i++) {
11416                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11417                    }
11418                }
11419            }
11420        }
11421
11422        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11423    }
11424
11425    /**
11426     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11427     * is derived purely on the basis of the contents of {@code scanFile} and
11428     * {@code cpuAbiOverride}.
11429     *
11430     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11431     */
11432    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11433            boolean extractLibs)
11434                    throws PackageManagerException {
11435        // Give ourselves some initial paths; we'll come back for another
11436        // pass once we've determined ABI below.
11437        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11438
11439        // We would never need to extract libs for forward-locked and external packages,
11440        // since the container service will do it for us. We shouldn't attempt to
11441        // extract libs from system app when it was not updated.
11442        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11443                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11444            extractLibs = false;
11445        }
11446
11447        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11448        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11449
11450        NativeLibraryHelper.Handle handle = null;
11451        try {
11452            handle = NativeLibraryHelper.Handle.create(pkg);
11453            // TODO(multiArch): This can be null for apps that didn't go through the
11454            // usual installation process. We can calculate it again, like we
11455            // do during install time.
11456            //
11457            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11458            // unnecessary.
11459            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11460
11461            // Null out the abis so that they can be recalculated.
11462            pkg.applicationInfo.primaryCpuAbi = null;
11463            pkg.applicationInfo.secondaryCpuAbi = null;
11464            if (isMultiArch(pkg.applicationInfo)) {
11465                // Warn if we've set an abiOverride for multi-lib packages..
11466                // By definition, we need to copy both 32 and 64 bit libraries for
11467                // such packages.
11468                if (pkg.cpuAbiOverride != null
11469                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11470                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11471                }
11472
11473                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11474                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11475                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11476                    if (extractLibs) {
11477                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11478                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11479                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11480                                useIsaSpecificSubdirs);
11481                    } else {
11482                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11483                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11484                    }
11485                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11486                }
11487
11488                // Shared library native code should be in the APK zip aligned
11489                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11490                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11491                            "Shared library native lib extraction not supported");
11492                }
11493
11494                maybeThrowExceptionForMultiArchCopy(
11495                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11496
11497                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11498                    if (extractLibs) {
11499                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11500                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11501                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11502                                useIsaSpecificSubdirs);
11503                    } else {
11504                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11505                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11506                    }
11507                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11508                }
11509
11510                maybeThrowExceptionForMultiArchCopy(
11511                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11512
11513                if (abi64 >= 0) {
11514                    // Shared library native libs should be in the APK zip aligned
11515                    if (extractLibs && pkg.isLibrary()) {
11516                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11517                                "Shared library native lib extraction not supported");
11518                    }
11519                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11520                }
11521
11522                if (abi32 >= 0) {
11523                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11524                    if (abi64 >= 0) {
11525                        if (pkg.use32bitAbi) {
11526                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11527                            pkg.applicationInfo.primaryCpuAbi = abi;
11528                        } else {
11529                            pkg.applicationInfo.secondaryCpuAbi = abi;
11530                        }
11531                    } else {
11532                        pkg.applicationInfo.primaryCpuAbi = abi;
11533                    }
11534                }
11535            } else {
11536                String[] abiList = (cpuAbiOverride != null) ?
11537                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11538
11539                // Enable gross and lame hacks for apps that are built with old
11540                // SDK tools. We must scan their APKs for renderscript bitcode and
11541                // not launch them if it's present. Don't bother checking on devices
11542                // that don't have 64 bit support.
11543                boolean needsRenderScriptOverride = false;
11544                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11545                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11546                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11547                    needsRenderScriptOverride = true;
11548                }
11549
11550                final int copyRet;
11551                if (extractLibs) {
11552                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11553                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11554                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11555                } else {
11556                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11557                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11558                }
11559                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11560
11561                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11562                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11563                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11564                }
11565
11566                if (copyRet >= 0) {
11567                    // Shared libraries that have native libs must be multi-architecture
11568                    if (pkg.isLibrary()) {
11569                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11570                                "Shared library with native libs must be multiarch");
11571                    }
11572                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11573                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11574                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11575                } else if (needsRenderScriptOverride) {
11576                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11577                }
11578            }
11579        } catch (IOException ioe) {
11580            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11581        } finally {
11582            IoUtils.closeQuietly(handle);
11583        }
11584
11585        // Now that we've calculated the ABIs and determined if it's an internal app,
11586        // we will go ahead and populate the nativeLibraryPath.
11587        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11588    }
11589
11590    /**
11591     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11592     * i.e, so that all packages can be run inside a single process if required.
11593     *
11594     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11595     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11596     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11597     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11598     * updating a package that belongs to a shared user.
11599     *
11600     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11601     * adds unnecessary complexity.
11602     */
11603    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11604            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11605        List<String> changedAbiCodePath = null;
11606        String requiredInstructionSet = null;
11607        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11608            requiredInstructionSet = VMRuntime.getInstructionSet(
11609                     scannedPackage.applicationInfo.primaryCpuAbi);
11610        }
11611
11612        PackageSetting requirer = null;
11613        for (PackageSetting ps : packagesForUser) {
11614            // If packagesForUser contains scannedPackage, we skip it. This will happen
11615            // when scannedPackage is an update of an existing package. Without this check,
11616            // we will never be able to change the ABI of any package belonging to a shared
11617            // user, even if it's compatible with other packages.
11618            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11619                if (ps.primaryCpuAbiString == null) {
11620                    continue;
11621                }
11622
11623                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11624                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11625                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11626                    // this but there's not much we can do.
11627                    String errorMessage = "Instruction set mismatch, "
11628                            + ((requirer == null) ? "[caller]" : requirer)
11629                            + " requires " + requiredInstructionSet + " whereas " + ps
11630                            + " requires " + instructionSet;
11631                    Slog.w(TAG, errorMessage);
11632                }
11633
11634                if (requiredInstructionSet == null) {
11635                    requiredInstructionSet = instructionSet;
11636                    requirer = ps;
11637                }
11638            }
11639        }
11640
11641        if (requiredInstructionSet != null) {
11642            String adjustedAbi;
11643            if (requirer != null) {
11644                // requirer != null implies that either scannedPackage was null or that scannedPackage
11645                // did not require an ABI, in which case we have to adjust scannedPackage to match
11646                // the ABI of the set (which is the same as requirer's ABI)
11647                adjustedAbi = requirer.primaryCpuAbiString;
11648                if (scannedPackage != null) {
11649                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11650                }
11651            } else {
11652                // requirer == null implies that we're updating all ABIs in the set to
11653                // match scannedPackage.
11654                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11655            }
11656
11657            for (PackageSetting ps : packagesForUser) {
11658                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11659                    if (ps.primaryCpuAbiString != null) {
11660                        continue;
11661                    }
11662
11663                    ps.primaryCpuAbiString = adjustedAbi;
11664                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11665                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11666                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11667                        if (DEBUG_ABI_SELECTION) {
11668                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11669                                    + " (requirer="
11670                                    + (requirer != null ? requirer.pkg : "null")
11671                                    + ", scannedPackage="
11672                                    + (scannedPackage != null ? scannedPackage : "null")
11673                                    + ")");
11674                        }
11675                        if (changedAbiCodePath == null) {
11676                            changedAbiCodePath = new ArrayList<>();
11677                        }
11678                        changedAbiCodePath.add(ps.codePathString);
11679                    }
11680                }
11681            }
11682        }
11683        return changedAbiCodePath;
11684    }
11685
11686    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11687        synchronized (mPackages) {
11688            mResolverReplaced = true;
11689            // Set up information for custom user intent resolution activity.
11690            mResolveActivity.applicationInfo = pkg.applicationInfo;
11691            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11692            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11693            mResolveActivity.processName = pkg.applicationInfo.packageName;
11694            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11695            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11696                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11697            mResolveActivity.theme = 0;
11698            mResolveActivity.exported = true;
11699            mResolveActivity.enabled = true;
11700            mResolveInfo.activityInfo = mResolveActivity;
11701            mResolveInfo.priority = 0;
11702            mResolveInfo.preferredOrder = 0;
11703            mResolveInfo.match = 0;
11704            mResolveComponentName = mCustomResolverComponentName;
11705            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11706                    mResolveComponentName);
11707        }
11708    }
11709
11710    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11711        if (installerActivity == null) {
11712            if (DEBUG_INSTANT) {
11713                Slog.d(TAG, "Clear ephemeral installer activity");
11714            }
11715            mInstantAppInstallerActivity = null;
11716            return;
11717        }
11718
11719        if (DEBUG_INSTANT) {
11720            Slog.d(TAG, "Set ephemeral installer activity: "
11721                    + installerActivity.getComponentName());
11722        }
11723        // Set up information for ephemeral installer activity
11724        mInstantAppInstallerActivity = installerActivity;
11725        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11726                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11727        mInstantAppInstallerActivity.exported = true;
11728        mInstantAppInstallerActivity.enabled = true;
11729        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11730        mInstantAppInstallerInfo.priority = 1;
11731        mInstantAppInstallerInfo.preferredOrder = 1;
11732        mInstantAppInstallerInfo.isDefault = true;
11733        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11734                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11735    }
11736
11737    private static String calculateBundledApkRoot(final String codePathString) {
11738        final File codePath = new File(codePathString);
11739        final File codeRoot;
11740        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11741            codeRoot = Environment.getRootDirectory();
11742        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11743            codeRoot = Environment.getOemDirectory();
11744        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11745            codeRoot = Environment.getVendorDirectory();
11746        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11747            codeRoot = Environment.getProductDirectory();
11748        } else {
11749            // Unrecognized code path; take its top real segment as the apk root:
11750            // e.g. /something/app/blah.apk => /something
11751            try {
11752                File f = codePath.getCanonicalFile();
11753                File parent = f.getParentFile();    // non-null because codePath is a file
11754                File tmp;
11755                while ((tmp = parent.getParentFile()) != null) {
11756                    f = parent;
11757                    parent = tmp;
11758                }
11759                codeRoot = f;
11760                Slog.w(TAG, "Unrecognized code path "
11761                        + codePath + " - using " + codeRoot);
11762            } catch (IOException e) {
11763                // Can't canonicalize the code path -- shenanigans?
11764                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11765                return Environment.getRootDirectory().getPath();
11766            }
11767        }
11768        return codeRoot.getPath();
11769    }
11770
11771    /**
11772     * Derive and set the location of native libraries for the given package,
11773     * which varies depending on where and how the package was installed.
11774     */
11775    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11776        final ApplicationInfo info = pkg.applicationInfo;
11777        final String codePath = pkg.codePath;
11778        final File codeFile = new File(codePath);
11779        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11780        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11781
11782        info.nativeLibraryRootDir = null;
11783        info.nativeLibraryRootRequiresIsa = false;
11784        info.nativeLibraryDir = null;
11785        info.secondaryNativeLibraryDir = null;
11786
11787        if (isApkFile(codeFile)) {
11788            // Monolithic install
11789            if (bundledApp) {
11790                // If "/system/lib64/apkname" exists, assume that is the per-package
11791                // native library directory to use; otherwise use "/system/lib/apkname".
11792                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11793                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11794                        getPrimaryInstructionSet(info));
11795
11796                // This is a bundled system app so choose the path based on the ABI.
11797                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11798                // is just the default path.
11799                final String apkName = deriveCodePathName(codePath);
11800                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11801                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11802                        apkName).getAbsolutePath();
11803
11804                if (info.secondaryCpuAbi != null) {
11805                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11806                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11807                            secondaryLibDir, apkName).getAbsolutePath();
11808                }
11809            } else if (asecApp) {
11810                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11811                        .getAbsolutePath();
11812            } else {
11813                final String apkName = deriveCodePathName(codePath);
11814                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11815                        .getAbsolutePath();
11816            }
11817
11818            info.nativeLibraryRootRequiresIsa = false;
11819            info.nativeLibraryDir = info.nativeLibraryRootDir;
11820        } else {
11821            // Cluster install
11822            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11823            info.nativeLibraryRootRequiresIsa = true;
11824
11825            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11826                    getPrimaryInstructionSet(info)).getAbsolutePath();
11827
11828            if (info.secondaryCpuAbi != null) {
11829                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11830                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11831            }
11832        }
11833    }
11834
11835    /**
11836     * Calculate the abis and roots for a bundled app. These can uniquely
11837     * be determined from the contents of the system partition, i.e whether
11838     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11839     * of this information, and instead assume that the system was built
11840     * sensibly.
11841     */
11842    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11843                                           PackageSetting pkgSetting) {
11844        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11845
11846        // If "/system/lib64/apkname" exists, assume that is the per-package
11847        // native library directory to use; otherwise use "/system/lib/apkname".
11848        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11849        setBundledAppAbi(pkg, apkRoot, apkName);
11850        // pkgSetting might be null during rescan following uninstall of updates
11851        // to a bundled app, so accommodate that possibility.  The settings in
11852        // that case will be established later from the parsed package.
11853        //
11854        // If the settings aren't null, sync them up with what we've just derived.
11855        // note that apkRoot isn't stored in the package settings.
11856        if (pkgSetting != null) {
11857            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11858            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11859        }
11860    }
11861
11862    /**
11863     * Deduces the ABI of a bundled app and sets the relevant fields on the
11864     * parsed pkg object.
11865     *
11866     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11867     *        under which system libraries are installed.
11868     * @param apkName the name of the installed package.
11869     */
11870    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11871        final File codeFile = new File(pkg.codePath);
11872
11873        final boolean has64BitLibs;
11874        final boolean has32BitLibs;
11875        if (isApkFile(codeFile)) {
11876            // Monolithic install
11877            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11878            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11879        } else {
11880            // Cluster install
11881            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11882            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11883                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11884                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11885                has64BitLibs = (new File(rootDir, isa)).exists();
11886            } else {
11887                has64BitLibs = false;
11888            }
11889            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11890                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11891                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11892                has32BitLibs = (new File(rootDir, isa)).exists();
11893            } else {
11894                has32BitLibs = false;
11895            }
11896        }
11897
11898        if (has64BitLibs && !has32BitLibs) {
11899            // The package has 64 bit libs, but not 32 bit libs. Its primary
11900            // ABI should be 64 bit. We can safely assume here that the bundled
11901            // native libraries correspond to the most preferred ABI in the list.
11902
11903            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11904            pkg.applicationInfo.secondaryCpuAbi = null;
11905        } else if (has32BitLibs && !has64BitLibs) {
11906            // The package has 32 bit libs but not 64 bit libs. Its primary
11907            // ABI should be 32 bit.
11908
11909            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11910            pkg.applicationInfo.secondaryCpuAbi = null;
11911        } else if (has32BitLibs && has64BitLibs) {
11912            // The application has both 64 and 32 bit bundled libraries. We check
11913            // here that the app declares multiArch support, and warn if it doesn't.
11914            //
11915            // We will be lenient here and record both ABIs. The primary will be the
11916            // ABI that's higher on the list, i.e, a device that's configured to prefer
11917            // 64 bit apps will see a 64 bit primary ABI,
11918
11919            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11920                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11921            }
11922
11923            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11924                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11925                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11926            } else {
11927                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11928                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11929            }
11930        } else {
11931            pkg.applicationInfo.primaryCpuAbi = null;
11932            pkg.applicationInfo.secondaryCpuAbi = null;
11933        }
11934    }
11935
11936    private void killApplication(String pkgName, int appId, String reason) {
11937        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11938    }
11939
11940    private void killApplication(String pkgName, int appId, int userId, String reason) {
11941        // Request the ActivityManager to kill the process(only for existing packages)
11942        // so that we do not end up in a confused state while the user is still using the older
11943        // version of the application while the new one gets installed.
11944        final long token = Binder.clearCallingIdentity();
11945        try {
11946            IActivityManager am = ActivityManager.getService();
11947            if (am != null) {
11948                try {
11949                    am.killApplication(pkgName, appId, userId, reason);
11950                } catch (RemoteException e) {
11951                }
11952            }
11953        } finally {
11954            Binder.restoreCallingIdentity(token);
11955        }
11956    }
11957
11958    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11959        // Remove the parent package setting
11960        PackageSetting ps = (PackageSetting) pkg.mExtras;
11961        if (ps != null) {
11962            removePackageLI(ps, chatty);
11963        }
11964        // Remove the child package setting
11965        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11966        for (int i = 0; i < childCount; i++) {
11967            PackageParser.Package childPkg = pkg.childPackages.get(i);
11968            ps = (PackageSetting) childPkg.mExtras;
11969            if (ps != null) {
11970                removePackageLI(ps, chatty);
11971            }
11972        }
11973    }
11974
11975    void removePackageLI(PackageSetting ps, boolean chatty) {
11976        if (DEBUG_INSTALL) {
11977            if (chatty)
11978                Log.d(TAG, "Removing package " + ps.name);
11979        }
11980
11981        // writer
11982        synchronized (mPackages) {
11983            mPackages.remove(ps.name);
11984            final PackageParser.Package pkg = ps.pkg;
11985            if (pkg != null) {
11986                cleanPackageDataStructuresLILPw(pkg, chatty);
11987            }
11988        }
11989    }
11990
11991    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11992        if (DEBUG_INSTALL) {
11993            if (chatty)
11994                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11995        }
11996
11997        // writer
11998        synchronized (mPackages) {
11999            // Remove the parent package
12000            mPackages.remove(pkg.applicationInfo.packageName);
12001            cleanPackageDataStructuresLILPw(pkg, chatty);
12002
12003            // Remove the child packages
12004            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12005            for (int i = 0; i < childCount; i++) {
12006                PackageParser.Package childPkg = pkg.childPackages.get(i);
12007                mPackages.remove(childPkg.applicationInfo.packageName);
12008                cleanPackageDataStructuresLILPw(childPkg, chatty);
12009            }
12010        }
12011    }
12012
12013    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12014        int N = pkg.providers.size();
12015        StringBuilder r = null;
12016        int i;
12017        for (i=0; i<N; i++) {
12018            PackageParser.Provider p = pkg.providers.get(i);
12019            mProviders.removeProvider(p);
12020            if (p.info.authority == null) {
12021
12022                /* There was another ContentProvider with this authority when
12023                 * this app was installed so this authority is null,
12024                 * Ignore it as we don't have to unregister the provider.
12025                 */
12026                continue;
12027            }
12028            String names[] = p.info.authority.split(";");
12029            for (int j = 0; j < names.length; j++) {
12030                if (mProvidersByAuthority.get(names[j]) == p) {
12031                    mProvidersByAuthority.remove(names[j]);
12032                    if (DEBUG_REMOVE) {
12033                        if (chatty)
12034                            Log.d(TAG, "Unregistered content provider: " + names[j]
12035                                    + ", className = " + p.info.name + ", isSyncable = "
12036                                    + p.info.isSyncable);
12037                    }
12038                }
12039            }
12040            if (DEBUG_REMOVE && chatty) {
12041                if (r == null) {
12042                    r = new StringBuilder(256);
12043                } else {
12044                    r.append(' ');
12045                }
12046                r.append(p.info.name);
12047            }
12048        }
12049        if (r != null) {
12050            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12051        }
12052
12053        N = pkg.services.size();
12054        r = null;
12055        for (i=0; i<N; i++) {
12056            PackageParser.Service s = pkg.services.get(i);
12057            mServices.removeService(s);
12058            if (chatty) {
12059                if (r == null) {
12060                    r = new StringBuilder(256);
12061                } else {
12062                    r.append(' ');
12063                }
12064                r.append(s.info.name);
12065            }
12066        }
12067        if (r != null) {
12068            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12069        }
12070
12071        N = pkg.receivers.size();
12072        r = null;
12073        for (i=0; i<N; i++) {
12074            PackageParser.Activity a = pkg.receivers.get(i);
12075            mReceivers.removeActivity(a, "receiver");
12076            if (DEBUG_REMOVE && chatty) {
12077                if (r == null) {
12078                    r = new StringBuilder(256);
12079                } else {
12080                    r.append(' ');
12081                }
12082                r.append(a.info.name);
12083            }
12084        }
12085        if (r != null) {
12086            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12087        }
12088
12089        N = pkg.activities.size();
12090        r = null;
12091        for (i=0; i<N; i++) {
12092            PackageParser.Activity a = pkg.activities.get(i);
12093            mActivities.removeActivity(a, "activity");
12094            if (DEBUG_REMOVE && chatty) {
12095                if (r == null) {
12096                    r = new StringBuilder(256);
12097                } else {
12098                    r.append(' ');
12099                }
12100                r.append(a.info.name);
12101            }
12102        }
12103        if (r != null) {
12104            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12105        }
12106
12107        mPermissionManager.removeAllPermissions(pkg, chatty);
12108
12109        N = pkg.instrumentation.size();
12110        r = null;
12111        for (i=0; i<N; i++) {
12112            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12113            mInstrumentation.remove(a.getComponentName());
12114            if (DEBUG_REMOVE && chatty) {
12115                if (r == null) {
12116                    r = new StringBuilder(256);
12117                } else {
12118                    r.append(' ');
12119                }
12120                r.append(a.info.name);
12121            }
12122        }
12123        if (r != null) {
12124            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12125        }
12126
12127        r = null;
12128        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12129            // Only system apps can hold shared libraries.
12130            if (pkg.libraryNames != null) {
12131                for (i = 0; i < pkg.libraryNames.size(); i++) {
12132                    String name = pkg.libraryNames.get(i);
12133                    if (removeSharedLibraryLPw(name, 0)) {
12134                        if (DEBUG_REMOVE && chatty) {
12135                            if (r == null) {
12136                                r = new StringBuilder(256);
12137                            } else {
12138                                r.append(' ');
12139                            }
12140                            r.append(name);
12141                        }
12142                    }
12143                }
12144            }
12145        }
12146
12147        r = null;
12148
12149        // Any package can hold static shared libraries.
12150        if (pkg.staticSharedLibName != null) {
12151            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12152                if (DEBUG_REMOVE && chatty) {
12153                    if (r == null) {
12154                        r = new StringBuilder(256);
12155                    } else {
12156                        r.append(' ');
12157                    }
12158                    r.append(pkg.staticSharedLibName);
12159                }
12160            }
12161        }
12162
12163        if (r != null) {
12164            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12165        }
12166    }
12167
12168
12169    final class ActivityIntentResolver
12170            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12171        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12172                boolean defaultOnly, int userId) {
12173            if (!sUserManager.exists(userId)) return null;
12174            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12175            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12176        }
12177
12178        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12179                int userId) {
12180            if (!sUserManager.exists(userId)) return null;
12181            mFlags = flags;
12182            return super.queryIntent(intent, resolvedType,
12183                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12184                    userId);
12185        }
12186
12187        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12188                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12189            if (!sUserManager.exists(userId)) return null;
12190            if (packageActivities == null) {
12191                return null;
12192            }
12193            mFlags = flags;
12194            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12195            final int N = packageActivities.size();
12196            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12197                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12198
12199            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12200            for (int i = 0; i < N; ++i) {
12201                intentFilters = packageActivities.get(i).intents;
12202                if (intentFilters != null && intentFilters.size() > 0) {
12203                    PackageParser.ActivityIntentInfo[] array =
12204                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12205                    intentFilters.toArray(array);
12206                    listCut.add(array);
12207                }
12208            }
12209            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12210        }
12211
12212        /**
12213         * Finds a privileged activity that matches the specified activity names.
12214         */
12215        private PackageParser.Activity findMatchingActivity(
12216                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12217            for (PackageParser.Activity sysActivity : activityList) {
12218                if (sysActivity.info.name.equals(activityInfo.name)) {
12219                    return sysActivity;
12220                }
12221                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12222                    return sysActivity;
12223                }
12224                if (sysActivity.info.targetActivity != null) {
12225                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12226                        return sysActivity;
12227                    }
12228                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12229                        return sysActivity;
12230                    }
12231                }
12232            }
12233            return null;
12234        }
12235
12236        public class IterGenerator<E> {
12237            public Iterator<E> generate(ActivityIntentInfo info) {
12238                return null;
12239            }
12240        }
12241
12242        public class ActionIterGenerator extends IterGenerator<String> {
12243            @Override
12244            public Iterator<String> generate(ActivityIntentInfo info) {
12245                return info.actionsIterator();
12246            }
12247        }
12248
12249        public class CategoriesIterGenerator extends IterGenerator<String> {
12250            @Override
12251            public Iterator<String> generate(ActivityIntentInfo info) {
12252                return info.categoriesIterator();
12253            }
12254        }
12255
12256        public class SchemesIterGenerator extends IterGenerator<String> {
12257            @Override
12258            public Iterator<String> generate(ActivityIntentInfo info) {
12259                return info.schemesIterator();
12260            }
12261        }
12262
12263        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12264            @Override
12265            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12266                return info.authoritiesIterator();
12267            }
12268        }
12269
12270        /**
12271         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12272         * MODIFIED. Do not pass in a list that should not be changed.
12273         */
12274        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12275                IterGenerator<T> generator, Iterator<T> searchIterator) {
12276            // loop through the set of actions; every one must be found in the intent filter
12277            while (searchIterator.hasNext()) {
12278                // we must have at least one filter in the list to consider a match
12279                if (intentList.size() == 0) {
12280                    break;
12281                }
12282
12283                final T searchAction = searchIterator.next();
12284
12285                // loop through the set of intent filters
12286                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12287                while (intentIter.hasNext()) {
12288                    final ActivityIntentInfo intentInfo = intentIter.next();
12289                    boolean selectionFound = false;
12290
12291                    // loop through the intent filter's selection criteria; at least one
12292                    // of them must match the searched criteria
12293                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12294                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12295                        final T intentSelection = intentSelectionIter.next();
12296                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12297                            selectionFound = true;
12298                            break;
12299                        }
12300                    }
12301
12302                    // the selection criteria wasn't found in this filter's set; this filter
12303                    // is not a potential match
12304                    if (!selectionFound) {
12305                        intentIter.remove();
12306                    }
12307                }
12308            }
12309        }
12310
12311        private boolean isProtectedAction(ActivityIntentInfo filter) {
12312            final Iterator<String> actionsIter = filter.actionsIterator();
12313            while (actionsIter != null && actionsIter.hasNext()) {
12314                final String filterAction = actionsIter.next();
12315                if (PROTECTED_ACTIONS.contains(filterAction)) {
12316                    return true;
12317                }
12318            }
12319            return false;
12320        }
12321
12322        /**
12323         * Adjusts the priority of the given intent filter according to policy.
12324         * <p>
12325         * <ul>
12326         * <li>The priority for non privileged applications is capped to '0'</li>
12327         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12328         * <li>The priority for unbundled updates to privileged applications is capped to the
12329         *      priority defined on the system partition</li>
12330         * </ul>
12331         * <p>
12332         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12333         * allowed to obtain any priority on any action.
12334         */
12335        private void adjustPriority(
12336                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12337            // nothing to do; priority is fine as-is
12338            if (intent.getPriority() <= 0) {
12339                return;
12340            }
12341
12342            final ActivityInfo activityInfo = intent.activity.info;
12343            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12344
12345            final boolean privilegedApp =
12346                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12347            if (!privilegedApp) {
12348                // non-privileged applications can never define a priority >0
12349                if (DEBUG_FILTERS) {
12350                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12351                            + " package: " + applicationInfo.packageName
12352                            + " activity: " + intent.activity.className
12353                            + " origPrio: " + intent.getPriority());
12354                }
12355                intent.setPriority(0);
12356                return;
12357            }
12358
12359            if (systemActivities == null) {
12360                // the system package is not disabled; we're parsing the system partition
12361                if (isProtectedAction(intent)) {
12362                    if (mDeferProtectedFilters) {
12363                        // We can't deal with these just yet. No component should ever obtain a
12364                        // >0 priority for a protected actions, with ONE exception -- the setup
12365                        // wizard. The setup wizard, however, cannot be known until we're able to
12366                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12367                        // until all intent filters have been processed. Chicken, meet egg.
12368                        // Let the filter temporarily have a high priority and rectify the
12369                        // priorities after all system packages have been scanned.
12370                        mProtectedFilters.add(intent);
12371                        if (DEBUG_FILTERS) {
12372                            Slog.i(TAG, "Protected action; save for later;"
12373                                    + " package: " + applicationInfo.packageName
12374                                    + " activity: " + intent.activity.className
12375                                    + " origPrio: " + intent.getPriority());
12376                        }
12377                        return;
12378                    } else {
12379                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12380                            Slog.i(TAG, "No setup wizard;"
12381                                + " All protected intents capped to priority 0");
12382                        }
12383                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12384                            if (DEBUG_FILTERS) {
12385                                Slog.i(TAG, "Found setup wizard;"
12386                                    + " allow priority " + intent.getPriority() + ";"
12387                                    + " package: " + intent.activity.info.packageName
12388                                    + " activity: " + intent.activity.className
12389                                    + " priority: " + intent.getPriority());
12390                            }
12391                            // setup wizard gets whatever it wants
12392                            return;
12393                        }
12394                        if (DEBUG_FILTERS) {
12395                            Slog.i(TAG, "Protected action; cap priority to 0;"
12396                                    + " package: " + intent.activity.info.packageName
12397                                    + " activity: " + intent.activity.className
12398                                    + " origPrio: " + intent.getPriority());
12399                        }
12400                        intent.setPriority(0);
12401                        return;
12402                    }
12403                }
12404                // privileged apps on the system image get whatever priority they request
12405                return;
12406            }
12407
12408            // privileged app unbundled update ... try to find the same activity
12409            final PackageParser.Activity foundActivity =
12410                    findMatchingActivity(systemActivities, activityInfo);
12411            if (foundActivity == null) {
12412                // this is a new activity; it cannot obtain >0 priority
12413                if (DEBUG_FILTERS) {
12414                    Slog.i(TAG, "New activity; cap priority to 0;"
12415                            + " package: " + applicationInfo.packageName
12416                            + " activity: " + intent.activity.className
12417                            + " origPrio: " + intent.getPriority());
12418                }
12419                intent.setPriority(0);
12420                return;
12421            }
12422
12423            // found activity, now check for filter equivalence
12424
12425            // a shallow copy is enough; we modify the list, not its contents
12426            final List<ActivityIntentInfo> intentListCopy =
12427                    new ArrayList<>(foundActivity.intents);
12428            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12429
12430            // find matching action subsets
12431            final Iterator<String> actionsIterator = intent.actionsIterator();
12432            if (actionsIterator != null) {
12433                getIntentListSubset(
12434                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12435                if (intentListCopy.size() == 0) {
12436                    // no more intents to match; we're not equivalent
12437                    if (DEBUG_FILTERS) {
12438                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12439                                + " package: " + applicationInfo.packageName
12440                                + " activity: " + intent.activity.className
12441                                + " origPrio: " + intent.getPriority());
12442                    }
12443                    intent.setPriority(0);
12444                    return;
12445                }
12446            }
12447
12448            // find matching category subsets
12449            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12450            if (categoriesIterator != null) {
12451                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12452                        categoriesIterator);
12453                if (intentListCopy.size() == 0) {
12454                    // no more intents to match; we're not equivalent
12455                    if (DEBUG_FILTERS) {
12456                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12457                                + " package: " + applicationInfo.packageName
12458                                + " activity: " + intent.activity.className
12459                                + " origPrio: " + intent.getPriority());
12460                    }
12461                    intent.setPriority(0);
12462                    return;
12463                }
12464            }
12465
12466            // find matching schemes subsets
12467            final Iterator<String> schemesIterator = intent.schemesIterator();
12468            if (schemesIterator != null) {
12469                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12470                        schemesIterator);
12471                if (intentListCopy.size() == 0) {
12472                    // no more intents to match; we're not equivalent
12473                    if (DEBUG_FILTERS) {
12474                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12475                                + " package: " + applicationInfo.packageName
12476                                + " activity: " + intent.activity.className
12477                                + " origPrio: " + intent.getPriority());
12478                    }
12479                    intent.setPriority(0);
12480                    return;
12481                }
12482            }
12483
12484            // find matching authorities subsets
12485            final Iterator<IntentFilter.AuthorityEntry>
12486                    authoritiesIterator = intent.authoritiesIterator();
12487            if (authoritiesIterator != null) {
12488                getIntentListSubset(intentListCopy,
12489                        new AuthoritiesIterGenerator(),
12490                        authoritiesIterator);
12491                if (intentListCopy.size() == 0) {
12492                    // no more intents to match; we're not equivalent
12493                    if (DEBUG_FILTERS) {
12494                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12495                                + " package: " + applicationInfo.packageName
12496                                + " activity: " + intent.activity.className
12497                                + " origPrio: " + intent.getPriority());
12498                    }
12499                    intent.setPriority(0);
12500                    return;
12501                }
12502            }
12503
12504            // we found matching filter(s); app gets the max priority of all intents
12505            int cappedPriority = 0;
12506            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12507                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12508            }
12509            if (intent.getPriority() > cappedPriority) {
12510                if (DEBUG_FILTERS) {
12511                    Slog.i(TAG, "Found matching filter(s);"
12512                            + " cap priority to " + cappedPriority + ";"
12513                            + " package: " + applicationInfo.packageName
12514                            + " activity: " + intent.activity.className
12515                            + " origPrio: " + intent.getPriority());
12516                }
12517                intent.setPriority(cappedPriority);
12518                return;
12519            }
12520            // all this for nothing; the requested priority was <= what was on the system
12521        }
12522
12523        public final void addActivity(PackageParser.Activity a, String type) {
12524            mActivities.put(a.getComponentName(), a);
12525            if (DEBUG_SHOW_INFO)
12526                Log.v(
12527                TAG, "  " + type + " " +
12528                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12529            if (DEBUG_SHOW_INFO)
12530                Log.v(TAG, "    Class=" + a.info.name);
12531            final int NI = a.intents.size();
12532            for (int j=0; j<NI; j++) {
12533                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12534                if ("activity".equals(type)) {
12535                    final PackageSetting ps =
12536                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12537                    final List<PackageParser.Activity> systemActivities =
12538                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12539                    adjustPriority(systemActivities, intent);
12540                }
12541                if (DEBUG_SHOW_INFO) {
12542                    Log.v(TAG, "    IntentFilter:");
12543                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12544                }
12545                if (!intent.debugCheck()) {
12546                    Log.w(TAG, "==> For Activity " + a.info.name);
12547                }
12548                addFilter(intent);
12549            }
12550        }
12551
12552        public final void removeActivity(PackageParser.Activity a, String type) {
12553            mActivities.remove(a.getComponentName());
12554            if (DEBUG_SHOW_INFO) {
12555                Log.v(TAG, "  " + type + " "
12556                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12557                                : a.info.name) + ":");
12558                Log.v(TAG, "    Class=" + a.info.name);
12559            }
12560            final int NI = a.intents.size();
12561            for (int j=0; j<NI; j++) {
12562                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12563                if (DEBUG_SHOW_INFO) {
12564                    Log.v(TAG, "    IntentFilter:");
12565                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12566                }
12567                removeFilter(intent);
12568            }
12569        }
12570
12571        @Override
12572        protected boolean allowFilterResult(
12573                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12574            ActivityInfo filterAi = filter.activity.info;
12575            for (int i=dest.size()-1; i>=0; i--) {
12576                ActivityInfo destAi = dest.get(i).activityInfo;
12577                if (destAi.name == filterAi.name
12578                        && destAi.packageName == filterAi.packageName) {
12579                    return false;
12580                }
12581            }
12582            return true;
12583        }
12584
12585        @Override
12586        protected ActivityIntentInfo[] newArray(int size) {
12587            return new ActivityIntentInfo[size];
12588        }
12589
12590        @Override
12591        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12592            if (!sUserManager.exists(userId)) return true;
12593            PackageParser.Package p = filter.activity.owner;
12594            if (p != null) {
12595                PackageSetting ps = (PackageSetting)p.mExtras;
12596                if (ps != null) {
12597                    // System apps are never considered stopped for purposes of
12598                    // filtering, because there may be no way for the user to
12599                    // actually re-launch them.
12600                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12601                            && ps.getStopped(userId);
12602                }
12603            }
12604            return false;
12605        }
12606
12607        @Override
12608        protected boolean isPackageForFilter(String packageName,
12609                PackageParser.ActivityIntentInfo info) {
12610            return packageName.equals(info.activity.owner.packageName);
12611        }
12612
12613        @Override
12614        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12615                int match, int userId) {
12616            if (!sUserManager.exists(userId)) return null;
12617            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12618                return null;
12619            }
12620            final PackageParser.Activity activity = info.activity;
12621            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12622            if (ps == null) {
12623                return null;
12624            }
12625            final PackageUserState userState = ps.readUserState(userId);
12626            ActivityInfo ai =
12627                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12628            if (ai == null) {
12629                return null;
12630            }
12631            final boolean matchExplicitlyVisibleOnly =
12632                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12633            final boolean matchVisibleToInstantApp =
12634                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12635            final boolean componentVisible =
12636                    matchVisibleToInstantApp
12637                    && info.isVisibleToInstantApp()
12638                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12639            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12640            // throw out filters that aren't visible to ephemeral apps
12641            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12642                return null;
12643            }
12644            // throw out instant app filters if we're not explicitly requesting them
12645            if (!matchInstantApp && userState.instantApp) {
12646                return null;
12647            }
12648            // throw out instant app filters if updates are available; will trigger
12649            // instant app resolution
12650            if (userState.instantApp && ps.isUpdateAvailable()) {
12651                return null;
12652            }
12653            final ResolveInfo res = new ResolveInfo();
12654            res.activityInfo = ai;
12655            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12656                res.filter = info;
12657            }
12658            if (info != null) {
12659                res.handleAllWebDataURI = info.handleAllWebDataURI();
12660            }
12661            res.priority = info.getPriority();
12662            res.preferredOrder = activity.owner.mPreferredOrder;
12663            //System.out.println("Result: " + res.activityInfo.className +
12664            //                   " = " + res.priority);
12665            res.match = match;
12666            res.isDefault = info.hasDefault;
12667            res.labelRes = info.labelRes;
12668            res.nonLocalizedLabel = info.nonLocalizedLabel;
12669            if (userNeedsBadging(userId)) {
12670                res.noResourceId = true;
12671            } else {
12672                res.icon = info.icon;
12673            }
12674            res.iconResourceId = info.icon;
12675            res.system = res.activityInfo.applicationInfo.isSystemApp();
12676            res.isInstantAppAvailable = userState.instantApp;
12677            return res;
12678        }
12679
12680        @Override
12681        protected void sortResults(List<ResolveInfo> results) {
12682            Collections.sort(results, mResolvePrioritySorter);
12683        }
12684
12685        @Override
12686        protected void dumpFilter(PrintWriter out, String prefix,
12687                PackageParser.ActivityIntentInfo filter) {
12688            out.print(prefix); out.print(
12689                    Integer.toHexString(System.identityHashCode(filter.activity)));
12690                    out.print(' ');
12691                    filter.activity.printComponentShortName(out);
12692                    out.print(" filter ");
12693                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12694        }
12695
12696        @Override
12697        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12698            return filter.activity;
12699        }
12700
12701        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12702            PackageParser.Activity activity = (PackageParser.Activity)label;
12703            out.print(prefix); out.print(
12704                    Integer.toHexString(System.identityHashCode(activity)));
12705                    out.print(' ');
12706                    activity.printComponentShortName(out);
12707            if (count > 1) {
12708                out.print(" ("); out.print(count); out.print(" filters)");
12709            }
12710            out.println();
12711        }
12712
12713        // Keys are String (activity class name), values are Activity.
12714        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12715                = new ArrayMap<ComponentName, PackageParser.Activity>();
12716        private int mFlags;
12717    }
12718
12719    private final class ServiceIntentResolver
12720            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12721        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12722                boolean defaultOnly, int userId) {
12723            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12724            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12725        }
12726
12727        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12728                int userId) {
12729            if (!sUserManager.exists(userId)) return null;
12730            mFlags = flags;
12731            return super.queryIntent(intent, resolvedType,
12732                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12733                    userId);
12734        }
12735
12736        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12737                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12738            if (!sUserManager.exists(userId)) return null;
12739            if (packageServices == null) {
12740                return null;
12741            }
12742            mFlags = flags;
12743            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12744            final int N = packageServices.size();
12745            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12746                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12747
12748            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12749            for (int i = 0; i < N; ++i) {
12750                intentFilters = packageServices.get(i).intents;
12751                if (intentFilters != null && intentFilters.size() > 0) {
12752                    PackageParser.ServiceIntentInfo[] array =
12753                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12754                    intentFilters.toArray(array);
12755                    listCut.add(array);
12756                }
12757            }
12758            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12759        }
12760
12761        public final void addService(PackageParser.Service s) {
12762            mServices.put(s.getComponentName(), s);
12763            if (DEBUG_SHOW_INFO) {
12764                Log.v(TAG, "  "
12765                        + (s.info.nonLocalizedLabel != null
12766                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12767                Log.v(TAG, "    Class=" + s.info.name);
12768            }
12769            final int NI = s.intents.size();
12770            int j;
12771            for (j=0; j<NI; j++) {
12772                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12773                if (DEBUG_SHOW_INFO) {
12774                    Log.v(TAG, "    IntentFilter:");
12775                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12776                }
12777                if (!intent.debugCheck()) {
12778                    Log.w(TAG, "==> For Service " + s.info.name);
12779                }
12780                addFilter(intent);
12781            }
12782        }
12783
12784        public final void removeService(PackageParser.Service s) {
12785            mServices.remove(s.getComponentName());
12786            if (DEBUG_SHOW_INFO) {
12787                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12788                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12789                Log.v(TAG, "    Class=" + s.info.name);
12790            }
12791            final int NI = s.intents.size();
12792            int j;
12793            for (j=0; j<NI; j++) {
12794                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12795                if (DEBUG_SHOW_INFO) {
12796                    Log.v(TAG, "    IntentFilter:");
12797                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12798                }
12799                removeFilter(intent);
12800            }
12801        }
12802
12803        @Override
12804        protected boolean allowFilterResult(
12805                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12806            ServiceInfo filterSi = filter.service.info;
12807            for (int i=dest.size()-1; i>=0; i--) {
12808                ServiceInfo destAi = dest.get(i).serviceInfo;
12809                if (destAi.name == filterSi.name
12810                        && destAi.packageName == filterSi.packageName) {
12811                    return false;
12812                }
12813            }
12814            return true;
12815        }
12816
12817        @Override
12818        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12819            return new PackageParser.ServiceIntentInfo[size];
12820        }
12821
12822        @Override
12823        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12824            if (!sUserManager.exists(userId)) return true;
12825            PackageParser.Package p = filter.service.owner;
12826            if (p != null) {
12827                PackageSetting ps = (PackageSetting)p.mExtras;
12828                if (ps != null) {
12829                    // System apps are never considered stopped for purposes of
12830                    // filtering, because there may be no way for the user to
12831                    // actually re-launch them.
12832                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12833                            && ps.getStopped(userId);
12834                }
12835            }
12836            return false;
12837        }
12838
12839        @Override
12840        protected boolean isPackageForFilter(String packageName,
12841                PackageParser.ServiceIntentInfo info) {
12842            return packageName.equals(info.service.owner.packageName);
12843        }
12844
12845        @Override
12846        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12847                int match, int userId) {
12848            if (!sUserManager.exists(userId)) return null;
12849            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12850            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12851                return null;
12852            }
12853            final PackageParser.Service service = info.service;
12854            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12855            if (ps == null) {
12856                return null;
12857            }
12858            final PackageUserState userState = ps.readUserState(userId);
12859            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12860                    userState, userId);
12861            if (si == null) {
12862                return null;
12863            }
12864            final boolean matchVisibleToInstantApp =
12865                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12866            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12867            // throw out filters that aren't visible to ephemeral apps
12868            if (matchVisibleToInstantApp
12869                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12870                return null;
12871            }
12872            // throw out ephemeral filters if we're not explicitly requesting them
12873            if (!isInstantApp && userState.instantApp) {
12874                return null;
12875            }
12876            // throw out instant app filters if updates are available; will trigger
12877            // instant app resolution
12878            if (userState.instantApp && ps.isUpdateAvailable()) {
12879                return null;
12880            }
12881            final ResolveInfo res = new ResolveInfo();
12882            res.serviceInfo = si;
12883            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12884                res.filter = filter;
12885            }
12886            res.priority = info.getPriority();
12887            res.preferredOrder = service.owner.mPreferredOrder;
12888            res.match = match;
12889            res.isDefault = info.hasDefault;
12890            res.labelRes = info.labelRes;
12891            res.nonLocalizedLabel = info.nonLocalizedLabel;
12892            res.icon = info.icon;
12893            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12894            return res;
12895        }
12896
12897        @Override
12898        protected void sortResults(List<ResolveInfo> results) {
12899            Collections.sort(results, mResolvePrioritySorter);
12900        }
12901
12902        @Override
12903        protected void dumpFilter(PrintWriter out, String prefix,
12904                PackageParser.ServiceIntentInfo filter) {
12905            out.print(prefix); out.print(
12906                    Integer.toHexString(System.identityHashCode(filter.service)));
12907                    out.print(' ');
12908                    filter.service.printComponentShortName(out);
12909                    out.print(" filter ");
12910                    out.print(Integer.toHexString(System.identityHashCode(filter)));
12911                    if (filter.service.info.permission != null) {
12912                        out.print(" permission "); out.println(filter.service.info.permission);
12913                    } else {
12914                        out.println();
12915                    }
12916        }
12917
12918        @Override
12919        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12920            return filter.service;
12921        }
12922
12923        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12924            PackageParser.Service service = (PackageParser.Service)label;
12925            out.print(prefix); out.print(
12926                    Integer.toHexString(System.identityHashCode(service)));
12927                    out.print(' ');
12928                    service.printComponentShortName(out);
12929            if (count > 1) {
12930                out.print(" ("); out.print(count); out.print(" filters)");
12931            }
12932            out.println();
12933        }
12934
12935//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12936//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12937//            final List<ResolveInfo> retList = Lists.newArrayList();
12938//            while (i.hasNext()) {
12939//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12940//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12941//                    retList.add(resolveInfo);
12942//                }
12943//            }
12944//            return retList;
12945//        }
12946
12947        // Keys are String (activity class name), values are Activity.
12948        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12949                = new ArrayMap<ComponentName, PackageParser.Service>();
12950        private int mFlags;
12951    }
12952
12953    private final class ProviderIntentResolver
12954            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12955        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12956                boolean defaultOnly, int userId) {
12957            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12958            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12959        }
12960
12961        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12962                int userId) {
12963            if (!sUserManager.exists(userId))
12964                return null;
12965            mFlags = flags;
12966            return super.queryIntent(intent, resolvedType,
12967                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12968                    userId);
12969        }
12970
12971        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12972                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12973            if (!sUserManager.exists(userId))
12974                return null;
12975            if (packageProviders == null) {
12976                return null;
12977            }
12978            mFlags = flags;
12979            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12980            final int N = packageProviders.size();
12981            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12982                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12983
12984            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12985            for (int i = 0; i < N; ++i) {
12986                intentFilters = packageProviders.get(i).intents;
12987                if (intentFilters != null && intentFilters.size() > 0) {
12988                    PackageParser.ProviderIntentInfo[] array =
12989                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12990                    intentFilters.toArray(array);
12991                    listCut.add(array);
12992                }
12993            }
12994            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12995        }
12996
12997        public final void addProvider(PackageParser.Provider p) {
12998            if (mProviders.containsKey(p.getComponentName())) {
12999                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13000                return;
13001            }
13002
13003            mProviders.put(p.getComponentName(), p);
13004            if (DEBUG_SHOW_INFO) {
13005                Log.v(TAG, "  "
13006                        + (p.info.nonLocalizedLabel != null
13007                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13008                Log.v(TAG, "    Class=" + p.info.name);
13009            }
13010            final int NI = p.intents.size();
13011            int j;
13012            for (j = 0; j < NI; j++) {
13013                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13014                if (DEBUG_SHOW_INFO) {
13015                    Log.v(TAG, "    IntentFilter:");
13016                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13017                }
13018                if (!intent.debugCheck()) {
13019                    Log.w(TAG, "==> For Provider " + p.info.name);
13020                }
13021                addFilter(intent);
13022            }
13023        }
13024
13025        public final void removeProvider(PackageParser.Provider p) {
13026            mProviders.remove(p.getComponentName());
13027            if (DEBUG_SHOW_INFO) {
13028                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13029                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13030                Log.v(TAG, "    Class=" + p.info.name);
13031            }
13032            final int NI = p.intents.size();
13033            int j;
13034            for (j = 0; j < NI; j++) {
13035                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13036                if (DEBUG_SHOW_INFO) {
13037                    Log.v(TAG, "    IntentFilter:");
13038                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13039                }
13040                removeFilter(intent);
13041            }
13042        }
13043
13044        @Override
13045        protected boolean allowFilterResult(
13046                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13047            ProviderInfo filterPi = filter.provider.info;
13048            for (int i = dest.size() - 1; i >= 0; i--) {
13049                ProviderInfo destPi = dest.get(i).providerInfo;
13050                if (destPi.name == filterPi.name
13051                        && destPi.packageName == filterPi.packageName) {
13052                    return false;
13053                }
13054            }
13055            return true;
13056        }
13057
13058        @Override
13059        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13060            return new PackageParser.ProviderIntentInfo[size];
13061        }
13062
13063        @Override
13064        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13065            if (!sUserManager.exists(userId))
13066                return true;
13067            PackageParser.Package p = filter.provider.owner;
13068            if (p != null) {
13069                PackageSetting ps = (PackageSetting) p.mExtras;
13070                if (ps != null) {
13071                    // System apps are never considered stopped for purposes of
13072                    // filtering, because there may be no way for the user to
13073                    // actually re-launch them.
13074                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13075                            && ps.getStopped(userId);
13076                }
13077            }
13078            return false;
13079        }
13080
13081        @Override
13082        protected boolean isPackageForFilter(String packageName,
13083                PackageParser.ProviderIntentInfo info) {
13084            return packageName.equals(info.provider.owner.packageName);
13085        }
13086
13087        @Override
13088        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13089                int match, int userId) {
13090            if (!sUserManager.exists(userId))
13091                return null;
13092            final PackageParser.ProviderIntentInfo info = filter;
13093            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13094                return null;
13095            }
13096            final PackageParser.Provider provider = info.provider;
13097            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13098            if (ps == null) {
13099                return null;
13100            }
13101            final PackageUserState userState = ps.readUserState(userId);
13102            final boolean matchVisibleToInstantApp =
13103                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13104            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13105            // throw out filters that aren't visible to instant applications
13106            if (matchVisibleToInstantApp
13107                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13108                return null;
13109            }
13110            // throw out instant application filters if we're not explicitly requesting them
13111            if (!isInstantApp && userState.instantApp) {
13112                return null;
13113            }
13114            // throw out instant application filters if updates are available; will trigger
13115            // instant application resolution
13116            if (userState.instantApp && ps.isUpdateAvailable()) {
13117                return null;
13118            }
13119            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13120                    userState, userId);
13121            if (pi == null) {
13122                return null;
13123            }
13124            final ResolveInfo res = new ResolveInfo();
13125            res.providerInfo = pi;
13126            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13127                res.filter = filter;
13128            }
13129            res.priority = info.getPriority();
13130            res.preferredOrder = provider.owner.mPreferredOrder;
13131            res.match = match;
13132            res.isDefault = info.hasDefault;
13133            res.labelRes = info.labelRes;
13134            res.nonLocalizedLabel = info.nonLocalizedLabel;
13135            res.icon = info.icon;
13136            res.system = res.providerInfo.applicationInfo.isSystemApp();
13137            return res;
13138        }
13139
13140        @Override
13141        protected void sortResults(List<ResolveInfo> results) {
13142            Collections.sort(results, mResolvePrioritySorter);
13143        }
13144
13145        @Override
13146        protected void dumpFilter(PrintWriter out, String prefix,
13147                PackageParser.ProviderIntentInfo filter) {
13148            out.print(prefix);
13149            out.print(
13150                    Integer.toHexString(System.identityHashCode(filter.provider)));
13151            out.print(' ');
13152            filter.provider.printComponentShortName(out);
13153            out.print(" filter ");
13154            out.println(Integer.toHexString(System.identityHashCode(filter)));
13155        }
13156
13157        @Override
13158        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13159            return filter.provider;
13160        }
13161
13162        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13163            PackageParser.Provider provider = (PackageParser.Provider)label;
13164            out.print(prefix); out.print(
13165                    Integer.toHexString(System.identityHashCode(provider)));
13166                    out.print(' ');
13167                    provider.printComponentShortName(out);
13168            if (count > 1) {
13169                out.print(" ("); out.print(count); out.print(" filters)");
13170            }
13171            out.println();
13172        }
13173
13174        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13175                = new ArrayMap<ComponentName, PackageParser.Provider>();
13176        private int mFlags;
13177    }
13178
13179    static final class InstantAppIntentResolver
13180            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13181            AuxiliaryResolveInfo.AuxiliaryFilter> {
13182        /**
13183         * The result that has the highest defined order. Ordering applies on a
13184         * per-package basis. Mapping is from package name to Pair of order and
13185         * EphemeralResolveInfo.
13186         * <p>
13187         * NOTE: This is implemented as a field variable for convenience and efficiency.
13188         * By having a field variable, we're able to track filter ordering as soon as
13189         * a non-zero order is defined. Otherwise, multiple loops across the result set
13190         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13191         * this needs to be contained entirely within {@link #filterResults}.
13192         */
13193        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13194
13195        @Override
13196        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13197            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13198        }
13199
13200        @Override
13201        protected boolean isPackageForFilter(String packageName,
13202                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13203            return true;
13204        }
13205
13206        @Override
13207        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13208                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13209            if (!sUserManager.exists(userId)) {
13210                return null;
13211            }
13212            final String packageName = responseObj.resolveInfo.getPackageName();
13213            final Integer order = responseObj.getOrder();
13214            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13215                    mOrderResult.get(packageName);
13216            // ordering is enabled and this item's order isn't high enough
13217            if (lastOrderResult != null && lastOrderResult.first >= order) {
13218                return null;
13219            }
13220            final InstantAppResolveInfo res = responseObj.resolveInfo;
13221            if (order > 0) {
13222                // non-zero order, enable ordering
13223                mOrderResult.put(packageName, new Pair<>(order, res));
13224            }
13225            return responseObj;
13226        }
13227
13228        @Override
13229        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13230            // only do work if ordering is enabled [most of the time it won't be]
13231            if (mOrderResult.size() == 0) {
13232                return;
13233            }
13234            int resultSize = results.size();
13235            for (int i = 0; i < resultSize; i++) {
13236                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13237                final String packageName = info.getPackageName();
13238                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13239                if (savedInfo == null) {
13240                    // package doesn't having ordering
13241                    continue;
13242                }
13243                if (savedInfo.second == info) {
13244                    // circled back to the highest ordered item; remove from order list
13245                    mOrderResult.remove(packageName);
13246                    if (mOrderResult.size() == 0) {
13247                        // no more ordered items
13248                        break;
13249                    }
13250                    continue;
13251                }
13252                // item has a worse order, remove it from the result list
13253                results.remove(i);
13254                resultSize--;
13255                i--;
13256            }
13257        }
13258    }
13259
13260    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13261            new Comparator<ResolveInfo>() {
13262        public int compare(ResolveInfo r1, ResolveInfo r2) {
13263            int v1 = r1.priority;
13264            int v2 = r2.priority;
13265            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13266            if (v1 != v2) {
13267                return (v1 > v2) ? -1 : 1;
13268            }
13269            v1 = r1.preferredOrder;
13270            v2 = r2.preferredOrder;
13271            if (v1 != v2) {
13272                return (v1 > v2) ? -1 : 1;
13273            }
13274            if (r1.isDefault != r2.isDefault) {
13275                return r1.isDefault ? -1 : 1;
13276            }
13277            v1 = r1.match;
13278            v2 = r2.match;
13279            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13280            if (v1 != v2) {
13281                return (v1 > v2) ? -1 : 1;
13282            }
13283            if (r1.system != r2.system) {
13284                return r1.system ? -1 : 1;
13285            }
13286            if (r1.activityInfo != null) {
13287                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13288            }
13289            if (r1.serviceInfo != null) {
13290                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13291            }
13292            if (r1.providerInfo != null) {
13293                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13294            }
13295            return 0;
13296        }
13297    };
13298
13299    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13300            new Comparator<ProviderInfo>() {
13301        public int compare(ProviderInfo p1, ProviderInfo p2) {
13302            final int v1 = p1.initOrder;
13303            final int v2 = p2.initOrder;
13304            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13305        }
13306    };
13307
13308    @Override
13309    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13310            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13311            final int[] userIds, int[] instantUserIds) {
13312        mHandler.post(new Runnable() {
13313            @Override
13314            public void run() {
13315                try {
13316                    final IActivityManager am = ActivityManager.getService();
13317                    if (am == null) return;
13318                    final int[] resolvedUserIds;
13319                    if (userIds == null) {
13320                        resolvedUserIds = am.getRunningUserIds();
13321                    } else {
13322                        resolvedUserIds = userIds;
13323                    }
13324                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13325                            resolvedUserIds, false);
13326                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13327                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13328                                instantUserIds, true);
13329                    }
13330                } catch (RemoteException ex) {
13331                }
13332            }
13333        });
13334    }
13335
13336    @Override
13337    public void notifyPackageAdded(String packageName) {
13338        final PackageListObserver[] observers;
13339        synchronized (mPackages) {
13340            if (mPackageListObservers.size() == 0) {
13341                return;
13342            }
13343            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13344        }
13345        for (int i = observers.length - 1; i >= 0; --i) {
13346            observers[i].onPackageAdded(packageName);
13347        }
13348    }
13349
13350    @Override
13351    public void notifyPackageRemoved(String packageName) {
13352        final PackageListObserver[] observers;
13353        synchronized (mPackages) {
13354            if (mPackageListObservers.size() == 0) {
13355                return;
13356            }
13357            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13358        }
13359        for (int i = observers.length - 1; i >= 0; --i) {
13360            observers[i].onPackageRemoved(packageName);
13361        }
13362    }
13363
13364    /**
13365     * Sends a broadcast for the given action.
13366     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13367     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13368     * the system and applications allowed to see instant applications to receive package
13369     * lifecycle events for instant applications.
13370     */
13371    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13372            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13373            int[] userIds, boolean isInstantApp)
13374                    throws RemoteException {
13375        for (int id : userIds) {
13376            final Intent intent = new Intent(action,
13377                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13378            final String[] requiredPermissions =
13379                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13380            if (extras != null) {
13381                intent.putExtras(extras);
13382            }
13383            if (targetPkg != null) {
13384                intent.setPackage(targetPkg);
13385            }
13386            // Modify the UID when posting to other users
13387            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13388            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13389                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13390                intent.putExtra(Intent.EXTRA_UID, uid);
13391            }
13392            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13393            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13394            if (DEBUG_BROADCASTS) {
13395                RuntimeException here = new RuntimeException("here");
13396                here.fillInStackTrace();
13397                Slog.d(TAG, "Sending to user " + id + ": "
13398                        + intent.toShortString(false, true, false, false)
13399                        + " " + intent.getExtras(), here);
13400            }
13401            am.broadcastIntent(null, intent, null, finishedReceiver,
13402                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13403                    null, finishedReceiver != null, false, id);
13404        }
13405    }
13406
13407    /**
13408     * Check if the external storage media is available. This is true if there
13409     * is a mounted external storage medium or if the external storage is
13410     * emulated.
13411     */
13412    private boolean isExternalMediaAvailable() {
13413        return mMediaMounted || Environment.isExternalStorageEmulated();
13414    }
13415
13416    @Override
13417    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13418        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13419            return null;
13420        }
13421        if (!isExternalMediaAvailable()) {
13422                // If the external storage is no longer mounted at this point,
13423                // the caller may not have been able to delete all of this
13424                // packages files and can not delete any more.  Bail.
13425            return null;
13426        }
13427        synchronized (mPackages) {
13428            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13429            if (lastPackage != null) {
13430                pkgs.remove(lastPackage);
13431            }
13432            if (pkgs.size() > 0) {
13433                return pkgs.get(0);
13434            }
13435        }
13436        return null;
13437    }
13438
13439    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13440        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13441                userId, andCode ? 1 : 0, packageName);
13442        if (mSystemReady) {
13443            msg.sendToTarget();
13444        } else {
13445            if (mPostSystemReadyMessages == null) {
13446                mPostSystemReadyMessages = new ArrayList<>();
13447            }
13448            mPostSystemReadyMessages.add(msg);
13449        }
13450    }
13451
13452    void startCleaningPackages() {
13453        // reader
13454        if (!isExternalMediaAvailable()) {
13455            return;
13456        }
13457        synchronized (mPackages) {
13458            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13459                return;
13460            }
13461        }
13462        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13463        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13464        IActivityManager am = ActivityManager.getService();
13465        if (am != null) {
13466            int dcsUid = -1;
13467            synchronized (mPackages) {
13468                if (!mDefaultContainerWhitelisted) {
13469                    mDefaultContainerWhitelisted = true;
13470                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13471                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13472                }
13473            }
13474            try {
13475                if (dcsUid > 0) {
13476                    am.backgroundWhitelistUid(dcsUid);
13477                }
13478                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13479                        UserHandle.USER_SYSTEM);
13480            } catch (RemoteException e) {
13481            }
13482        }
13483    }
13484
13485    /**
13486     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13487     * it is acting on behalf on an enterprise or the user).
13488     *
13489     * Note that the ordering of the conditionals in this method is important. The checks we perform
13490     * are as follows, in this order:
13491     *
13492     * 1) If the install is being performed by a system app, we can trust the app to have set the
13493     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13494     *    what it is.
13495     * 2) If the install is being performed by a device or profile owner app, the install reason
13496     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13497     *    set the install reason correctly. If the app targets an older SDK version where install
13498     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13499     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13500     * 3) In all other cases, the install is being performed by a regular app that is neither part
13501     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13502     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13503     *    set to enterprise policy and if so, change it to unknown instead.
13504     */
13505    private int fixUpInstallReason(String installerPackageName, int installerUid,
13506            int installReason) {
13507        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13508                == PERMISSION_GRANTED) {
13509            // If the install is being performed by a system app, we trust that app to have set the
13510            // install reason correctly.
13511            return installReason;
13512        }
13513
13514        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13515            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13516        if (dpm != null) {
13517            ComponentName owner = null;
13518            try {
13519                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13520                if (owner == null) {
13521                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13522                }
13523            } catch (RemoteException e) {
13524            }
13525            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13526                // If the install is being performed by a device or profile owner, the install
13527                // reason should be enterprise policy.
13528                return PackageManager.INSTALL_REASON_POLICY;
13529            }
13530        }
13531
13532        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13533            // If the install is being performed by a regular app (i.e. neither system app nor
13534            // device or profile owner), we have no reason to believe that the app is acting on
13535            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13536            // change it to unknown instead.
13537            return PackageManager.INSTALL_REASON_UNKNOWN;
13538        }
13539
13540        // If the install is being performed by a regular app and the install reason was set to any
13541        // value but enterprise policy, leave the install reason unchanged.
13542        return installReason;
13543    }
13544
13545    void installStage(String packageName, File stagedDir,
13546            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13547            String installerPackageName, int installerUid, UserHandle user,
13548            PackageParser.SigningDetails signingDetails) {
13549        if (DEBUG_INSTANT) {
13550            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13551                Slog.d(TAG, "Ephemeral install of " + packageName);
13552            }
13553        }
13554        final VerificationInfo verificationInfo = new VerificationInfo(
13555                sessionParams.originatingUri, sessionParams.referrerUri,
13556                sessionParams.originatingUid, installerUid);
13557
13558        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13559
13560        final Message msg = mHandler.obtainMessage(INIT_COPY);
13561        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13562                sessionParams.installReason);
13563        final InstallParams params = new InstallParams(origin, null, observer,
13564                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13565                verificationInfo, user, sessionParams.abiOverride,
13566                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13567        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13568        msg.obj = params;
13569
13570        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13571                System.identityHashCode(msg.obj));
13572        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13573                System.identityHashCode(msg.obj));
13574
13575        mHandler.sendMessage(msg);
13576    }
13577
13578    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13579            int userId) {
13580        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13581        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13582        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13583        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13584        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13585                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13586
13587        // Send a session commit broadcast
13588        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13589        info.installReason = pkgSetting.getInstallReason(userId);
13590        info.appPackageName = packageName;
13591        sendSessionCommitBroadcast(info, userId);
13592    }
13593
13594    @Override
13595    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13596            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13597        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13598            return;
13599        }
13600        Bundle extras = new Bundle(1);
13601        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13602        final int uid = UserHandle.getUid(
13603                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13604        extras.putInt(Intent.EXTRA_UID, uid);
13605
13606        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13607                packageName, extras, 0, null, null, userIds, instantUserIds);
13608        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13609            mHandler.post(() -> {
13610                        for (int userId : userIds) {
13611                            sendBootCompletedBroadcastToSystemApp(
13612                                    packageName, includeStopped, userId);
13613                        }
13614                    }
13615            );
13616        }
13617    }
13618
13619    /**
13620     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13621     * automatically without needing an explicit launch.
13622     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13623     */
13624    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13625            int userId) {
13626        // If user is not running, the app didn't miss any broadcast
13627        if (!mUserManagerInternal.isUserRunning(userId)) {
13628            return;
13629        }
13630        final IActivityManager am = ActivityManager.getService();
13631        try {
13632            // Deliver LOCKED_BOOT_COMPLETED first
13633            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13634                    .setPackage(packageName);
13635            if (includeStopped) {
13636                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13637            }
13638            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13639            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13640                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13641
13642            // Deliver BOOT_COMPLETED only if user is unlocked
13643            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13644                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13645                if (includeStopped) {
13646                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13647                }
13648                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13649                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13650            }
13651        } catch (RemoteException e) {
13652            throw e.rethrowFromSystemServer();
13653        }
13654    }
13655
13656    @Override
13657    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13658            int userId) {
13659        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13660        PackageSetting pkgSetting;
13661        final int callingUid = Binder.getCallingUid();
13662        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13663                true /* requireFullPermission */, true /* checkShell */,
13664                "setApplicationHiddenSetting for user " + userId);
13665
13666        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13667            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13668            return false;
13669        }
13670
13671        long callingId = Binder.clearCallingIdentity();
13672        try {
13673            boolean sendAdded = false;
13674            boolean sendRemoved = false;
13675            // writer
13676            synchronized (mPackages) {
13677                pkgSetting = mSettings.mPackages.get(packageName);
13678                if (pkgSetting == null) {
13679                    return false;
13680                }
13681                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13682                    return false;
13683                }
13684                // Do not allow "android" is being disabled
13685                if ("android".equals(packageName)) {
13686                    Slog.w(TAG, "Cannot hide package: android");
13687                    return false;
13688                }
13689                // Cannot hide static shared libs as they are considered
13690                // a part of the using app (emulating static linking). Also
13691                // static libs are installed always on internal storage.
13692                PackageParser.Package pkg = mPackages.get(packageName);
13693                if (pkg != null && pkg.staticSharedLibName != null) {
13694                    Slog.w(TAG, "Cannot hide package: " + packageName
13695                            + " providing static shared library: "
13696                            + pkg.staticSharedLibName);
13697                    return false;
13698                }
13699                // Only allow protected packages to hide themselves.
13700                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13701                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13702                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13703                    return false;
13704                }
13705
13706                if (pkgSetting.getHidden(userId) != hidden) {
13707                    pkgSetting.setHidden(hidden, userId);
13708                    mSettings.writePackageRestrictionsLPr(userId);
13709                    if (hidden) {
13710                        sendRemoved = true;
13711                    } else {
13712                        sendAdded = true;
13713                    }
13714                }
13715            }
13716            if (sendAdded) {
13717                sendPackageAddedForUser(packageName, pkgSetting, userId);
13718                return true;
13719            }
13720            if (sendRemoved) {
13721                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13722                        "hiding pkg");
13723                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13724                return true;
13725            }
13726        } finally {
13727            Binder.restoreCallingIdentity(callingId);
13728        }
13729        return false;
13730    }
13731
13732    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13733            int userId) {
13734        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13735        info.removedPackage = packageName;
13736        info.installerPackageName = pkgSetting.installerPackageName;
13737        info.removedUsers = new int[] {userId};
13738        info.broadcastUsers = new int[] {userId};
13739        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13740        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13741    }
13742
13743    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13744        if (pkgList.length > 0) {
13745            Bundle extras = new Bundle(1);
13746            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13747
13748            sendPackageBroadcast(
13749                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13750                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13751                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13752                    new int[] {userId}, null);
13753        }
13754    }
13755
13756    /**
13757     * Returns true if application is not found or there was an error. Otherwise it returns
13758     * the hidden state of the package for the given user.
13759     */
13760    @Override
13761    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13762        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13763        final int callingUid = Binder.getCallingUid();
13764        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13765                true /* requireFullPermission */, false /* checkShell */,
13766                "getApplicationHidden for user " + userId);
13767        PackageSetting ps;
13768        long callingId = Binder.clearCallingIdentity();
13769        try {
13770            // writer
13771            synchronized (mPackages) {
13772                ps = mSettings.mPackages.get(packageName);
13773                if (ps == null) {
13774                    return true;
13775                }
13776                if (filterAppAccessLPr(ps, callingUid, userId)) {
13777                    return true;
13778                }
13779                return ps.getHidden(userId);
13780            }
13781        } finally {
13782            Binder.restoreCallingIdentity(callingId);
13783        }
13784    }
13785
13786    /**
13787     * @hide
13788     */
13789    @Override
13790    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13791            int installReason) {
13792        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13793                null);
13794        PackageSetting pkgSetting;
13795        final int callingUid = Binder.getCallingUid();
13796        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13797                true /* requireFullPermission */, true /* checkShell */,
13798                "installExistingPackage for user " + userId);
13799        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13800            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13801        }
13802
13803        long callingId = Binder.clearCallingIdentity();
13804        try {
13805            boolean installed = false;
13806            final boolean instantApp =
13807                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13808            final boolean fullApp =
13809                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13810
13811            // writer
13812            synchronized (mPackages) {
13813                pkgSetting = mSettings.mPackages.get(packageName);
13814                if (pkgSetting == null) {
13815                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13816                }
13817                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13818                    // only allow the existing package to be used if it's installed as a full
13819                    // application for at least one user
13820                    boolean installAllowed = false;
13821                    for (int checkUserId : sUserManager.getUserIds()) {
13822                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13823                        if (installAllowed) {
13824                            break;
13825                        }
13826                    }
13827                    if (!installAllowed) {
13828                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13829                    }
13830                }
13831                if (!pkgSetting.getInstalled(userId)) {
13832                    pkgSetting.setInstalled(true, userId);
13833                    pkgSetting.setHidden(false, userId);
13834                    pkgSetting.setInstallReason(installReason, userId);
13835                    mSettings.writePackageRestrictionsLPr(userId);
13836                    mSettings.writeKernelMappingLPr(pkgSetting);
13837                    installed = true;
13838                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13839                    // upgrade app from instant to full; we don't allow app downgrade
13840                    installed = true;
13841                }
13842                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13843            }
13844
13845            if (installed) {
13846                if (pkgSetting.pkg != null) {
13847                    synchronized (mInstallLock) {
13848                        // We don't need to freeze for a brand new install
13849                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13850                    }
13851                }
13852                sendPackageAddedForUser(packageName, pkgSetting, userId);
13853                synchronized (mPackages) {
13854                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13855                }
13856            }
13857        } finally {
13858            Binder.restoreCallingIdentity(callingId);
13859        }
13860
13861        return PackageManager.INSTALL_SUCCEEDED;
13862    }
13863
13864    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13865            boolean instantApp, boolean fullApp) {
13866        // no state specified; do nothing
13867        if (!instantApp && !fullApp) {
13868            return;
13869        }
13870        if (userId != UserHandle.USER_ALL) {
13871            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13872                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13873            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13874                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13875            }
13876        } else {
13877            for (int currentUserId : sUserManager.getUserIds()) {
13878                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13879                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13880                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13881                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13882                }
13883            }
13884        }
13885    }
13886
13887    boolean isUserRestricted(int userId, String restrictionKey) {
13888        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13889        if (restrictions.getBoolean(restrictionKey, false)) {
13890            Log.w(TAG, "User is restricted: " + restrictionKey);
13891            return true;
13892        }
13893        return false;
13894    }
13895
13896    @Override
13897    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13898            int userId) {
13899        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13900        final int callingUid = Binder.getCallingUid();
13901        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13902                true /* requireFullPermission */, true /* checkShell */,
13903                "setPackagesSuspended for user " + userId);
13904
13905        if (ArrayUtils.isEmpty(packageNames)) {
13906            return packageNames;
13907        }
13908
13909        // List of package names for whom the suspended state has changed.
13910        List<String> changedPackages = new ArrayList<>(packageNames.length);
13911        // List of package names for whom the suspended state is not set as requested in this
13912        // method.
13913        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13914        long callingId = Binder.clearCallingIdentity();
13915        try {
13916            for (int i = 0; i < packageNames.length; i++) {
13917                String packageName = packageNames[i];
13918                boolean changed = false;
13919                final int appId;
13920                synchronized (mPackages) {
13921                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13922                    if (pkgSetting == null
13923                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13924                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13925                                + "\". Skipping suspending/un-suspending.");
13926                        unactionedPackages.add(packageName);
13927                        continue;
13928                    }
13929                    appId = pkgSetting.appId;
13930                    if (pkgSetting.getSuspended(userId) != suspended) {
13931                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13932                            unactionedPackages.add(packageName);
13933                            continue;
13934                        }
13935                        pkgSetting.setSuspended(suspended, userId);
13936                        mSettings.writePackageRestrictionsLPr(userId);
13937                        changed = true;
13938                        changedPackages.add(packageName);
13939                    }
13940                }
13941
13942                if (changed && suspended) {
13943                    killApplication(packageName, UserHandle.getUid(userId, appId),
13944                            "suspending package");
13945                }
13946            }
13947        } finally {
13948            Binder.restoreCallingIdentity(callingId);
13949        }
13950
13951        if (!changedPackages.isEmpty()) {
13952            sendPackagesSuspendedForUser(changedPackages.toArray(
13953                    new String[changedPackages.size()]), userId, suspended);
13954        }
13955
13956        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13957    }
13958
13959    @Override
13960    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13961        final int callingUid = Binder.getCallingUid();
13962        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13963                true /* requireFullPermission */, false /* checkShell */,
13964                "isPackageSuspendedForUser for user " + userId);
13965        synchronized (mPackages) {
13966            final PackageSetting ps = mSettings.mPackages.get(packageName);
13967            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
13968                throw new IllegalArgumentException("Unknown target package: " + packageName);
13969            }
13970            return ps.getSuspended(userId);
13971        }
13972    }
13973
13974    @GuardedBy("mPackages")
13975    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13976        if (isPackageDeviceAdmin(packageName, userId)) {
13977            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13978                    + "\": has an active device admin");
13979            return false;
13980        }
13981
13982        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13983        if (packageName.equals(activeLauncherPackageName)) {
13984            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13985                    + "\": contains the active launcher");
13986            return false;
13987        }
13988
13989        if (packageName.equals(mRequiredInstallerPackage)) {
13990            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13991                    + "\": required for package installation");
13992            return false;
13993        }
13994
13995        if (packageName.equals(mRequiredUninstallerPackage)) {
13996            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13997                    + "\": required for package uninstallation");
13998            return false;
13999        }
14000
14001        if (packageName.equals(mRequiredVerifierPackage)) {
14002            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14003                    + "\": required for package verification");
14004            return false;
14005        }
14006
14007        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14008            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14009                    + "\": is the default dialer");
14010            return false;
14011        }
14012
14013        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14014            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14015                    + "\": protected package");
14016            return false;
14017        }
14018
14019        // Cannot suspend static shared libs as they are considered
14020        // a part of the using app (emulating static linking). Also
14021        // static libs are installed always on internal storage.
14022        PackageParser.Package pkg = mPackages.get(packageName);
14023        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14024            Slog.w(TAG, "Cannot suspend package: " + packageName
14025                    + " providing static shared library: "
14026                    + pkg.staticSharedLibName);
14027            return false;
14028        }
14029
14030        return true;
14031    }
14032
14033    private String getActiveLauncherPackageName(int userId) {
14034        Intent intent = new Intent(Intent.ACTION_MAIN);
14035        intent.addCategory(Intent.CATEGORY_HOME);
14036        ResolveInfo resolveInfo = resolveIntent(
14037                intent,
14038                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14039                PackageManager.MATCH_DEFAULT_ONLY,
14040                userId);
14041
14042        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14043    }
14044
14045    private String getDefaultDialerPackageName(int userId) {
14046        synchronized (mPackages) {
14047            return mSettings.getDefaultDialerPackageNameLPw(userId);
14048        }
14049    }
14050
14051    @Override
14052    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14053        mContext.enforceCallingOrSelfPermission(
14054                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14055                "Only package verification agents can verify applications");
14056
14057        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14058        final PackageVerificationResponse response = new PackageVerificationResponse(
14059                verificationCode, Binder.getCallingUid());
14060        msg.arg1 = id;
14061        msg.obj = response;
14062        mHandler.sendMessage(msg);
14063    }
14064
14065    @Override
14066    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14067            long millisecondsToDelay) {
14068        mContext.enforceCallingOrSelfPermission(
14069                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14070                "Only package verification agents can extend verification timeouts");
14071
14072        final PackageVerificationState state = mPendingVerification.get(id);
14073        final PackageVerificationResponse response = new PackageVerificationResponse(
14074                verificationCodeAtTimeout, Binder.getCallingUid());
14075
14076        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14077            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14078        }
14079        if (millisecondsToDelay < 0) {
14080            millisecondsToDelay = 0;
14081        }
14082        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14083                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14084            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14085        }
14086
14087        if ((state != null) && !state.timeoutExtended()) {
14088            state.extendTimeout();
14089
14090            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14091            msg.arg1 = id;
14092            msg.obj = response;
14093            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14094        }
14095    }
14096
14097    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14098            int verificationCode, UserHandle user) {
14099        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14100        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14101        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14102        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14103        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14104
14105        mContext.sendBroadcastAsUser(intent, user,
14106                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14107    }
14108
14109    private ComponentName matchComponentForVerifier(String packageName,
14110            List<ResolveInfo> receivers) {
14111        ActivityInfo targetReceiver = null;
14112
14113        final int NR = receivers.size();
14114        for (int i = 0; i < NR; i++) {
14115            final ResolveInfo info = receivers.get(i);
14116            if (info.activityInfo == null) {
14117                continue;
14118            }
14119
14120            if (packageName.equals(info.activityInfo.packageName)) {
14121                targetReceiver = info.activityInfo;
14122                break;
14123            }
14124        }
14125
14126        if (targetReceiver == null) {
14127            return null;
14128        }
14129
14130        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14131    }
14132
14133    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14134            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14135        if (pkgInfo.verifiers.length == 0) {
14136            return null;
14137        }
14138
14139        final int N = pkgInfo.verifiers.length;
14140        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14141        for (int i = 0; i < N; i++) {
14142            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14143
14144            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14145                    receivers);
14146            if (comp == null) {
14147                continue;
14148            }
14149
14150            final int verifierUid = getUidForVerifier(verifierInfo);
14151            if (verifierUid == -1) {
14152                continue;
14153            }
14154
14155            if (DEBUG_VERIFY) {
14156                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14157                        + " with the correct signature");
14158            }
14159            sufficientVerifiers.add(comp);
14160            verificationState.addSufficientVerifier(verifierUid);
14161        }
14162
14163        return sufficientVerifiers;
14164    }
14165
14166    private int getUidForVerifier(VerifierInfo verifierInfo) {
14167        synchronized (mPackages) {
14168            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14169            if (pkg == null) {
14170                return -1;
14171            } else if (pkg.mSigningDetails.signatures.length != 1) {
14172                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14173                        + " has more than one signature; ignoring");
14174                return -1;
14175            }
14176
14177            /*
14178             * If the public key of the package's signature does not match
14179             * our expected public key, then this is a different package and
14180             * we should skip.
14181             */
14182
14183            final byte[] expectedPublicKey;
14184            try {
14185                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14186                final PublicKey publicKey = verifierSig.getPublicKey();
14187                expectedPublicKey = publicKey.getEncoded();
14188            } catch (CertificateException e) {
14189                return -1;
14190            }
14191
14192            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14193
14194            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14195                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14196                        + " does not have the expected public key; ignoring");
14197                return -1;
14198            }
14199
14200            return pkg.applicationInfo.uid;
14201        }
14202    }
14203
14204    @Override
14205    public void finishPackageInstall(int token, boolean didLaunch) {
14206        enforceSystemOrRoot("Only the system is allowed to finish installs");
14207
14208        if (DEBUG_INSTALL) {
14209            Slog.v(TAG, "BM finishing package install for " + token);
14210        }
14211        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14212
14213        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14214        mHandler.sendMessage(msg);
14215    }
14216
14217    /**
14218     * Get the verification agent timeout.  Used for both the APK verifier and the
14219     * intent filter verifier.
14220     *
14221     * @return verification timeout in milliseconds
14222     */
14223    private long getVerificationTimeout() {
14224        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14225                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14226                DEFAULT_VERIFICATION_TIMEOUT);
14227    }
14228
14229    /**
14230     * Get the default verification agent response code.
14231     *
14232     * @return default verification response code
14233     */
14234    private int getDefaultVerificationResponse(UserHandle user) {
14235        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14236            return PackageManager.VERIFICATION_REJECT;
14237        }
14238        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14239                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14240                DEFAULT_VERIFICATION_RESPONSE);
14241    }
14242
14243    /**
14244     * Check whether or not package verification has been enabled.
14245     *
14246     * @return true if verification should be performed
14247     */
14248    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14249        if (!DEFAULT_VERIFY_ENABLE) {
14250            return false;
14251        }
14252
14253        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14254
14255        // Check if installing from ADB
14256        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14257            // Do not run verification in a test harness environment
14258            if (ActivityManager.isRunningInTestHarness()) {
14259                return false;
14260            }
14261            if (ensureVerifyAppsEnabled) {
14262                return true;
14263            }
14264            // Check if the developer does not want package verification for ADB installs
14265            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14266                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14267                return false;
14268            }
14269        } else {
14270            // only when not installed from ADB, skip verification for instant apps when
14271            // the installer and verifier are the same.
14272            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14273                if (mInstantAppInstallerActivity != null
14274                        && mInstantAppInstallerActivity.packageName.equals(
14275                                mRequiredVerifierPackage)) {
14276                    try {
14277                        mContext.getSystemService(AppOpsManager.class)
14278                                .checkPackage(installerUid, mRequiredVerifierPackage);
14279                        if (DEBUG_VERIFY) {
14280                            Slog.i(TAG, "disable verification for instant app");
14281                        }
14282                        return false;
14283                    } catch (SecurityException ignore) { }
14284                }
14285            }
14286        }
14287
14288        if (ensureVerifyAppsEnabled) {
14289            return true;
14290        }
14291
14292        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14293                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14294    }
14295
14296    @Override
14297    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14298            throws RemoteException {
14299        mContext.enforceCallingOrSelfPermission(
14300                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14301                "Only intentfilter verification agents can verify applications");
14302
14303        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14304        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14305                Binder.getCallingUid(), verificationCode, failedDomains);
14306        msg.arg1 = id;
14307        msg.obj = response;
14308        mHandler.sendMessage(msg);
14309    }
14310
14311    @Override
14312    public int getIntentVerificationStatus(String packageName, int userId) {
14313        final int callingUid = Binder.getCallingUid();
14314        if (UserHandle.getUserId(callingUid) != userId) {
14315            mContext.enforceCallingOrSelfPermission(
14316                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14317                    "getIntentVerificationStatus" + userId);
14318        }
14319        if (getInstantAppPackageName(callingUid) != null) {
14320            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14321        }
14322        synchronized (mPackages) {
14323            final PackageSetting ps = mSettings.mPackages.get(packageName);
14324            if (ps == null
14325                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14326                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14327            }
14328            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14329        }
14330    }
14331
14332    @Override
14333    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14334        mContext.enforceCallingOrSelfPermission(
14335                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14336
14337        boolean result = false;
14338        synchronized (mPackages) {
14339            final PackageSetting ps = mSettings.mPackages.get(packageName);
14340            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14341                return false;
14342            }
14343            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14344        }
14345        if (result) {
14346            scheduleWritePackageRestrictionsLocked(userId);
14347        }
14348        return result;
14349    }
14350
14351    @Override
14352    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14353            String packageName) {
14354        final int callingUid = Binder.getCallingUid();
14355        if (getInstantAppPackageName(callingUid) != null) {
14356            return ParceledListSlice.emptyList();
14357        }
14358        synchronized (mPackages) {
14359            final PackageSetting ps = mSettings.mPackages.get(packageName);
14360            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14361                return ParceledListSlice.emptyList();
14362            }
14363            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14364        }
14365    }
14366
14367    @Override
14368    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14369        if (TextUtils.isEmpty(packageName)) {
14370            return ParceledListSlice.emptyList();
14371        }
14372        final int callingUid = Binder.getCallingUid();
14373        final int callingUserId = UserHandle.getUserId(callingUid);
14374        synchronized (mPackages) {
14375            PackageParser.Package pkg = mPackages.get(packageName);
14376            if (pkg == null || pkg.activities == null) {
14377                return ParceledListSlice.emptyList();
14378            }
14379            if (pkg.mExtras == null) {
14380                return ParceledListSlice.emptyList();
14381            }
14382            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14383            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14384                return ParceledListSlice.emptyList();
14385            }
14386            final int count = pkg.activities.size();
14387            ArrayList<IntentFilter> result = new ArrayList<>();
14388            for (int n=0; n<count; n++) {
14389                PackageParser.Activity activity = pkg.activities.get(n);
14390                if (activity.intents != null && activity.intents.size() > 0) {
14391                    result.addAll(activity.intents);
14392                }
14393            }
14394            return new ParceledListSlice<>(result);
14395        }
14396    }
14397
14398    @Override
14399    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14400        mContext.enforceCallingOrSelfPermission(
14401                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14402        if (UserHandle.getCallingUserId() != userId) {
14403            mContext.enforceCallingOrSelfPermission(
14404                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14405        }
14406
14407        synchronized (mPackages) {
14408            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14409            if (packageName != null) {
14410                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14411                        packageName, userId);
14412            }
14413            return result;
14414        }
14415    }
14416
14417    @Override
14418    public String getDefaultBrowserPackageName(int userId) {
14419        if (UserHandle.getCallingUserId() != userId) {
14420            mContext.enforceCallingOrSelfPermission(
14421                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14422        }
14423        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14424            return null;
14425        }
14426        synchronized (mPackages) {
14427            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14428        }
14429    }
14430
14431    /**
14432     * Get the "allow unknown sources" setting.
14433     *
14434     * @return the current "allow unknown sources" setting
14435     */
14436    private int getUnknownSourcesSettings() {
14437        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14438                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14439                -1);
14440    }
14441
14442    @Override
14443    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14444        final int callingUid = Binder.getCallingUid();
14445        if (getInstantAppPackageName(callingUid) != null) {
14446            return;
14447        }
14448        // writer
14449        synchronized (mPackages) {
14450            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14451            if (targetPackageSetting == null
14452                    || filterAppAccessLPr(
14453                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14454                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14455            }
14456
14457            PackageSetting installerPackageSetting;
14458            if (installerPackageName != null) {
14459                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14460                if (installerPackageSetting == null) {
14461                    throw new IllegalArgumentException("Unknown installer package: "
14462                            + installerPackageName);
14463                }
14464            } else {
14465                installerPackageSetting = null;
14466            }
14467
14468            Signature[] callerSignature;
14469            Object obj = mSettings.getUserIdLPr(callingUid);
14470            if (obj != null) {
14471                if (obj instanceof SharedUserSetting) {
14472                    callerSignature =
14473                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14474                } else if (obj instanceof PackageSetting) {
14475                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14476                } else {
14477                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14478                }
14479            } else {
14480                throw new SecurityException("Unknown calling UID: " + callingUid);
14481            }
14482
14483            // Verify: can't set installerPackageName to a package that is
14484            // not signed with the same cert as the caller.
14485            if (installerPackageSetting != null) {
14486                if (compareSignatures(callerSignature,
14487                        installerPackageSetting.signatures.mSigningDetails.signatures)
14488                        != PackageManager.SIGNATURE_MATCH) {
14489                    throw new SecurityException(
14490                            "Caller does not have same cert as new installer package "
14491                            + installerPackageName);
14492                }
14493            }
14494
14495            // Verify: if target already has an installer package, it must
14496            // be signed with the same cert as the caller.
14497            if (targetPackageSetting.installerPackageName != null) {
14498                PackageSetting setting = mSettings.mPackages.get(
14499                        targetPackageSetting.installerPackageName);
14500                // If the currently set package isn't valid, then it's always
14501                // okay to change it.
14502                if (setting != null) {
14503                    if (compareSignatures(callerSignature,
14504                            setting.signatures.mSigningDetails.signatures)
14505                            != PackageManager.SIGNATURE_MATCH) {
14506                        throw new SecurityException(
14507                                "Caller does not have same cert as old installer package "
14508                                + targetPackageSetting.installerPackageName);
14509                    }
14510                }
14511            }
14512
14513            // Okay!
14514            targetPackageSetting.installerPackageName = installerPackageName;
14515            if (installerPackageName != null) {
14516                mSettings.mInstallerPackages.add(installerPackageName);
14517            }
14518            scheduleWriteSettingsLocked();
14519        }
14520    }
14521
14522    @Override
14523    public void setApplicationCategoryHint(String packageName, int categoryHint,
14524            String callerPackageName) {
14525        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14526            throw new SecurityException("Instant applications don't have access to this method");
14527        }
14528        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14529                callerPackageName);
14530        synchronized (mPackages) {
14531            PackageSetting ps = mSettings.mPackages.get(packageName);
14532            if (ps == null) {
14533                throw new IllegalArgumentException("Unknown target package " + packageName);
14534            }
14535            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14536                throw new IllegalArgumentException("Unknown target package " + packageName);
14537            }
14538            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14539                throw new IllegalArgumentException("Calling package " + callerPackageName
14540                        + " is not installer for " + packageName);
14541            }
14542
14543            if (ps.categoryHint != categoryHint) {
14544                ps.categoryHint = categoryHint;
14545                scheduleWriteSettingsLocked();
14546            }
14547        }
14548    }
14549
14550    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14551        // Queue up an async operation since the package installation may take a little while.
14552        mHandler.post(new Runnable() {
14553            public void run() {
14554                mHandler.removeCallbacks(this);
14555                 // Result object to be returned
14556                PackageInstalledInfo res = new PackageInstalledInfo();
14557                res.setReturnCode(currentStatus);
14558                res.uid = -1;
14559                res.pkg = null;
14560                res.removedInfo = null;
14561                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14562                    args.doPreInstall(res.returnCode);
14563                    synchronized (mInstallLock) {
14564                        installPackageTracedLI(args, res);
14565                    }
14566                    args.doPostInstall(res.returnCode, res.uid);
14567                }
14568
14569                // A restore should be performed at this point if (a) the install
14570                // succeeded, (b) the operation is not an update, and (c) the new
14571                // package has not opted out of backup participation.
14572                final boolean update = res.removedInfo != null
14573                        && res.removedInfo.removedPackage != null;
14574                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14575                boolean doRestore = !update
14576                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14577
14578                // Set up the post-install work request bookkeeping.  This will be used
14579                // and cleaned up by the post-install event handling regardless of whether
14580                // there's a restore pass performed.  Token values are >= 1.
14581                int token;
14582                if (mNextInstallToken < 0) mNextInstallToken = 1;
14583                token = mNextInstallToken++;
14584
14585                PostInstallData data = new PostInstallData(args, res);
14586                mRunningInstalls.put(token, data);
14587                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14588
14589                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14590                    // Pass responsibility to the Backup Manager.  It will perform a
14591                    // restore if appropriate, then pass responsibility back to the
14592                    // Package Manager to run the post-install observer callbacks
14593                    // and broadcasts.
14594                    IBackupManager bm = IBackupManager.Stub.asInterface(
14595                            ServiceManager.getService(Context.BACKUP_SERVICE));
14596                    if (bm != null) {
14597                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14598                                + " to BM for possible restore");
14599                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14600                        try {
14601                            // TODO: http://b/22388012
14602                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14603                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14604                            } else {
14605                                doRestore = false;
14606                            }
14607                        } catch (RemoteException e) {
14608                            // can't happen; the backup manager is local
14609                        } catch (Exception e) {
14610                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14611                            doRestore = false;
14612                        }
14613                    } else {
14614                        Slog.e(TAG, "Backup Manager not found!");
14615                        doRestore = false;
14616                    }
14617                }
14618
14619                if (!doRestore) {
14620                    // No restore possible, or the Backup Manager was mysteriously not
14621                    // available -- just fire the post-install work request directly.
14622                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14623
14624                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14625
14626                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14627                    mHandler.sendMessage(msg);
14628                }
14629            }
14630        });
14631    }
14632
14633    /**
14634     * Callback from PackageSettings whenever an app is first transitioned out of the
14635     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14636     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14637     * here whether the app is the target of an ongoing install, and only send the
14638     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14639     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14640     * handling.
14641     */
14642    void notifyFirstLaunch(final String packageName, final String installerPackage,
14643            final int userId) {
14644        // Serialize this with the rest of the install-process message chain.  In the
14645        // restore-at-install case, this Runnable will necessarily run before the
14646        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14647        // are coherent.  In the non-restore case, the app has already completed install
14648        // and been launched through some other means, so it is not in a problematic
14649        // state for observers to see the FIRST_LAUNCH signal.
14650        mHandler.post(new Runnable() {
14651            @Override
14652            public void run() {
14653                for (int i = 0; i < mRunningInstalls.size(); i++) {
14654                    final PostInstallData data = mRunningInstalls.valueAt(i);
14655                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14656                        continue;
14657                    }
14658                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14659                        // right package; but is it for the right user?
14660                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14661                            if (userId == data.res.newUsers[uIndex]) {
14662                                if (DEBUG_BACKUP) {
14663                                    Slog.i(TAG, "Package " + packageName
14664                                            + " being restored so deferring FIRST_LAUNCH");
14665                                }
14666                                return;
14667                            }
14668                        }
14669                    }
14670                }
14671                // didn't find it, so not being restored
14672                if (DEBUG_BACKUP) {
14673                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14674                }
14675                final boolean isInstantApp = isInstantApp(packageName, userId);
14676                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14677                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14678                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14679            }
14680        });
14681    }
14682
14683    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14684            int[] userIds, int[] instantUserIds) {
14685        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14686                installerPkg, null, userIds, instantUserIds);
14687    }
14688
14689    private abstract class HandlerParams {
14690        private static final int MAX_RETRIES = 4;
14691
14692        /**
14693         * Number of times startCopy() has been attempted and had a non-fatal
14694         * error.
14695         */
14696        private int mRetries = 0;
14697
14698        /** User handle for the user requesting the information or installation. */
14699        private final UserHandle mUser;
14700        String traceMethod;
14701        int traceCookie;
14702
14703        HandlerParams(UserHandle user) {
14704            mUser = user;
14705        }
14706
14707        UserHandle getUser() {
14708            return mUser;
14709        }
14710
14711        HandlerParams setTraceMethod(String traceMethod) {
14712            this.traceMethod = traceMethod;
14713            return this;
14714        }
14715
14716        HandlerParams setTraceCookie(int traceCookie) {
14717            this.traceCookie = traceCookie;
14718            return this;
14719        }
14720
14721        final boolean startCopy() {
14722            boolean res;
14723            try {
14724                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14725
14726                if (++mRetries > MAX_RETRIES) {
14727                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14728                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14729                    handleServiceError();
14730                    return false;
14731                } else {
14732                    handleStartCopy();
14733                    res = true;
14734                }
14735            } catch (RemoteException e) {
14736                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14737                mHandler.sendEmptyMessage(MCS_RECONNECT);
14738                res = false;
14739            }
14740            handleReturnCode();
14741            return res;
14742        }
14743
14744        final void serviceError() {
14745            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14746            handleServiceError();
14747            handleReturnCode();
14748        }
14749
14750        abstract void handleStartCopy() throws RemoteException;
14751        abstract void handleServiceError();
14752        abstract void handleReturnCode();
14753    }
14754
14755    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14756        for (File path : paths) {
14757            try {
14758                mcs.clearDirectory(path.getAbsolutePath());
14759            } catch (RemoteException e) {
14760            }
14761        }
14762    }
14763
14764    static class OriginInfo {
14765        /**
14766         * Location where install is coming from, before it has been
14767         * copied/renamed into place. This could be a single monolithic APK
14768         * file, or a cluster directory. This location may be untrusted.
14769         */
14770        final File file;
14771
14772        /**
14773         * Flag indicating that {@link #file} or {@link #cid} has already been
14774         * staged, meaning downstream users don't need to defensively copy the
14775         * contents.
14776         */
14777        final boolean staged;
14778
14779        /**
14780         * Flag indicating that {@link #file} or {@link #cid} is an already
14781         * installed app that is being moved.
14782         */
14783        final boolean existing;
14784
14785        final String resolvedPath;
14786        final File resolvedFile;
14787
14788        static OriginInfo fromNothing() {
14789            return new OriginInfo(null, false, false);
14790        }
14791
14792        static OriginInfo fromUntrustedFile(File file) {
14793            return new OriginInfo(file, false, false);
14794        }
14795
14796        static OriginInfo fromExistingFile(File file) {
14797            return new OriginInfo(file, false, true);
14798        }
14799
14800        static OriginInfo fromStagedFile(File file) {
14801            return new OriginInfo(file, true, false);
14802        }
14803
14804        private OriginInfo(File file, boolean staged, boolean existing) {
14805            this.file = file;
14806            this.staged = staged;
14807            this.existing = existing;
14808
14809            if (file != null) {
14810                resolvedPath = file.getAbsolutePath();
14811                resolvedFile = file;
14812            } else {
14813                resolvedPath = null;
14814                resolvedFile = null;
14815            }
14816        }
14817    }
14818
14819    static class MoveInfo {
14820        final int moveId;
14821        final String fromUuid;
14822        final String toUuid;
14823        final String packageName;
14824        final String dataAppName;
14825        final int appId;
14826        final String seinfo;
14827        final int targetSdkVersion;
14828
14829        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14830                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14831            this.moveId = moveId;
14832            this.fromUuid = fromUuid;
14833            this.toUuid = toUuid;
14834            this.packageName = packageName;
14835            this.dataAppName = dataAppName;
14836            this.appId = appId;
14837            this.seinfo = seinfo;
14838            this.targetSdkVersion = targetSdkVersion;
14839        }
14840    }
14841
14842    static class VerificationInfo {
14843        /** A constant used to indicate that a uid value is not present. */
14844        public static final int NO_UID = -1;
14845
14846        /** URI referencing where the package was downloaded from. */
14847        final Uri originatingUri;
14848
14849        /** HTTP referrer URI associated with the originatingURI. */
14850        final Uri referrer;
14851
14852        /** UID of the application that the install request originated from. */
14853        final int originatingUid;
14854
14855        /** UID of application requesting the install */
14856        final int installerUid;
14857
14858        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14859            this.originatingUri = originatingUri;
14860            this.referrer = referrer;
14861            this.originatingUid = originatingUid;
14862            this.installerUid = installerUid;
14863        }
14864    }
14865
14866    class InstallParams extends HandlerParams {
14867        final OriginInfo origin;
14868        final MoveInfo move;
14869        final IPackageInstallObserver2 observer;
14870        int installFlags;
14871        final String installerPackageName;
14872        final String volumeUuid;
14873        private InstallArgs mArgs;
14874        private int mRet;
14875        final String packageAbiOverride;
14876        final String[] grantedRuntimePermissions;
14877        final VerificationInfo verificationInfo;
14878        final PackageParser.SigningDetails signingDetails;
14879        final int installReason;
14880
14881        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14882                int installFlags, String installerPackageName, String volumeUuid,
14883                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14884                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
14885            super(user);
14886            this.origin = origin;
14887            this.move = move;
14888            this.observer = observer;
14889            this.installFlags = installFlags;
14890            this.installerPackageName = installerPackageName;
14891            this.volumeUuid = volumeUuid;
14892            this.verificationInfo = verificationInfo;
14893            this.packageAbiOverride = packageAbiOverride;
14894            this.grantedRuntimePermissions = grantedPermissions;
14895            this.signingDetails = signingDetails;
14896            this.installReason = installReason;
14897        }
14898
14899        @Override
14900        public String toString() {
14901            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14902                    + " file=" + origin.file + "}";
14903        }
14904
14905        private int installLocationPolicy(PackageInfoLite pkgLite) {
14906            String packageName = pkgLite.packageName;
14907            int installLocation = pkgLite.installLocation;
14908            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14909            // reader
14910            synchronized (mPackages) {
14911                // Currently installed package which the new package is attempting to replace or
14912                // null if no such package is installed.
14913                PackageParser.Package installedPkg = mPackages.get(packageName);
14914                // Package which currently owns the data which the new package will own if installed.
14915                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14916                // will be null whereas dataOwnerPkg will contain information about the package
14917                // which was uninstalled while keeping its data.
14918                PackageParser.Package dataOwnerPkg = installedPkg;
14919                if (dataOwnerPkg  == null) {
14920                    PackageSetting ps = mSettings.mPackages.get(packageName);
14921                    if (ps != null) {
14922                        dataOwnerPkg = ps.pkg;
14923                    }
14924                }
14925
14926                if (dataOwnerPkg != null) {
14927                    // If installed, the package will get access to data left on the device by its
14928                    // predecessor. As a security measure, this is permited only if this is not a
14929                    // version downgrade or if the predecessor package is marked as debuggable and
14930                    // a downgrade is explicitly requested.
14931                    //
14932                    // On debuggable platform builds, downgrades are permitted even for
14933                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14934                    // not offer security guarantees and thus it's OK to disable some security
14935                    // mechanisms to make debugging/testing easier on those builds. However, even on
14936                    // debuggable builds downgrades of packages are permitted only if requested via
14937                    // installFlags. This is because we aim to keep the behavior of debuggable
14938                    // platform builds as close as possible to the behavior of non-debuggable
14939                    // platform builds.
14940                    final boolean downgradeRequested =
14941                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14942                    final boolean packageDebuggable =
14943                                (dataOwnerPkg.applicationInfo.flags
14944                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14945                    final boolean downgradePermitted =
14946                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14947                    if (!downgradePermitted) {
14948                        try {
14949                            checkDowngrade(dataOwnerPkg, pkgLite);
14950                        } catch (PackageManagerException e) {
14951                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14952                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14953                        }
14954                    }
14955                }
14956
14957                if (installedPkg != null) {
14958                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14959                        // Check for updated system application.
14960                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14961                            if (onSd) {
14962                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14963                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14964                            }
14965                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14966                        } else {
14967                            if (onSd) {
14968                                // Install flag overrides everything.
14969                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14970                            }
14971                            // If current upgrade specifies particular preference
14972                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14973                                // Application explicitly specified internal.
14974                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14975                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14976                                // App explictly prefers external. Let policy decide
14977                            } else {
14978                                // Prefer previous location
14979                                if (isExternal(installedPkg)) {
14980                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14981                                }
14982                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14983                            }
14984                        }
14985                    } else {
14986                        // Invalid install. Return error code
14987                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14988                    }
14989                }
14990            }
14991            // All the special cases have been taken care of.
14992            // Return result based on recommended install location.
14993            if (onSd) {
14994                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14995            }
14996            return pkgLite.recommendedInstallLocation;
14997        }
14998
14999        /*
15000         * Invoke remote method to get package information and install
15001         * location values. Override install location based on default
15002         * policy if needed and then create install arguments based
15003         * on the install location.
15004         */
15005        public void handleStartCopy() throws RemoteException {
15006            int ret = PackageManager.INSTALL_SUCCEEDED;
15007
15008            // If we're already staged, we've firmly committed to an install location
15009            if (origin.staged) {
15010                if (origin.file != null) {
15011                    installFlags |= PackageManager.INSTALL_INTERNAL;
15012                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15013                } else {
15014                    throw new IllegalStateException("Invalid stage location");
15015                }
15016            }
15017
15018            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15019            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15020            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15021            PackageInfoLite pkgLite = null;
15022
15023            if (onInt && onSd) {
15024                // Check if both bits are set.
15025                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15026                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15027            } else if (onSd && ephemeral) {
15028                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15029                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15030            } else {
15031                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15032                        packageAbiOverride);
15033
15034                if (DEBUG_INSTANT && ephemeral) {
15035                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15036                }
15037
15038                /*
15039                 * If we have too little free space, try to free cache
15040                 * before giving up.
15041                 */
15042                if (!origin.staged && pkgLite.recommendedInstallLocation
15043                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15044                    // TODO: focus freeing disk space on the target device
15045                    final StorageManager storage = StorageManager.from(mContext);
15046                    final long lowThreshold = storage.getStorageLowBytes(
15047                            Environment.getDataDirectory());
15048
15049                    final long sizeBytes = mContainerService.calculateInstalledSize(
15050                            origin.resolvedPath, packageAbiOverride);
15051
15052                    try {
15053                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15054                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15055                                installFlags, packageAbiOverride);
15056                    } catch (InstallerException e) {
15057                        Slog.w(TAG, "Failed to free cache", e);
15058                    }
15059
15060                    /*
15061                     * The cache free must have deleted the file we
15062                     * downloaded to install.
15063                     *
15064                     * TODO: fix the "freeCache" call to not delete
15065                     *       the file we care about.
15066                     */
15067                    if (pkgLite.recommendedInstallLocation
15068                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15069                        pkgLite.recommendedInstallLocation
15070                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15071                    }
15072                }
15073            }
15074
15075            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15076                int loc = pkgLite.recommendedInstallLocation;
15077                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15078                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15079                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15080                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15081                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15082                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15083                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15084                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15085                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15086                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15087                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15088                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15089                } else {
15090                    // Override with defaults if needed.
15091                    loc = installLocationPolicy(pkgLite);
15092                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15093                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15094                    } else if (!onSd && !onInt) {
15095                        // Override install location with flags
15096                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15097                            // Set the flag to install on external media.
15098                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15099                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15100                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15101                            if (DEBUG_INSTANT) {
15102                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15103                            }
15104                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15105                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15106                                    |PackageManager.INSTALL_INTERNAL);
15107                        } else {
15108                            // Make sure the flag for installing on external
15109                            // media is unset
15110                            installFlags |= PackageManager.INSTALL_INTERNAL;
15111                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15112                        }
15113                    }
15114                }
15115            }
15116
15117            final InstallArgs args = createInstallArgs(this);
15118            mArgs = args;
15119
15120            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15121                // TODO: http://b/22976637
15122                // Apps installed for "all" users use the device owner to verify the app
15123                UserHandle verifierUser = getUser();
15124                if (verifierUser == UserHandle.ALL) {
15125                    verifierUser = UserHandle.SYSTEM;
15126                }
15127
15128                /*
15129                 * Determine if we have any installed package verifiers. If we
15130                 * do, then we'll defer to them to verify the packages.
15131                 */
15132                final int requiredUid = mRequiredVerifierPackage == null ? -1
15133                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15134                                verifierUser.getIdentifier());
15135                final int installerUid =
15136                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15137                if (!origin.existing && requiredUid != -1
15138                        && isVerificationEnabled(
15139                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15140                    final Intent verification = new Intent(
15141                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15142                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15143                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15144                            PACKAGE_MIME_TYPE);
15145                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15146
15147                    // Query all live verifiers based on current user state
15148                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15149                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15150                            false /*allowDynamicSplits*/);
15151
15152                    if (DEBUG_VERIFY) {
15153                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15154                                + verification.toString() + " with " + pkgLite.verifiers.length
15155                                + " optional verifiers");
15156                    }
15157
15158                    final int verificationId = mPendingVerificationToken++;
15159
15160                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15161
15162                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15163                            installerPackageName);
15164
15165                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15166                            installFlags);
15167
15168                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15169                            pkgLite.packageName);
15170
15171                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15172                            pkgLite.versionCode);
15173
15174                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15175                            pkgLite.getLongVersionCode());
15176
15177                    if (verificationInfo != null) {
15178                        if (verificationInfo.originatingUri != null) {
15179                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15180                                    verificationInfo.originatingUri);
15181                        }
15182                        if (verificationInfo.referrer != null) {
15183                            verification.putExtra(Intent.EXTRA_REFERRER,
15184                                    verificationInfo.referrer);
15185                        }
15186                        if (verificationInfo.originatingUid >= 0) {
15187                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15188                                    verificationInfo.originatingUid);
15189                        }
15190                        if (verificationInfo.installerUid >= 0) {
15191                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15192                                    verificationInfo.installerUid);
15193                        }
15194                    }
15195
15196                    final PackageVerificationState verificationState = new PackageVerificationState(
15197                            requiredUid, args);
15198
15199                    mPendingVerification.append(verificationId, verificationState);
15200
15201                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15202                            receivers, verificationState);
15203
15204                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15205                    final long idleDuration = getVerificationTimeout();
15206
15207                    /*
15208                     * If any sufficient verifiers were listed in the package
15209                     * manifest, attempt to ask them.
15210                     */
15211                    if (sufficientVerifiers != null) {
15212                        final int N = sufficientVerifiers.size();
15213                        if (N == 0) {
15214                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15215                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15216                        } else {
15217                            for (int i = 0; i < N; i++) {
15218                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15219                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15220                                        verifierComponent.getPackageName(), idleDuration,
15221                                        verifierUser.getIdentifier(), false, "package verifier");
15222
15223                                final Intent sufficientIntent = new Intent(verification);
15224                                sufficientIntent.setComponent(verifierComponent);
15225                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15226                            }
15227                        }
15228                    }
15229
15230                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15231                            mRequiredVerifierPackage, receivers);
15232                    if (ret == PackageManager.INSTALL_SUCCEEDED
15233                            && mRequiredVerifierPackage != null) {
15234                        Trace.asyncTraceBegin(
15235                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15236                        /*
15237                         * Send the intent to the required verification agent,
15238                         * but only start the verification timeout after the
15239                         * target BroadcastReceivers have run.
15240                         */
15241                        verification.setComponent(requiredVerifierComponent);
15242                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15243                                mRequiredVerifierPackage, idleDuration,
15244                                verifierUser.getIdentifier(), false, "package verifier");
15245                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15246                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15247                                new BroadcastReceiver() {
15248                                    @Override
15249                                    public void onReceive(Context context, Intent intent) {
15250                                        final Message msg = mHandler
15251                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15252                                        msg.arg1 = verificationId;
15253                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15254                                    }
15255                                }, null, 0, null, null);
15256
15257                        /*
15258                         * We don't want the copy to proceed until verification
15259                         * succeeds, so null out this field.
15260                         */
15261                        mArgs = null;
15262                    }
15263                } else {
15264                    /*
15265                     * No package verification is enabled, so immediately start
15266                     * the remote call to initiate copy using temporary file.
15267                     */
15268                    ret = args.copyApk(mContainerService, true);
15269                }
15270            }
15271
15272            mRet = ret;
15273        }
15274
15275        @Override
15276        void handleReturnCode() {
15277            // If mArgs is null, then MCS couldn't be reached. When it
15278            // reconnects, it will try again to install. At that point, this
15279            // will succeed.
15280            if (mArgs != null) {
15281                processPendingInstall(mArgs, mRet);
15282            }
15283        }
15284
15285        @Override
15286        void handleServiceError() {
15287            mArgs = createInstallArgs(this);
15288            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15289        }
15290    }
15291
15292    private InstallArgs createInstallArgs(InstallParams params) {
15293        if (params.move != null) {
15294            return new MoveInstallArgs(params);
15295        } else {
15296            return new FileInstallArgs(params);
15297        }
15298    }
15299
15300    /**
15301     * Create args that describe an existing installed package. Typically used
15302     * when cleaning up old installs, or used as a move source.
15303     */
15304    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15305            String resourcePath, String[] instructionSets) {
15306        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15307    }
15308
15309    static abstract class InstallArgs {
15310        /** @see InstallParams#origin */
15311        final OriginInfo origin;
15312        /** @see InstallParams#move */
15313        final MoveInfo move;
15314
15315        final IPackageInstallObserver2 observer;
15316        // Always refers to PackageManager flags only
15317        final int installFlags;
15318        final String installerPackageName;
15319        final String volumeUuid;
15320        final UserHandle user;
15321        final String abiOverride;
15322        final String[] installGrantPermissions;
15323        /** If non-null, drop an async trace when the install completes */
15324        final String traceMethod;
15325        final int traceCookie;
15326        final PackageParser.SigningDetails signingDetails;
15327        final int installReason;
15328
15329        // The list of instruction sets supported by this app. This is currently
15330        // only used during the rmdex() phase to clean up resources. We can get rid of this
15331        // if we move dex files under the common app path.
15332        /* nullable */ String[] instructionSets;
15333
15334        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15335                int installFlags, String installerPackageName, String volumeUuid,
15336                UserHandle user, String[] instructionSets,
15337                String abiOverride, String[] installGrantPermissions,
15338                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15339                int installReason) {
15340            this.origin = origin;
15341            this.move = move;
15342            this.installFlags = installFlags;
15343            this.observer = observer;
15344            this.installerPackageName = installerPackageName;
15345            this.volumeUuid = volumeUuid;
15346            this.user = user;
15347            this.instructionSets = instructionSets;
15348            this.abiOverride = abiOverride;
15349            this.installGrantPermissions = installGrantPermissions;
15350            this.traceMethod = traceMethod;
15351            this.traceCookie = traceCookie;
15352            this.signingDetails = signingDetails;
15353            this.installReason = installReason;
15354        }
15355
15356        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15357        abstract int doPreInstall(int status);
15358
15359        /**
15360         * Rename package into final resting place. All paths on the given
15361         * scanned package should be updated to reflect the rename.
15362         */
15363        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15364        abstract int doPostInstall(int status, int uid);
15365
15366        /** @see PackageSettingBase#codePathString */
15367        abstract String getCodePath();
15368        /** @see PackageSettingBase#resourcePathString */
15369        abstract String getResourcePath();
15370
15371        // Need installer lock especially for dex file removal.
15372        abstract void cleanUpResourcesLI();
15373        abstract boolean doPostDeleteLI(boolean delete);
15374
15375        /**
15376         * Called before the source arguments are copied. This is used mostly
15377         * for MoveParams when it needs to read the source file to put it in the
15378         * destination.
15379         */
15380        int doPreCopy() {
15381            return PackageManager.INSTALL_SUCCEEDED;
15382        }
15383
15384        /**
15385         * Called after the source arguments are copied. This is used mostly for
15386         * MoveParams when it needs to read the source file to put it in the
15387         * destination.
15388         */
15389        int doPostCopy(int uid) {
15390            return PackageManager.INSTALL_SUCCEEDED;
15391        }
15392
15393        protected boolean isFwdLocked() {
15394            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15395        }
15396
15397        protected boolean isExternalAsec() {
15398            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15399        }
15400
15401        protected boolean isEphemeral() {
15402            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15403        }
15404
15405        UserHandle getUser() {
15406            return user;
15407        }
15408    }
15409
15410    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15411        if (!allCodePaths.isEmpty()) {
15412            if (instructionSets == null) {
15413                throw new IllegalStateException("instructionSet == null");
15414            }
15415            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15416            for (String codePath : allCodePaths) {
15417                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15418                    try {
15419                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15420                    } catch (InstallerException ignored) {
15421                    }
15422                }
15423            }
15424        }
15425    }
15426
15427    /**
15428     * Logic to handle installation of non-ASEC applications, including copying
15429     * and renaming logic.
15430     */
15431    class FileInstallArgs extends InstallArgs {
15432        private File codeFile;
15433        private File resourceFile;
15434
15435        // Example topology:
15436        // /data/app/com.example/base.apk
15437        // /data/app/com.example/split_foo.apk
15438        // /data/app/com.example/lib/arm/libfoo.so
15439        // /data/app/com.example/lib/arm64/libfoo.so
15440        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15441
15442        /** New install */
15443        FileInstallArgs(InstallParams params) {
15444            super(params.origin, params.move, params.observer, params.installFlags,
15445                    params.installerPackageName, params.volumeUuid,
15446                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15447                    params.grantedRuntimePermissions,
15448                    params.traceMethod, params.traceCookie, params.signingDetails,
15449                    params.installReason);
15450            if (isFwdLocked()) {
15451                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15452            }
15453        }
15454
15455        /** Existing install */
15456        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15457            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15458                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15459                    PackageManager.INSTALL_REASON_UNKNOWN);
15460            this.codeFile = (codePath != null) ? new File(codePath) : null;
15461            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15462        }
15463
15464        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15465            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15466            try {
15467                return doCopyApk(imcs, temp);
15468            } finally {
15469                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15470            }
15471        }
15472
15473        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15474            if (origin.staged) {
15475                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15476                codeFile = origin.file;
15477                resourceFile = origin.file;
15478                return PackageManager.INSTALL_SUCCEEDED;
15479            }
15480
15481            try {
15482                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15483                final File tempDir =
15484                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15485                codeFile = tempDir;
15486                resourceFile = tempDir;
15487            } catch (IOException e) {
15488                Slog.w(TAG, "Failed to create copy file: " + e);
15489                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15490            }
15491
15492            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15493                @Override
15494                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15495                    if (!FileUtils.isValidExtFilename(name)) {
15496                        throw new IllegalArgumentException("Invalid filename: " + name);
15497                    }
15498                    try {
15499                        final File file = new File(codeFile, name);
15500                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15501                                O_RDWR | O_CREAT, 0644);
15502                        Os.chmod(file.getAbsolutePath(), 0644);
15503                        return new ParcelFileDescriptor(fd);
15504                    } catch (ErrnoException e) {
15505                        throw new RemoteException("Failed to open: " + e.getMessage());
15506                    }
15507                }
15508            };
15509
15510            int ret = PackageManager.INSTALL_SUCCEEDED;
15511            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15512            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15513                Slog.e(TAG, "Failed to copy package");
15514                return ret;
15515            }
15516
15517            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15518            NativeLibraryHelper.Handle handle = null;
15519            try {
15520                handle = NativeLibraryHelper.Handle.create(codeFile);
15521                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15522                        abiOverride);
15523            } catch (IOException e) {
15524                Slog.e(TAG, "Copying native libraries failed", e);
15525                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15526            } finally {
15527                IoUtils.closeQuietly(handle);
15528            }
15529
15530            return ret;
15531        }
15532
15533        int doPreInstall(int status) {
15534            if (status != PackageManager.INSTALL_SUCCEEDED) {
15535                cleanUp();
15536            }
15537            return status;
15538        }
15539
15540        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15541            if (status != PackageManager.INSTALL_SUCCEEDED) {
15542                cleanUp();
15543                return false;
15544            }
15545
15546            final File targetDir = codeFile.getParentFile();
15547            final File beforeCodeFile = codeFile;
15548            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15549
15550            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15551            try {
15552                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15553            } catch (ErrnoException e) {
15554                Slog.w(TAG, "Failed to rename", e);
15555                return false;
15556            }
15557
15558            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15559                Slog.w(TAG, "Failed to restorecon");
15560                return false;
15561            }
15562
15563            // Reflect the rename internally
15564            codeFile = afterCodeFile;
15565            resourceFile = afterCodeFile;
15566
15567            // Reflect the rename in scanned details
15568            try {
15569                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15570            } catch (IOException e) {
15571                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15572                return false;
15573            }
15574            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15575                    afterCodeFile, pkg.baseCodePath));
15576            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15577                    afterCodeFile, pkg.splitCodePaths));
15578
15579            // Reflect the rename in app info
15580            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15581            pkg.setApplicationInfoCodePath(pkg.codePath);
15582            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15583            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15584            pkg.setApplicationInfoResourcePath(pkg.codePath);
15585            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15586            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15587
15588            return true;
15589        }
15590
15591        int doPostInstall(int status, int uid) {
15592            if (status != PackageManager.INSTALL_SUCCEEDED) {
15593                cleanUp();
15594            }
15595            return status;
15596        }
15597
15598        @Override
15599        String getCodePath() {
15600            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15601        }
15602
15603        @Override
15604        String getResourcePath() {
15605            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15606        }
15607
15608        private boolean cleanUp() {
15609            if (codeFile == null || !codeFile.exists()) {
15610                return false;
15611            }
15612
15613            removeCodePathLI(codeFile);
15614
15615            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15616                resourceFile.delete();
15617            }
15618
15619            return true;
15620        }
15621
15622        void cleanUpResourcesLI() {
15623            // Try enumerating all code paths before deleting
15624            List<String> allCodePaths = Collections.EMPTY_LIST;
15625            if (codeFile != null && codeFile.exists()) {
15626                try {
15627                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15628                    allCodePaths = pkg.getAllCodePaths();
15629                } catch (PackageParserException e) {
15630                    // Ignored; we tried our best
15631                }
15632            }
15633
15634            cleanUp();
15635            removeDexFiles(allCodePaths, instructionSets);
15636        }
15637
15638        boolean doPostDeleteLI(boolean delete) {
15639            // XXX err, shouldn't we respect the delete flag?
15640            cleanUpResourcesLI();
15641            return true;
15642        }
15643    }
15644
15645    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15646            PackageManagerException {
15647        if (copyRet < 0) {
15648            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15649                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15650                throw new PackageManagerException(copyRet, message);
15651            }
15652        }
15653    }
15654
15655    /**
15656     * Extract the StorageManagerService "container ID" from the full code path of an
15657     * .apk.
15658     */
15659    static String cidFromCodePath(String fullCodePath) {
15660        int eidx = fullCodePath.lastIndexOf("/");
15661        String subStr1 = fullCodePath.substring(0, eidx);
15662        int sidx = subStr1.lastIndexOf("/");
15663        return subStr1.substring(sidx+1, eidx);
15664    }
15665
15666    /**
15667     * Logic to handle movement of existing installed applications.
15668     */
15669    class MoveInstallArgs extends InstallArgs {
15670        private File codeFile;
15671        private File resourceFile;
15672
15673        /** New install */
15674        MoveInstallArgs(InstallParams params) {
15675            super(params.origin, params.move, params.observer, params.installFlags,
15676                    params.installerPackageName, params.volumeUuid,
15677                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15678                    params.grantedRuntimePermissions,
15679                    params.traceMethod, params.traceCookie, params.signingDetails,
15680                    params.installReason);
15681        }
15682
15683        int copyApk(IMediaContainerService imcs, boolean temp) {
15684            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15685                    + move.fromUuid + " to " + move.toUuid);
15686            synchronized (mInstaller) {
15687                try {
15688                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15689                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15690                } catch (InstallerException e) {
15691                    Slog.w(TAG, "Failed to move app", e);
15692                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15693                }
15694            }
15695
15696            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15697            resourceFile = codeFile;
15698            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15699
15700            return PackageManager.INSTALL_SUCCEEDED;
15701        }
15702
15703        int doPreInstall(int status) {
15704            if (status != PackageManager.INSTALL_SUCCEEDED) {
15705                cleanUp(move.toUuid);
15706            }
15707            return status;
15708        }
15709
15710        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15711            if (status != PackageManager.INSTALL_SUCCEEDED) {
15712                cleanUp(move.toUuid);
15713                return false;
15714            }
15715
15716            // Reflect the move in app info
15717            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15718            pkg.setApplicationInfoCodePath(pkg.codePath);
15719            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15720            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15721            pkg.setApplicationInfoResourcePath(pkg.codePath);
15722            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15723            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15724
15725            return true;
15726        }
15727
15728        int doPostInstall(int status, int uid) {
15729            if (status == PackageManager.INSTALL_SUCCEEDED) {
15730                cleanUp(move.fromUuid);
15731            } else {
15732                cleanUp(move.toUuid);
15733            }
15734            return status;
15735        }
15736
15737        @Override
15738        String getCodePath() {
15739            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15740        }
15741
15742        @Override
15743        String getResourcePath() {
15744            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15745        }
15746
15747        private boolean cleanUp(String volumeUuid) {
15748            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15749                    move.dataAppName);
15750            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15751            final int[] userIds = sUserManager.getUserIds();
15752            synchronized (mInstallLock) {
15753                // Clean up both app data and code
15754                // All package moves are frozen until finished
15755                for (int userId : userIds) {
15756                    try {
15757                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15758                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15759                    } catch (InstallerException e) {
15760                        Slog.w(TAG, String.valueOf(e));
15761                    }
15762                }
15763                removeCodePathLI(codeFile);
15764            }
15765            return true;
15766        }
15767
15768        void cleanUpResourcesLI() {
15769            throw new UnsupportedOperationException();
15770        }
15771
15772        boolean doPostDeleteLI(boolean delete) {
15773            throw new UnsupportedOperationException();
15774        }
15775    }
15776
15777    static String getAsecPackageName(String packageCid) {
15778        int idx = packageCid.lastIndexOf("-");
15779        if (idx == -1) {
15780            return packageCid;
15781        }
15782        return packageCid.substring(0, idx);
15783    }
15784
15785    // Utility method used to create code paths based on package name and available index.
15786    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15787        String idxStr = "";
15788        int idx = 1;
15789        // Fall back to default value of idx=1 if prefix is not
15790        // part of oldCodePath
15791        if (oldCodePath != null) {
15792            String subStr = oldCodePath;
15793            // Drop the suffix right away
15794            if (suffix != null && subStr.endsWith(suffix)) {
15795                subStr = subStr.substring(0, subStr.length() - suffix.length());
15796            }
15797            // If oldCodePath already contains prefix find out the
15798            // ending index to either increment or decrement.
15799            int sidx = subStr.lastIndexOf(prefix);
15800            if (sidx != -1) {
15801                subStr = subStr.substring(sidx + prefix.length());
15802                if (subStr != null) {
15803                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15804                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15805                    }
15806                    try {
15807                        idx = Integer.parseInt(subStr);
15808                        if (idx <= 1) {
15809                            idx++;
15810                        } else {
15811                            idx--;
15812                        }
15813                    } catch(NumberFormatException e) {
15814                    }
15815                }
15816            }
15817        }
15818        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15819        return prefix + idxStr;
15820    }
15821
15822    private File getNextCodePath(File targetDir, String packageName) {
15823        File result;
15824        SecureRandom random = new SecureRandom();
15825        byte[] bytes = new byte[16];
15826        do {
15827            random.nextBytes(bytes);
15828            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15829            result = new File(targetDir, packageName + "-" + suffix);
15830        } while (result.exists());
15831        return result;
15832    }
15833
15834    // Utility method that returns the relative package path with respect
15835    // to the installation directory. Like say for /data/data/com.test-1.apk
15836    // string com.test-1 is returned.
15837    static String deriveCodePathName(String codePath) {
15838        if (codePath == null) {
15839            return null;
15840        }
15841        final File codeFile = new File(codePath);
15842        final String name = codeFile.getName();
15843        if (codeFile.isDirectory()) {
15844            return name;
15845        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15846            final int lastDot = name.lastIndexOf('.');
15847            return name.substring(0, lastDot);
15848        } else {
15849            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15850            return null;
15851        }
15852    }
15853
15854    static class PackageInstalledInfo {
15855        String name;
15856        int uid;
15857        // The set of users that originally had this package installed.
15858        int[] origUsers;
15859        // The set of users that now have this package installed.
15860        int[] newUsers;
15861        PackageParser.Package pkg;
15862        int returnCode;
15863        String returnMsg;
15864        String installerPackageName;
15865        PackageRemovedInfo removedInfo;
15866        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15867
15868        public void setError(int code, String msg) {
15869            setReturnCode(code);
15870            setReturnMessage(msg);
15871            Slog.w(TAG, msg);
15872        }
15873
15874        public void setError(String msg, PackageParserException e) {
15875            setReturnCode(e.error);
15876            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15877            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15878            for (int i = 0; i < childCount; i++) {
15879                addedChildPackages.valueAt(i).setError(msg, e);
15880            }
15881            Slog.w(TAG, msg, e);
15882        }
15883
15884        public void setError(String msg, PackageManagerException e) {
15885            returnCode = e.error;
15886            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15887            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15888            for (int i = 0; i < childCount; i++) {
15889                addedChildPackages.valueAt(i).setError(msg, e);
15890            }
15891            Slog.w(TAG, msg, e);
15892        }
15893
15894        public void setReturnCode(int returnCode) {
15895            this.returnCode = returnCode;
15896            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15897            for (int i = 0; i < childCount; i++) {
15898                addedChildPackages.valueAt(i).returnCode = returnCode;
15899            }
15900        }
15901
15902        private void setReturnMessage(String returnMsg) {
15903            this.returnMsg = returnMsg;
15904            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15905            for (int i = 0; i < childCount; i++) {
15906                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15907            }
15908        }
15909
15910        // In some error cases we want to convey more info back to the observer
15911        String origPackage;
15912        String origPermission;
15913    }
15914
15915    /*
15916     * Install a non-existing package.
15917     */
15918    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15919            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15920            String volumeUuid, PackageInstalledInfo res, int installReason) {
15921        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15922
15923        // Remember this for later, in case we need to rollback this install
15924        String pkgName = pkg.packageName;
15925
15926        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15927
15928        synchronized(mPackages) {
15929            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15930            if (renamedPackage != null) {
15931                // A package with the same name is already installed, though
15932                // it has been renamed to an older name.  The package we
15933                // are trying to install should be installed as an update to
15934                // the existing one, but that has not been requested, so bail.
15935                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15936                        + " without first uninstalling package running as "
15937                        + renamedPackage);
15938                return;
15939            }
15940            if (mPackages.containsKey(pkgName)) {
15941                // Don't allow installation over an existing package with the same name.
15942                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15943                        + " without first uninstalling.");
15944                return;
15945            }
15946        }
15947
15948        try {
15949            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
15950                    System.currentTimeMillis(), user);
15951
15952            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15953
15954            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15955                prepareAppDataAfterInstallLIF(newPackage);
15956
15957            } else {
15958                // Remove package from internal structures, but keep around any
15959                // data that might have already existed
15960                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15961                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15962            }
15963        } catch (PackageManagerException e) {
15964            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15965        }
15966
15967        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15968    }
15969
15970    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15971        try (DigestInputStream digestStream =
15972                new DigestInputStream(new FileInputStream(file), digest)) {
15973            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15974        }
15975    }
15976
15977    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15978            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15979            PackageInstalledInfo res, int installReason) {
15980        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15981
15982        final PackageParser.Package oldPackage;
15983        final PackageSetting ps;
15984        final String pkgName = pkg.packageName;
15985        final int[] allUsers;
15986        final int[] installedUsers;
15987
15988        synchronized(mPackages) {
15989            oldPackage = mPackages.get(pkgName);
15990            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15991
15992            // don't allow upgrade to target a release SDK from a pre-release SDK
15993            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15994                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15995            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15996                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15997            if (oldTargetsPreRelease
15998                    && !newTargetsPreRelease
15999                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16000                Slog.w(TAG, "Can't install package targeting released sdk");
16001                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16002                return;
16003            }
16004
16005            ps = mSettings.mPackages.get(pkgName);
16006
16007            // verify signatures are valid
16008            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16009            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16010                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16011                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16012                            "New package not signed by keys specified by upgrade-keysets: "
16013                                    + pkgName);
16014                    return;
16015                }
16016            } else {
16017
16018                // default to original signature matching
16019                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16020                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
16021                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16022                            "New package has a different signature: " + pkgName);
16023                    return;
16024                }
16025            }
16026
16027            // don't allow a system upgrade unless the upgrade hash matches
16028            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16029                byte[] digestBytes = null;
16030                try {
16031                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16032                    updateDigest(digest, new File(pkg.baseCodePath));
16033                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16034                        for (String path : pkg.splitCodePaths) {
16035                            updateDigest(digest, new File(path));
16036                        }
16037                    }
16038                    digestBytes = digest.digest();
16039                } catch (NoSuchAlgorithmException | IOException e) {
16040                    res.setError(INSTALL_FAILED_INVALID_APK,
16041                            "Could not compute hash: " + pkgName);
16042                    return;
16043                }
16044                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16045                    res.setError(INSTALL_FAILED_INVALID_APK,
16046                            "New package fails restrict-update check: " + pkgName);
16047                    return;
16048                }
16049                // retain upgrade restriction
16050                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16051            }
16052
16053            // Check for shared user id changes
16054            String invalidPackageName =
16055                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16056            if (invalidPackageName != null) {
16057                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16058                        "Package " + invalidPackageName + " tried to change user "
16059                                + oldPackage.mSharedUserId);
16060                return;
16061            }
16062
16063            // check if the new package supports all of the abis which the old package supports
16064            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16065            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16066            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16067                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16068                        "Update to package " + pkgName + " doesn't support multi arch");
16069                return;
16070            }
16071
16072            // In case of rollback, remember per-user/profile install state
16073            allUsers = sUserManager.getUserIds();
16074            installedUsers = ps.queryInstalledUsers(allUsers, true);
16075
16076            // don't allow an upgrade from full to ephemeral
16077            if (isInstantApp) {
16078                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16079                    for (int currentUser : allUsers) {
16080                        if (!ps.getInstantApp(currentUser)) {
16081                            // can't downgrade from full to instant
16082                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16083                                    + " for user: " + currentUser);
16084                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16085                            return;
16086                        }
16087                    }
16088                } else if (!ps.getInstantApp(user.getIdentifier())) {
16089                    // can't downgrade from full to instant
16090                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16091                            + " for user: " + user.getIdentifier());
16092                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16093                    return;
16094                }
16095            }
16096        }
16097
16098        // Update what is removed
16099        res.removedInfo = new PackageRemovedInfo(this);
16100        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16101        res.removedInfo.removedPackage = oldPackage.packageName;
16102        res.removedInfo.installerPackageName = ps.installerPackageName;
16103        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16104        res.removedInfo.isUpdate = true;
16105        res.removedInfo.origUsers = installedUsers;
16106        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16107        for (int i = 0; i < installedUsers.length; i++) {
16108            final int userId = installedUsers[i];
16109            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16110        }
16111
16112        final int childCount = (oldPackage.childPackages != null)
16113                ? oldPackage.childPackages.size() : 0;
16114        for (int i = 0; i < childCount; i++) {
16115            boolean childPackageUpdated = false;
16116            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16117            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16118            if (res.addedChildPackages != null) {
16119                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16120                if (childRes != null) {
16121                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16122                    childRes.removedInfo.removedPackage = childPkg.packageName;
16123                    if (childPs != null) {
16124                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16125                    }
16126                    childRes.removedInfo.isUpdate = true;
16127                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16128                    childPackageUpdated = true;
16129                }
16130            }
16131            if (!childPackageUpdated) {
16132                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16133                childRemovedRes.removedPackage = childPkg.packageName;
16134                if (childPs != null) {
16135                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16136                }
16137                childRemovedRes.isUpdate = false;
16138                childRemovedRes.dataRemoved = true;
16139                synchronized (mPackages) {
16140                    if (childPs != null) {
16141                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16142                    }
16143                }
16144                if (res.removedInfo.removedChildPackages == null) {
16145                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16146                }
16147                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16148            }
16149        }
16150
16151        boolean sysPkg = (isSystemApp(oldPackage));
16152        if (sysPkg) {
16153            // Set the system/privileged/oem/vendor/product flags as needed
16154            final boolean privileged =
16155                    (oldPackage.applicationInfo.privateFlags
16156                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16157            final boolean oem =
16158                    (oldPackage.applicationInfo.privateFlags
16159                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16160            final boolean vendor =
16161                    (oldPackage.applicationInfo.privateFlags
16162                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16163            final boolean product =
16164                    (oldPackage.applicationInfo.privateFlags
16165                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16166            final @ParseFlags int systemParseFlags = parseFlags;
16167            final @ScanFlags int systemScanFlags = scanFlags
16168                    | SCAN_AS_SYSTEM
16169                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16170                    | (oem ? SCAN_AS_OEM : 0)
16171                    | (vendor ? SCAN_AS_VENDOR : 0)
16172                    | (product ? SCAN_AS_PRODUCT : 0);
16173
16174            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16175                    user, allUsers, installerPackageName, res, installReason);
16176        } else {
16177            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16178                    user, allUsers, installerPackageName, res, installReason);
16179        }
16180    }
16181
16182    @Override
16183    public List<String> getPreviousCodePaths(String packageName) {
16184        final int callingUid = Binder.getCallingUid();
16185        final List<String> result = new ArrayList<>();
16186        if (getInstantAppPackageName(callingUid) != null) {
16187            return result;
16188        }
16189        final PackageSetting ps = mSettings.mPackages.get(packageName);
16190        if (ps != null
16191                && ps.oldCodePaths != null
16192                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16193            result.addAll(ps.oldCodePaths);
16194        }
16195        return result;
16196    }
16197
16198    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16199            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16200            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16201            String installerPackageName, PackageInstalledInfo res, int installReason) {
16202        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16203                + deletedPackage);
16204
16205        String pkgName = deletedPackage.packageName;
16206        boolean deletedPkg = true;
16207        boolean addedPkg = false;
16208        boolean updatedSettings = false;
16209        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16210        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16211                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16212
16213        final long origUpdateTime = (pkg.mExtras != null)
16214                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16215
16216        // First delete the existing package while retaining the data directory
16217        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16218                res.removedInfo, true, pkg)) {
16219            // If the existing package wasn't successfully deleted
16220            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16221            deletedPkg = false;
16222        } else {
16223            // Successfully deleted the old package; proceed with replace.
16224
16225            // If deleted package lived in a container, give users a chance to
16226            // relinquish resources before killing.
16227            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16228                if (DEBUG_INSTALL) {
16229                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16230                }
16231                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16232                final ArrayList<String> pkgList = new ArrayList<String>(1);
16233                pkgList.add(deletedPackage.applicationInfo.packageName);
16234                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16235            }
16236
16237            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16238                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16239
16240            try {
16241                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16242                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16243                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16244                        installReason);
16245
16246                // Update the in-memory copy of the previous code paths.
16247                PackageSetting ps = mSettings.mPackages.get(pkgName);
16248                if (!killApp) {
16249                    if (ps.oldCodePaths == null) {
16250                        ps.oldCodePaths = new ArraySet<>();
16251                    }
16252                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16253                    if (deletedPackage.splitCodePaths != null) {
16254                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16255                    }
16256                } else {
16257                    ps.oldCodePaths = null;
16258                }
16259                if (ps.childPackageNames != null) {
16260                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16261                        final String childPkgName = ps.childPackageNames.get(i);
16262                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16263                        childPs.oldCodePaths = ps.oldCodePaths;
16264                    }
16265                }
16266                // set instant app status, but, only if it's explicitly specified
16267                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16268                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16269                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16270                prepareAppDataAfterInstallLIF(newPackage);
16271                addedPkg = true;
16272                mDexManager.notifyPackageUpdated(newPackage.packageName,
16273                        newPackage.baseCodePath, newPackage.splitCodePaths);
16274            } catch (PackageManagerException e) {
16275                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16276            }
16277        }
16278
16279        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16280            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16281
16282            // Revert all internal state mutations and added folders for the failed install
16283            if (addedPkg) {
16284                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16285                        res.removedInfo, true, null);
16286            }
16287
16288            // Restore the old package
16289            if (deletedPkg) {
16290                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16291                File restoreFile = new File(deletedPackage.codePath);
16292                // Parse old package
16293                boolean oldExternal = isExternal(deletedPackage);
16294                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16295                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16296                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16297                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16298                try {
16299                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16300                            null);
16301                } catch (PackageManagerException e) {
16302                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16303                            + e.getMessage());
16304                    return;
16305                }
16306
16307                synchronized (mPackages) {
16308                    // Ensure the installer package name up to date
16309                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16310
16311                    // Update permissions for restored package
16312                    mPermissionManager.updatePermissions(
16313                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16314                            mPermissionCallback);
16315
16316                    mSettings.writeLPr();
16317                }
16318
16319                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16320            }
16321        } else {
16322            synchronized (mPackages) {
16323                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16324                if (ps != null) {
16325                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16326                    if (res.removedInfo.removedChildPackages != null) {
16327                        final int childCount = res.removedInfo.removedChildPackages.size();
16328                        // Iterate in reverse as we may modify the collection
16329                        for (int i = childCount - 1; i >= 0; i--) {
16330                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16331                            if (res.addedChildPackages.containsKey(childPackageName)) {
16332                                res.removedInfo.removedChildPackages.removeAt(i);
16333                            } else {
16334                                PackageRemovedInfo childInfo = res.removedInfo
16335                                        .removedChildPackages.valueAt(i);
16336                                childInfo.removedForAllUsers = mPackages.get(
16337                                        childInfo.removedPackage) == null;
16338                            }
16339                        }
16340                    }
16341                }
16342            }
16343        }
16344    }
16345
16346    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16347            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16348            final @ScanFlags int scanFlags, UserHandle user,
16349            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16350            int installReason) {
16351        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16352                + ", old=" + deletedPackage);
16353
16354        final boolean disabledSystem;
16355
16356        // Remove existing system package
16357        removePackageLI(deletedPackage, true);
16358
16359        synchronized (mPackages) {
16360            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16361        }
16362        if (!disabledSystem) {
16363            // We didn't need to disable the .apk as a current system package,
16364            // which means we are replacing another update that is already
16365            // installed.  We need to make sure to delete the older one's .apk.
16366            res.removedInfo.args = createInstallArgsForExisting(0,
16367                    deletedPackage.applicationInfo.getCodePath(),
16368                    deletedPackage.applicationInfo.getResourcePath(),
16369                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16370        } else {
16371            res.removedInfo.args = null;
16372        }
16373
16374        // Successfully disabled the old package. Now proceed with re-installation
16375        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16376                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16377
16378        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16379        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16380                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16381
16382        PackageParser.Package newPackage = null;
16383        try {
16384            // Add the package to the internal data structures
16385            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16386
16387            // Set the update and install times
16388            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16389            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16390                    System.currentTimeMillis());
16391
16392            // Update the package dynamic state if succeeded
16393            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16394                // Now that the install succeeded make sure we remove data
16395                // directories for any child package the update removed.
16396                final int deletedChildCount = (deletedPackage.childPackages != null)
16397                        ? deletedPackage.childPackages.size() : 0;
16398                final int newChildCount = (newPackage.childPackages != null)
16399                        ? newPackage.childPackages.size() : 0;
16400                for (int i = 0; i < deletedChildCount; i++) {
16401                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16402                    boolean childPackageDeleted = true;
16403                    for (int j = 0; j < newChildCount; j++) {
16404                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16405                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16406                            childPackageDeleted = false;
16407                            break;
16408                        }
16409                    }
16410                    if (childPackageDeleted) {
16411                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16412                                deletedChildPkg.packageName);
16413                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16414                            PackageRemovedInfo removedChildRes = res.removedInfo
16415                                    .removedChildPackages.get(deletedChildPkg.packageName);
16416                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16417                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16418                        }
16419                    }
16420                }
16421
16422                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16423                        installReason);
16424                prepareAppDataAfterInstallLIF(newPackage);
16425
16426                mDexManager.notifyPackageUpdated(newPackage.packageName,
16427                            newPackage.baseCodePath, newPackage.splitCodePaths);
16428            }
16429        } catch (PackageManagerException e) {
16430            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16431            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16432        }
16433
16434        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16435            // Re installation failed. Restore old information
16436            // Remove new pkg information
16437            if (newPackage != null) {
16438                removeInstalledPackageLI(newPackage, true);
16439            }
16440            // Add back the old system package
16441            try {
16442                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16443            } catch (PackageManagerException e) {
16444                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16445            }
16446
16447            synchronized (mPackages) {
16448                if (disabledSystem) {
16449                    enableSystemPackageLPw(deletedPackage);
16450                }
16451
16452                // Ensure the installer package name up to date
16453                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16454
16455                // Update permissions for restored package
16456                mPermissionManager.updatePermissions(
16457                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16458                        mPermissionCallback);
16459
16460                mSettings.writeLPr();
16461            }
16462
16463            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16464                    + " after failed upgrade");
16465        }
16466    }
16467
16468    /**
16469     * Checks whether the parent or any of the child packages have a change shared
16470     * user. For a package to be a valid update the shred users of the parent and
16471     * the children should match. We may later support changing child shared users.
16472     * @param oldPkg The updated package.
16473     * @param newPkg The update package.
16474     * @return The shared user that change between the versions.
16475     */
16476    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16477            PackageParser.Package newPkg) {
16478        // Check parent shared user
16479        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16480            return newPkg.packageName;
16481        }
16482        // Check child shared users
16483        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16484        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16485        for (int i = 0; i < newChildCount; i++) {
16486            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16487            // If this child was present, did it have the same shared user?
16488            for (int j = 0; j < oldChildCount; j++) {
16489                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16490                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16491                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16492                    return newChildPkg.packageName;
16493                }
16494            }
16495        }
16496        return null;
16497    }
16498
16499    private void removeNativeBinariesLI(PackageSetting ps) {
16500        // Remove the lib path for the parent package
16501        if (ps != null) {
16502            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16503            // Remove the lib path for the child packages
16504            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16505            for (int i = 0; i < childCount; i++) {
16506                PackageSetting childPs = null;
16507                synchronized (mPackages) {
16508                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16509                }
16510                if (childPs != null) {
16511                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16512                            .legacyNativeLibraryPathString);
16513                }
16514            }
16515        }
16516    }
16517
16518    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16519        // Enable the parent package
16520        mSettings.enableSystemPackageLPw(pkg.packageName);
16521        // Enable the child packages
16522        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16523        for (int i = 0; i < childCount; i++) {
16524            PackageParser.Package childPkg = pkg.childPackages.get(i);
16525            mSettings.enableSystemPackageLPw(childPkg.packageName);
16526        }
16527    }
16528
16529    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16530            PackageParser.Package newPkg) {
16531        // Disable the parent package (parent always replaced)
16532        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16533        // Disable the child packages
16534        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16535        for (int i = 0; i < childCount; i++) {
16536            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16537            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16538            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16539        }
16540        return disabled;
16541    }
16542
16543    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16544            String installerPackageName) {
16545        // Enable the parent package
16546        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16547        // Enable the child packages
16548        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16549        for (int i = 0; i < childCount; i++) {
16550            PackageParser.Package childPkg = pkg.childPackages.get(i);
16551            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16552        }
16553    }
16554
16555    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16556            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16557        // Update the parent package setting
16558        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16559                res, user, installReason);
16560        // Update the child packages setting
16561        final int childCount = (newPackage.childPackages != null)
16562                ? newPackage.childPackages.size() : 0;
16563        for (int i = 0; i < childCount; i++) {
16564            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16565            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16566            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16567                    childRes.origUsers, childRes, user, installReason);
16568        }
16569    }
16570
16571    private void updateSettingsInternalLI(PackageParser.Package pkg,
16572            String installerPackageName, int[] allUsers, int[] installedForUsers,
16573            PackageInstalledInfo res, UserHandle user, int installReason) {
16574        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16575
16576        final String pkgName = pkg.packageName;
16577
16578        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16579        synchronized (mPackages) {
16580// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16581            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16582                    mPermissionCallback);
16583            // For system-bundled packages, we assume that installing an upgraded version
16584            // of the package implies that the user actually wants to run that new code,
16585            // so we enable the package.
16586            PackageSetting ps = mSettings.mPackages.get(pkgName);
16587            final int userId = user.getIdentifier();
16588            if (ps != null) {
16589                if (isSystemApp(pkg)) {
16590                    if (DEBUG_INSTALL) {
16591                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16592                    }
16593                    // Enable system package for requested users
16594                    if (res.origUsers != null) {
16595                        for (int origUserId : res.origUsers) {
16596                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16597                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16598                                        origUserId, installerPackageName);
16599                            }
16600                        }
16601                    }
16602                    // Also convey the prior install/uninstall state
16603                    if (allUsers != null && installedForUsers != null) {
16604                        for (int currentUserId : allUsers) {
16605                            final boolean installed = ArrayUtils.contains(
16606                                    installedForUsers, currentUserId);
16607                            if (DEBUG_INSTALL) {
16608                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16609                            }
16610                            ps.setInstalled(installed, currentUserId);
16611                        }
16612                        // these install state changes will be persisted in the
16613                        // upcoming call to mSettings.writeLPr().
16614                    }
16615                }
16616                // It's implied that when a user requests installation, they want the app to be
16617                // installed and enabled.
16618                if (userId != UserHandle.USER_ALL) {
16619                    ps.setInstalled(true, userId);
16620                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16621                } else {
16622                    for (int currentUserId : sUserManager.getUserIds()) {
16623                        ps.setInstalled(true, currentUserId);
16624                        ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, currentUserId,
16625                                installerPackageName);
16626                    }
16627                }
16628
16629                // When replacing an existing package, preserve the original install reason for all
16630                // users that had the package installed before.
16631                final Set<Integer> previousUserIds = new ArraySet<>();
16632                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16633                    final int installReasonCount = res.removedInfo.installReasons.size();
16634                    for (int i = 0; i < installReasonCount; i++) {
16635                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16636                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16637                        ps.setInstallReason(previousInstallReason, previousUserId);
16638                        previousUserIds.add(previousUserId);
16639                    }
16640                }
16641
16642                // Set install reason for users that are having the package newly installed.
16643                if (userId == UserHandle.USER_ALL) {
16644                    for (int currentUserId : sUserManager.getUserIds()) {
16645                        if (!previousUserIds.contains(currentUserId)) {
16646                            ps.setInstallReason(installReason, currentUserId);
16647                        }
16648                    }
16649                } else if (!previousUserIds.contains(userId)) {
16650                    ps.setInstallReason(installReason, userId);
16651                }
16652                mSettings.writeKernelMappingLPr(ps);
16653            }
16654            res.name = pkgName;
16655            res.uid = pkg.applicationInfo.uid;
16656            res.pkg = pkg;
16657            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16658            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16659            //to update install status
16660            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16661            mSettings.writeLPr();
16662            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16663        }
16664
16665        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16666    }
16667
16668    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16669        try {
16670            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16671            installPackageLI(args, res);
16672        } finally {
16673            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16674        }
16675    }
16676
16677    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16678        final int installFlags = args.installFlags;
16679        final String installerPackageName = args.installerPackageName;
16680        final String volumeUuid = args.volumeUuid;
16681        final File tmpPackageFile = new File(args.getCodePath());
16682        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16683        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16684                || (args.volumeUuid != null));
16685        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16686        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16687        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16688        final boolean virtualPreload =
16689                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16690        boolean replace = false;
16691        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16692        if (args.move != null) {
16693            // moving a complete application; perform an initial scan on the new install location
16694            scanFlags |= SCAN_INITIAL;
16695        }
16696        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16697            scanFlags |= SCAN_DONT_KILL_APP;
16698        }
16699        if (instantApp) {
16700            scanFlags |= SCAN_AS_INSTANT_APP;
16701        }
16702        if (fullApp) {
16703            scanFlags |= SCAN_AS_FULL_APP;
16704        }
16705        if (virtualPreload) {
16706            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16707        }
16708
16709        // Result object to be returned
16710        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16711        res.installerPackageName = installerPackageName;
16712
16713        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16714
16715        // Sanity check
16716        if (instantApp && (forwardLocked || onExternal)) {
16717            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16718                    + " external=" + onExternal);
16719            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16720            return;
16721        }
16722
16723        // Retrieve PackageSettings and parse package
16724        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16725                | PackageParser.PARSE_ENFORCE_CODE
16726                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16727                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16728                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16729        PackageParser pp = new PackageParser();
16730        pp.setSeparateProcesses(mSeparateProcesses);
16731        pp.setDisplayMetrics(mMetrics);
16732        pp.setCallback(mPackageParserCallback);
16733
16734        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16735        final PackageParser.Package pkg;
16736        try {
16737            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16738            DexMetadataHelper.validatePackageDexMetadata(pkg);
16739        } catch (PackageParserException e) {
16740            res.setError("Failed parse during installPackageLI", e);
16741            return;
16742        } finally {
16743            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16744        }
16745
16746        // Instant apps have several additional install-time checks.
16747        if (instantApp) {
16748            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16749                Slog.w(TAG,
16750                        "Instant app package " + pkg.packageName + " does not target at least O");
16751                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16752                        "Instant app package must target at least O");
16753                return;
16754            }
16755            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16756                Slog.w(TAG, "Instant app package " + pkg.packageName
16757                        + " does not target targetSandboxVersion 2");
16758                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16759                        "Instant app package must use targetSandboxVersion 2");
16760                return;
16761            }
16762            if (pkg.mSharedUserId != null) {
16763                Slog.w(TAG, "Instant app package " + pkg.packageName
16764                        + " may not declare sharedUserId.");
16765                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16766                        "Instant app package may not declare a sharedUserId");
16767                return;
16768            }
16769        }
16770
16771        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16772            // Static shared libraries have synthetic package names
16773            renameStaticSharedLibraryPackage(pkg);
16774
16775            // No static shared libs on external storage
16776            if (onExternal) {
16777                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16778                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16779                        "Packages declaring static-shared libs cannot be updated");
16780                return;
16781            }
16782        }
16783
16784        // If we are installing a clustered package add results for the children
16785        if (pkg.childPackages != null) {
16786            synchronized (mPackages) {
16787                final int childCount = pkg.childPackages.size();
16788                for (int i = 0; i < childCount; i++) {
16789                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16790                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16791                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16792                    childRes.pkg = childPkg;
16793                    childRes.name = childPkg.packageName;
16794                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16795                    if (childPs != null) {
16796                        childRes.origUsers = childPs.queryInstalledUsers(
16797                                sUserManager.getUserIds(), true);
16798                    }
16799                    if ((mPackages.containsKey(childPkg.packageName))) {
16800                        childRes.removedInfo = new PackageRemovedInfo(this);
16801                        childRes.removedInfo.removedPackage = childPkg.packageName;
16802                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16803                    }
16804                    if (res.addedChildPackages == null) {
16805                        res.addedChildPackages = new ArrayMap<>();
16806                    }
16807                    res.addedChildPackages.put(childPkg.packageName, childRes);
16808                }
16809            }
16810        }
16811
16812        // If package doesn't declare API override, mark that we have an install
16813        // time CPU ABI override.
16814        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16815            pkg.cpuAbiOverride = args.abiOverride;
16816        }
16817
16818        String pkgName = res.name = pkg.packageName;
16819        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16820            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16821                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16822                return;
16823            }
16824        }
16825
16826        try {
16827            // either use what we've been given or parse directly from the APK
16828            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
16829                pkg.setSigningDetails(args.signingDetails);
16830            } else {
16831                PackageParser.collectCertificates(pkg, false /* skipVerify */);
16832            }
16833        } catch (PackageParserException e) {
16834            res.setError("Failed collect during installPackageLI", e);
16835            return;
16836        }
16837
16838        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
16839                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
16840            Slog.w(TAG, "Instant app package " + pkg.packageName
16841                    + " is not signed with at least APK Signature Scheme v2");
16842            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16843                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
16844            return;
16845        }
16846
16847        // Get rid of all references to package scan path via parser.
16848        pp = null;
16849        String oldCodePath = null;
16850        boolean systemApp = false;
16851        synchronized (mPackages) {
16852            // Check if installing already existing package
16853            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16854                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16855                if (pkg.mOriginalPackages != null
16856                        && pkg.mOriginalPackages.contains(oldName)
16857                        && mPackages.containsKey(oldName)) {
16858                    // This package is derived from an original package,
16859                    // and this device has been updating from that original
16860                    // name.  We must continue using the original name, so
16861                    // rename the new package here.
16862                    pkg.setPackageName(oldName);
16863                    pkgName = pkg.packageName;
16864                    replace = true;
16865                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16866                            + oldName + " pkgName=" + pkgName);
16867                } else if (mPackages.containsKey(pkgName)) {
16868                    // This package, under its official name, already exists
16869                    // on the device; we should replace it.
16870                    replace = true;
16871                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16872                }
16873
16874                // Child packages are installed through the parent package
16875                if (pkg.parentPackage != null) {
16876                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16877                            "Package " + pkg.packageName + " is child of package "
16878                                    + pkg.parentPackage.parentPackage + ". Child packages "
16879                                    + "can be updated only through the parent package.");
16880                    return;
16881                }
16882
16883                if (replace) {
16884                    // Prevent apps opting out from runtime permissions
16885                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16886                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16887                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16888                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16889                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16890                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16891                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16892                                        + " doesn't support runtime permissions but the old"
16893                                        + " target SDK " + oldTargetSdk + " does.");
16894                        return;
16895                    }
16896                    // Prevent persistent apps from being updated
16897                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
16898                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
16899                                "Package " + oldPackage.packageName + " is a persistent app. "
16900                                        + "Persistent apps are not updateable.");
16901                        return;
16902                    }
16903                    // Prevent apps from downgrading their targetSandbox.
16904                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16905                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16906                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16907                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16908                                "Package " + pkg.packageName + " new target sandbox "
16909                                + newTargetSandbox + " is incompatible with the previous value of"
16910                                + oldTargetSandbox + ".");
16911                        return;
16912                    }
16913
16914                    // Prevent installing of child packages
16915                    if (oldPackage.parentPackage != null) {
16916                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16917                                "Package " + pkg.packageName + " is child of package "
16918                                        + oldPackage.parentPackage + ". Child packages "
16919                                        + "can be updated only through the parent package.");
16920                        return;
16921                    }
16922                }
16923            }
16924
16925            PackageSetting ps = mSettings.mPackages.get(pkgName);
16926            if (ps != null) {
16927                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16928
16929                // Static shared libs have same package with different versions where
16930                // we internally use a synthetic package name to allow multiple versions
16931                // of the same package, therefore we need to compare signatures against
16932                // the package setting for the latest library version.
16933                PackageSetting signatureCheckPs = ps;
16934                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16935                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16936                    if (libraryEntry != null) {
16937                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16938                    }
16939                }
16940
16941                // Quick sanity check that we're signed correctly if updating;
16942                // we'll check this again later when scanning, but we want to
16943                // bail early here before tripping over redefined permissions.
16944                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16945                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
16946                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
16947                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16948                                + pkg.packageName + " upgrade keys do not match the "
16949                                + "previously installed version");
16950                        return;
16951                    }
16952                } else {
16953                    try {
16954                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
16955                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
16956                        // We don't care about disabledPkgSetting on install for now.
16957                        final boolean compatMatch = verifySignatures(
16958                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
16959                                compareRecover);
16960                        // The new KeySets will be re-added later in the scanning process.
16961                        if (compatMatch) {
16962                            synchronized (mPackages) {
16963                                ksms.removeAppKeySetDataLPw(pkg.packageName);
16964                            }
16965                        }
16966                    } catch (PackageManagerException e) {
16967                        res.setError(e.error, e.getMessage());
16968                        return;
16969                    }
16970                }
16971
16972                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16973                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16974                    systemApp = (ps.pkg.applicationInfo.flags &
16975                            ApplicationInfo.FLAG_SYSTEM) != 0;
16976                }
16977                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16978            }
16979
16980            int N = pkg.permissions.size();
16981            for (int i = N-1; i >= 0; i--) {
16982                final PackageParser.Permission perm = pkg.permissions.get(i);
16983                final BasePermission bp =
16984                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
16985
16986                // Don't allow anyone but the system to define ephemeral permissions.
16987                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
16988                        && !systemApp) {
16989                    Slog.w(TAG, "Non-System package " + pkg.packageName
16990                            + " attempting to delcare ephemeral permission "
16991                            + perm.info.name + "; Removing ephemeral.");
16992                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
16993                }
16994
16995                // Check whether the newly-scanned package wants to define an already-defined perm
16996                if (bp != null) {
16997                    // If the defining package is signed with our cert, it's okay.  This
16998                    // also includes the "updating the same package" case, of course.
16999                    // "updating same package" could also involve key-rotation.
17000                    final boolean sigsOk;
17001                    final String sourcePackageName = bp.getSourcePackageName();
17002                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17003                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17004                    if (sourcePackageName.equals(pkg.packageName)
17005                            && (ksms.shouldCheckUpgradeKeySetLocked(
17006                                    sourcePackageSetting, scanFlags))) {
17007                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17008                    } else {
17009
17010                        // in the event of signing certificate rotation, we need to see if the
17011                        // package's certificate has rotated from the current one, or if it is an
17012                        // older certificate with which the current is ok with sharing permissions
17013                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17014                                        pkg.mSigningDetails,
17015                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17016                            sigsOk = true;
17017                        } else if (pkg.mSigningDetails.checkCapability(
17018                                        sourcePackageSetting.signatures.mSigningDetails,
17019                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17020
17021                            // the scanned package checks out, has signing certificate rotation
17022                            // history, and is newer; bring it over
17023                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17024                            sigsOk = true;
17025                        } else {
17026                            sigsOk = false;
17027                        }
17028                    }
17029                    if (!sigsOk) {
17030                        // If the owning package is the system itself, we log but allow
17031                        // install to proceed; we fail the install on all other permission
17032                        // redefinitions.
17033                        if (!sourcePackageName.equals("android")) {
17034                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17035                                    + pkg.packageName + " attempting to redeclare permission "
17036                                    + perm.info.name + " already owned by " + sourcePackageName);
17037                            res.origPermission = perm.info.name;
17038                            res.origPackage = sourcePackageName;
17039                            return;
17040                        } else {
17041                            Slog.w(TAG, "Package " + pkg.packageName
17042                                    + " attempting to redeclare system permission "
17043                                    + perm.info.name + "; ignoring new declaration");
17044                            pkg.permissions.remove(i);
17045                        }
17046                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17047                        // Prevent apps to change protection level to dangerous from any other
17048                        // type as this would allow a privilege escalation where an app adds a
17049                        // normal/signature permission in other app's group and later redefines
17050                        // it as dangerous leading to the group auto-grant.
17051                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17052                                == PermissionInfo.PROTECTION_DANGEROUS) {
17053                            if (bp != null && !bp.isRuntime()) {
17054                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17055                                        + "non-runtime permission " + perm.info.name
17056                                        + " to runtime; keeping old protection level");
17057                                perm.info.protectionLevel = bp.getProtectionLevel();
17058                            }
17059                        }
17060                    }
17061                }
17062            }
17063        }
17064
17065        if (systemApp) {
17066            if (onExternal) {
17067                // Abort update; system app can't be replaced with app on sdcard
17068                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17069                        "Cannot install updates to system apps on sdcard");
17070                return;
17071            } else if (instantApp) {
17072                // Abort update; system app can't be replaced with an instant app
17073                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17074                        "Cannot update a system app with an instant app");
17075                return;
17076            }
17077        }
17078
17079        if (args.move != null) {
17080            // We did an in-place move, so dex is ready to roll
17081            scanFlags |= SCAN_NO_DEX;
17082            scanFlags |= SCAN_MOVE;
17083
17084            synchronized (mPackages) {
17085                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17086                if (ps == null) {
17087                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17088                            "Missing settings for moved package " + pkgName);
17089                }
17090
17091                // We moved the entire application as-is, so bring over the
17092                // previously derived ABI information.
17093                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17094                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17095            }
17096
17097        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17098            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17099            scanFlags |= SCAN_NO_DEX;
17100
17101            try {
17102                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17103                    args.abiOverride : pkg.cpuAbiOverride);
17104                final boolean extractNativeLibs = !pkg.isLibrary();
17105                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17106            } catch (PackageManagerException pme) {
17107                Slog.e(TAG, "Error deriving application ABI", pme);
17108                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17109                return;
17110            }
17111
17112            // Shared libraries for the package need to be updated.
17113            synchronized (mPackages) {
17114                try {
17115                    updateSharedLibrariesLPr(pkg, null);
17116                } catch (PackageManagerException e) {
17117                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17118                }
17119            }
17120        }
17121
17122        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17123            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17124            return;
17125        }
17126
17127        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17128            String apkPath = null;
17129            synchronized (mPackages) {
17130                // Note that if the attacker managed to skip verify setup, for example by tampering
17131                // with the package settings, upon reboot we will do full apk verification when
17132                // verity is not detected.
17133                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17134                if (ps != null && ps.isPrivileged()) {
17135                    apkPath = pkg.baseCodePath;
17136                }
17137            }
17138
17139            if (apkPath != null) {
17140                final VerityUtils.SetupResult result =
17141                        VerityUtils.generateApkVeritySetupData(apkPath);
17142                if (result.isOk()) {
17143                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17144                    FileDescriptor fd = result.getUnownedFileDescriptor();
17145                    try {
17146                        mInstaller.installApkVerity(apkPath, fd);
17147                    } catch (InstallerException e) {
17148                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17149                                "Failed to set up verity: " + e);
17150                        return;
17151                    } finally {
17152                        IoUtils.closeQuietly(fd);
17153                    }
17154                } else if (result.isFailed()) {
17155                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17156                    return;
17157                } else {
17158                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17159                    // reboot.
17160                }
17161            }
17162        }
17163
17164        if (!instantApp) {
17165            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17166        } else {
17167            if (DEBUG_DOMAIN_VERIFICATION) {
17168                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17169            }
17170        }
17171
17172        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17173                "installPackageLI")) {
17174            if (replace) {
17175                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17176                    // Static libs have a synthetic package name containing the version
17177                    // and cannot be updated as an update would get a new package name,
17178                    // unless this is the exact same version code which is useful for
17179                    // development.
17180                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17181                    if (existingPkg != null &&
17182                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17183                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17184                                + "static-shared libs cannot be updated");
17185                        return;
17186                    }
17187                }
17188                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17189                        installerPackageName, res, args.installReason);
17190            } else {
17191                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17192                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17193            }
17194        }
17195
17196        // Prepare the application profiles for the new code paths.
17197        // This needs to be done before invoking dexopt so that any install-time profile
17198        // can be used for optimizations.
17199        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17200
17201        // Check whether we need to dexopt the app.
17202        //
17203        // NOTE: it is IMPORTANT to call dexopt:
17204        //   - after doRename which will sync the package data from PackageParser.Package and its
17205        //     corresponding ApplicationInfo.
17206        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17207        //     uid of the application (pkg.applicationInfo.uid).
17208        //     This update happens in place!
17209        //
17210        // We only need to dexopt if the package meets ALL of the following conditions:
17211        //   1) it is not forward locked.
17212        //   2) it is not on on an external ASEC container.
17213        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17214        //
17215        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17216        // complete, so we skip this step during installation. Instead, we'll take extra time
17217        // the first time the instant app starts. It's preferred to do it this way to provide
17218        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17219        // middle of running an instant app. The default behaviour can be overridden
17220        // via gservices.
17221        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17222                && !forwardLocked
17223                && !pkg.applicationInfo.isExternalAsec()
17224                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17225                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17226
17227        if (performDexopt) {
17228            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17229            // Do not run PackageDexOptimizer through the local performDexOpt
17230            // method because `pkg` may not be in `mPackages` yet.
17231            //
17232            // Also, don't fail application installs if the dexopt step fails.
17233            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17234                    REASON_INSTALL,
17235                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17236                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17237            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17238                    null /* instructionSets */,
17239                    getOrCreateCompilerPackageStats(pkg),
17240                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17241                    dexoptOptions);
17242            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17243        }
17244
17245        // Notify BackgroundDexOptService that the package has been changed.
17246        // If this is an update of a package which used to fail to compile,
17247        // BackgroundDexOptService will remove it from its blacklist.
17248        // TODO: Layering violation
17249        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17250
17251        synchronized (mPackages) {
17252            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17253            if (ps != null) {
17254                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17255                ps.setUpdateAvailable(false /*updateAvailable*/);
17256            }
17257
17258            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17259            for (int i = 0; i < childCount; i++) {
17260                PackageParser.Package childPkg = pkg.childPackages.get(i);
17261                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17262                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17263                if (childPs != null) {
17264                    childRes.newUsers = childPs.queryInstalledUsers(
17265                            sUserManager.getUserIds(), true);
17266                }
17267            }
17268
17269            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17270                updateSequenceNumberLP(ps, res.newUsers);
17271                updateInstantAppInstallerLocked(pkgName);
17272            }
17273        }
17274    }
17275
17276    private void startIntentFilterVerifications(int userId, boolean replacing,
17277            PackageParser.Package pkg) {
17278        if (mIntentFilterVerifierComponent == null) {
17279            Slog.w(TAG, "No IntentFilter verification will not be done as "
17280                    + "there is no IntentFilterVerifier available!");
17281            return;
17282        }
17283
17284        final int verifierUid = getPackageUid(
17285                mIntentFilterVerifierComponent.getPackageName(),
17286                MATCH_DEBUG_TRIAGED_MISSING,
17287                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17288
17289        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17290        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17291        mHandler.sendMessage(msg);
17292
17293        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17294        for (int i = 0; i < childCount; i++) {
17295            PackageParser.Package childPkg = pkg.childPackages.get(i);
17296            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17297            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17298            mHandler.sendMessage(msg);
17299        }
17300    }
17301
17302    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17303            PackageParser.Package pkg) {
17304        int size = pkg.activities.size();
17305        if (size == 0) {
17306            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17307                    "No activity, so no need to verify any IntentFilter!");
17308            return;
17309        }
17310
17311        final boolean hasDomainURLs = hasDomainURLs(pkg);
17312        if (!hasDomainURLs) {
17313            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17314                    "No domain URLs, so no need to verify any IntentFilter!");
17315            return;
17316        }
17317
17318        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17319                + " if any IntentFilter from the " + size
17320                + " Activities needs verification ...");
17321
17322        int count = 0;
17323        final String packageName = pkg.packageName;
17324
17325        synchronized (mPackages) {
17326            // If this is a new install and we see that we've already run verification for this
17327            // package, we have nothing to do: it means the state was restored from backup.
17328            if (!replacing) {
17329                IntentFilterVerificationInfo ivi =
17330                        mSettings.getIntentFilterVerificationLPr(packageName);
17331                if (ivi != null) {
17332                    if (DEBUG_DOMAIN_VERIFICATION) {
17333                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17334                                + ivi.getStatusString());
17335                    }
17336                    return;
17337                }
17338            }
17339
17340            // If any filters need to be verified, then all need to be.
17341            boolean needToVerify = false;
17342            for (PackageParser.Activity a : pkg.activities) {
17343                for (ActivityIntentInfo filter : a.intents) {
17344                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17345                        if (DEBUG_DOMAIN_VERIFICATION) {
17346                            Slog.d(TAG,
17347                                    "Intent filter needs verification, so processing all filters");
17348                        }
17349                        needToVerify = true;
17350                        break;
17351                    }
17352                }
17353            }
17354
17355            if (needToVerify) {
17356                final int verificationId = mIntentFilterVerificationToken++;
17357                for (PackageParser.Activity a : pkg.activities) {
17358                    for (ActivityIntentInfo filter : a.intents) {
17359                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17360                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17361                                    "Verification needed for IntentFilter:" + filter.toString());
17362                            mIntentFilterVerifier.addOneIntentFilterVerification(
17363                                    verifierUid, userId, verificationId, filter, packageName);
17364                            count++;
17365                        }
17366                    }
17367                }
17368            }
17369        }
17370
17371        if (count > 0) {
17372            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17373                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17374                    +  " for userId:" + userId);
17375            mIntentFilterVerifier.startVerifications(userId);
17376        } else {
17377            if (DEBUG_DOMAIN_VERIFICATION) {
17378                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17379            }
17380        }
17381    }
17382
17383    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17384        final ComponentName cn  = filter.activity.getComponentName();
17385        final String packageName = cn.getPackageName();
17386
17387        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17388                packageName);
17389        if (ivi == null) {
17390            return true;
17391        }
17392        int status = ivi.getStatus();
17393        switch (status) {
17394            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17395            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17396                return true;
17397
17398            default:
17399                // Nothing to do
17400                return false;
17401        }
17402    }
17403
17404    private static boolean isMultiArch(ApplicationInfo info) {
17405        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17406    }
17407
17408    private static boolean isExternal(PackageParser.Package pkg) {
17409        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17410    }
17411
17412    private static boolean isExternal(PackageSetting ps) {
17413        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17414    }
17415
17416    private static boolean isSystemApp(PackageParser.Package pkg) {
17417        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17418    }
17419
17420    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17421        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17422    }
17423
17424    private static boolean isOemApp(PackageParser.Package pkg) {
17425        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17426    }
17427
17428    private static boolean isVendorApp(PackageParser.Package pkg) {
17429        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17430    }
17431
17432    private static boolean isProductApp(PackageParser.Package pkg) {
17433        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17434    }
17435
17436    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17437        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17438    }
17439
17440    private static boolean isSystemApp(PackageSetting ps) {
17441        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17442    }
17443
17444    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17445        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17446    }
17447
17448    private int packageFlagsToInstallFlags(PackageSetting ps) {
17449        int installFlags = 0;
17450        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17451            // This existing package was an external ASEC install when we have
17452            // the external flag without a UUID
17453            installFlags |= PackageManager.INSTALL_EXTERNAL;
17454        }
17455        if (ps.isForwardLocked()) {
17456            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17457        }
17458        return installFlags;
17459    }
17460
17461    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17462        if (isExternal(pkg)) {
17463            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17464                return mSettings.getExternalVersion();
17465            } else {
17466                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17467            }
17468        } else {
17469            return mSettings.getInternalVersion();
17470        }
17471    }
17472
17473    private void deleteTempPackageFiles() {
17474        final FilenameFilter filter = new FilenameFilter() {
17475            public boolean accept(File dir, String name) {
17476                return name.startsWith("vmdl") && name.endsWith(".tmp");
17477            }
17478        };
17479        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17480            file.delete();
17481        }
17482    }
17483
17484    @Override
17485    public void deletePackageAsUser(String packageName, int versionCode,
17486            IPackageDeleteObserver observer, int userId, int flags) {
17487        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17488                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17489    }
17490
17491    @Override
17492    public void deletePackageVersioned(VersionedPackage versionedPackage,
17493            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17494        final int callingUid = Binder.getCallingUid();
17495        mContext.enforceCallingOrSelfPermission(
17496                android.Manifest.permission.DELETE_PACKAGES, null);
17497        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17498        Preconditions.checkNotNull(versionedPackage);
17499        Preconditions.checkNotNull(observer);
17500        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17501                PackageManager.VERSION_CODE_HIGHEST,
17502                Long.MAX_VALUE, "versionCode must be >= -1");
17503
17504        final String packageName = versionedPackage.getPackageName();
17505        final long versionCode = versionedPackage.getLongVersionCode();
17506        final String internalPackageName;
17507        synchronized (mPackages) {
17508            // Normalize package name to handle renamed packages and static libs
17509            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17510        }
17511
17512        final int uid = Binder.getCallingUid();
17513        if (!isOrphaned(internalPackageName)
17514                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17515            try {
17516                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17517                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17518                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17519                observer.onUserActionRequired(intent);
17520            } catch (RemoteException re) {
17521            }
17522            return;
17523        }
17524        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17525        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17526        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17527            mContext.enforceCallingOrSelfPermission(
17528                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17529                    "deletePackage for user " + userId);
17530        }
17531
17532        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17533            try {
17534                observer.onPackageDeleted(packageName,
17535                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17536            } catch (RemoteException re) {
17537            }
17538            return;
17539        }
17540
17541        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17542            try {
17543                observer.onPackageDeleted(packageName,
17544                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17545            } catch (RemoteException re) {
17546            }
17547            return;
17548        }
17549
17550        if (DEBUG_REMOVE) {
17551            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17552                    + " deleteAllUsers: " + deleteAllUsers + " version="
17553                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17554                    ? "VERSION_CODE_HIGHEST" : versionCode));
17555        }
17556        // Queue up an async operation since the package deletion may take a little while.
17557        mHandler.post(new Runnable() {
17558            public void run() {
17559                mHandler.removeCallbacks(this);
17560                int returnCode;
17561                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17562                boolean doDeletePackage = true;
17563                if (ps != null) {
17564                    final boolean targetIsInstantApp =
17565                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17566                    doDeletePackage = !targetIsInstantApp
17567                            || canViewInstantApps;
17568                }
17569                if (doDeletePackage) {
17570                    if (!deleteAllUsers) {
17571                        returnCode = deletePackageX(internalPackageName, versionCode,
17572                                userId, deleteFlags);
17573                    } else {
17574                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17575                                internalPackageName, users);
17576                        // If nobody is blocking uninstall, proceed with delete for all users
17577                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17578                            returnCode = deletePackageX(internalPackageName, versionCode,
17579                                    userId, deleteFlags);
17580                        } else {
17581                            // Otherwise uninstall individually for users with blockUninstalls=false
17582                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17583                            for (int userId : users) {
17584                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17585                                    returnCode = deletePackageX(internalPackageName, versionCode,
17586                                            userId, userFlags);
17587                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17588                                        Slog.w(TAG, "Package delete failed for user " + userId
17589                                                + ", returnCode " + returnCode);
17590                                    }
17591                                }
17592                            }
17593                            // The app has only been marked uninstalled for certain users.
17594                            // We still need to report that delete was blocked
17595                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17596                        }
17597                    }
17598                } else {
17599                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17600                }
17601                try {
17602                    observer.onPackageDeleted(packageName, returnCode, null);
17603                } catch (RemoteException e) {
17604                    Log.i(TAG, "Observer no longer exists.");
17605                } //end catch
17606            } //end run
17607        });
17608    }
17609
17610    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17611        if (pkg.staticSharedLibName != null) {
17612            return pkg.manifestPackageName;
17613        }
17614        return pkg.packageName;
17615    }
17616
17617    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17618        // Handle renamed packages
17619        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17620        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17621
17622        // Is this a static library?
17623        LongSparseArray<SharedLibraryEntry> versionedLib =
17624                mStaticLibsByDeclaringPackage.get(packageName);
17625        if (versionedLib == null || versionedLib.size() <= 0) {
17626            return packageName;
17627        }
17628
17629        // Figure out which lib versions the caller can see
17630        LongSparseLongArray versionsCallerCanSee = null;
17631        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17632        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17633                && callingAppId != Process.ROOT_UID) {
17634            versionsCallerCanSee = new LongSparseLongArray();
17635            String libName = versionedLib.valueAt(0).info.getName();
17636            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17637            if (uidPackages != null) {
17638                for (String uidPackage : uidPackages) {
17639                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17640                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17641                    if (libIdx >= 0) {
17642                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17643                        versionsCallerCanSee.append(libVersion, libVersion);
17644                    }
17645                }
17646            }
17647        }
17648
17649        // Caller can see nothing - done
17650        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17651            return packageName;
17652        }
17653
17654        // Find the version the caller can see and the app version code
17655        SharedLibraryEntry highestVersion = null;
17656        final int versionCount = versionedLib.size();
17657        for (int i = 0; i < versionCount; i++) {
17658            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17659            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17660                    libEntry.info.getLongVersion()) < 0) {
17661                continue;
17662            }
17663            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17664            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17665                if (libVersionCode == versionCode) {
17666                    return libEntry.apk;
17667                }
17668            } else if (highestVersion == null) {
17669                highestVersion = libEntry;
17670            } else if (libVersionCode  > highestVersion.info
17671                    .getDeclaringPackage().getLongVersionCode()) {
17672                highestVersion = libEntry;
17673            }
17674        }
17675
17676        if (highestVersion != null) {
17677            return highestVersion.apk;
17678        }
17679
17680        return packageName;
17681    }
17682
17683    boolean isCallerVerifier(int callingUid) {
17684        final int callingUserId = UserHandle.getUserId(callingUid);
17685        return mRequiredVerifierPackage != null &&
17686                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17687    }
17688
17689    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17690        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17691              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17692            return true;
17693        }
17694        final int callingUserId = UserHandle.getUserId(callingUid);
17695        // If the caller installed the pkgName, then allow it to silently uninstall.
17696        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17697            return true;
17698        }
17699
17700        // Allow package verifier to silently uninstall.
17701        if (mRequiredVerifierPackage != null &&
17702                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17703            return true;
17704        }
17705
17706        // Allow package uninstaller to silently uninstall.
17707        if (mRequiredUninstallerPackage != null &&
17708                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17709            return true;
17710        }
17711
17712        // Allow storage manager to silently uninstall.
17713        if (mStorageManagerPackage != null &&
17714                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17715            return true;
17716        }
17717
17718        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17719        // uninstall for device owner provisioning.
17720        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17721                == PERMISSION_GRANTED) {
17722            return true;
17723        }
17724
17725        return false;
17726    }
17727
17728    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17729        int[] result = EMPTY_INT_ARRAY;
17730        for (int userId : userIds) {
17731            if (getBlockUninstallForUser(packageName, userId)) {
17732                result = ArrayUtils.appendInt(result, userId);
17733            }
17734        }
17735        return result;
17736    }
17737
17738    @Override
17739    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17740        final int callingUid = Binder.getCallingUid();
17741        if (getInstantAppPackageName(callingUid) != null
17742                && !isCallerSameApp(packageName, callingUid)) {
17743            return false;
17744        }
17745        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17746    }
17747
17748    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17749        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17750                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17751        try {
17752            if (dpm != null) {
17753                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17754                        /* callingUserOnly =*/ false);
17755                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17756                        : deviceOwnerComponentName.getPackageName();
17757                // Does the package contains the device owner?
17758                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17759                // this check is probably not needed, since DO should be registered as a device
17760                // admin on some user too. (Original bug for this: b/17657954)
17761                if (packageName.equals(deviceOwnerPackageName)) {
17762                    return true;
17763                }
17764                // Does it contain a device admin for any user?
17765                int[] users;
17766                if (userId == UserHandle.USER_ALL) {
17767                    users = sUserManager.getUserIds();
17768                } else {
17769                    users = new int[]{userId};
17770                }
17771                for (int i = 0; i < users.length; ++i) {
17772                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17773                        return true;
17774                    }
17775                }
17776            }
17777        } catch (RemoteException e) {
17778        }
17779        return false;
17780    }
17781
17782    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17783        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17784    }
17785
17786    /**
17787     *  This method is an internal method that could be get invoked either
17788     *  to delete an installed package or to clean up a failed installation.
17789     *  After deleting an installed package, a broadcast is sent to notify any
17790     *  listeners that the package has been removed. For cleaning up a failed
17791     *  installation, the broadcast is not necessary since the package's
17792     *  installation wouldn't have sent the initial broadcast either
17793     *  The key steps in deleting a package are
17794     *  deleting the package information in internal structures like mPackages,
17795     *  deleting the packages base directories through installd
17796     *  updating mSettings to reflect current status
17797     *  persisting settings for later use
17798     *  sending a broadcast if necessary
17799     */
17800    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17801        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17802        final boolean res;
17803
17804        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17805                ? UserHandle.USER_ALL : userId;
17806
17807        if (isPackageDeviceAdmin(packageName, removeUser)) {
17808            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17809            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17810        }
17811
17812        PackageSetting uninstalledPs = null;
17813        PackageParser.Package pkg = null;
17814
17815        // for the uninstall-updates case and restricted profiles, remember the per-
17816        // user handle installed state
17817        int[] allUsers;
17818        synchronized (mPackages) {
17819            uninstalledPs = mSettings.mPackages.get(packageName);
17820            if (uninstalledPs == null) {
17821                Slog.w(TAG, "Not removing non-existent package " + packageName);
17822                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17823            }
17824
17825            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17826                    && uninstalledPs.versionCode != versionCode) {
17827                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17828                        + uninstalledPs.versionCode + " != " + versionCode);
17829                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17830            }
17831
17832            // Static shared libs can be declared by any package, so let us not
17833            // allow removing a package if it provides a lib others depend on.
17834            pkg = mPackages.get(packageName);
17835
17836            allUsers = sUserManager.getUserIds();
17837
17838            if (pkg != null && pkg.staticSharedLibName != null) {
17839                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17840                        pkg.staticSharedLibVersion);
17841                if (libEntry != null) {
17842                    for (int currUserId : allUsers) {
17843                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17844                            continue;
17845                        }
17846                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17847                                libEntry.info, 0, currUserId);
17848                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17849                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17850                                    + " hosting lib " + libEntry.info.getName() + " version "
17851                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
17852                                    + " for user " + currUserId);
17853                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17854                        }
17855                    }
17856                }
17857            }
17858
17859            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17860        }
17861
17862        final int freezeUser;
17863        if (isUpdatedSystemApp(uninstalledPs)
17864                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17865            // We're downgrading a system app, which will apply to all users, so
17866            // freeze them all during the downgrade
17867            freezeUser = UserHandle.USER_ALL;
17868        } else {
17869            freezeUser = removeUser;
17870        }
17871
17872        synchronized (mInstallLock) {
17873            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17874            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17875                    deleteFlags, "deletePackageX")) {
17876                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17877                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
17878            }
17879            synchronized (mPackages) {
17880                if (res) {
17881                    if (pkg != null) {
17882                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17883                    }
17884                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
17885                    updateInstantAppInstallerLocked(packageName);
17886                }
17887            }
17888        }
17889
17890        if (res) {
17891            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17892            info.sendPackageRemovedBroadcasts(killApp);
17893            info.sendSystemPackageUpdatedBroadcasts();
17894            info.sendSystemPackageAppearedBroadcasts();
17895        }
17896        // Force a gc here.
17897        Runtime.getRuntime().gc();
17898        // Delete the resources here after sending the broadcast to let
17899        // other processes clean up before deleting resources.
17900        if (info.args != null) {
17901            synchronized (mInstallLock) {
17902                info.args.doPostDeleteLI(true);
17903            }
17904        }
17905
17906        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17907    }
17908
17909    static class PackageRemovedInfo {
17910        final PackageSender packageSender;
17911        String removedPackage;
17912        String installerPackageName;
17913        int uid = -1;
17914        int removedAppId = -1;
17915        int[] origUsers;
17916        int[] removedUsers = null;
17917        int[] broadcastUsers = null;
17918        int[] instantUserIds = null;
17919        SparseArray<Integer> installReasons;
17920        boolean isRemovedPackageSystemUpdate = false;
17921        boolean isUpdate;
17922        boolean dataRemoved;
17923        boolean removedForAllUsers;
17924        boolean isStaticSharedLib;
17925        // Clean up resources deleted packages.
17926        InstallArgs args = null;
17927        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17928        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17929
17930        PackageRemovedInfo(PackageSender packageSender) {
17931            this.packageSender = packageSender;
17932        }
17933
17934        void sendPackageRemovedBroadcasts(boolean killApp) {
17935            sendPackageRemovedBroadcastInternal(killApp);
17936            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17937            for (int i = 0; i < childCount; i++) {
17938                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17939                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17940            }
17941        }
17942
17943        void sendSystemPackageUpdatedBroadcasts() {
17944            if (isRemovedPackageSystemUpdate) {
17945                sendSystemPackageUpdatedBroadcastsInternal();
17946                final int childCount = (removedChildPackages != null)
17947                        ? removedChildPackages.size() : 0;
17948                for (int i = 0; i < childCount; i++) {
17949                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17950                    if (childInfo.isRemovedPackageSystemUpdate) {
17951                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17952                    }
17953                }
17954            }
17955        }
17956
17957        void sendSystemPackageAppearedBroadcasts() {
17958            final int packageCount = (appearedChildPackages != null)
17959                    ? appearedChildPackages.size() : 0;
17960            for (int i = 0; i < packageCount; i++) {
17961                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17962                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
17963                    true /*sendBootCompleted*/, false /*startReceiver*/,
17964                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
17965            }
17966        }
17967
17968        private void sendSystemPackageUpdatedBroadcastsInternal() {
17969            Bundle extras = new Bundle(2);
17970            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17971            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17972            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17973                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17974            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17975                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17976            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
17977                null, null, 0, removedPackage, null, null, null);
17978            if (installerPackageName != null) {
17979                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17980                        removedPackage, extras, 0 /*flags*/,
17981                        installerPackageName, null, null, null);
17982                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17983                        removedPackage, extras, 0 /*flags*/,
17984                        installerPackageName, null, null, null);
17985            }
17986        }
17987
17988        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17989            // Don't send static shared library removal broadcasts as these
17990            // libs are visible only the the apps that depend on them an one
17991            // cannot remove the library if it has a dependency.
17992            if (isStaticSharedLib) {
17993                return;
17994            }
17995            Bundle extras = new Bundle(2);
17996            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17997            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17998            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17999            if (isUpdate || isRemovedPackageSystemUpdate) {
18000                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18001            }
18002            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18003            if (removedPackage != null) {
18004                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18005                    removedPackage, extras, 0, null /*targetPackage*/, null,
18006                    broadcastUsers, instantUserIds);
18007                if (installerPackageName != null) {
18008                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18009                            removedPackage, extras, 0 /*flags*/,
18010                            installerPackageName, null, broadcastUsers, instantUserIds);
18011                }
18012                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18013                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18014                        removedPackage, extras,
18015                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18016                        null, null, broadcastUsers, instantUserIds);
18017                    packageSender.notifyPackageRemoved(removedPackage);
18018                }
18019            }
18020            if (removedAppId >= 0) {
18021                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18022                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18023                    null, null, broadcastUsers, instantUserIds);
18024            }
18025        }
18026
18027        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18028            removedUsers = userIds;
18029            if (removedUsers == null) {
18030                broadcastUsers = null;
18031                return;
18032            }
18033
18034            broadcastUsers = EMPTY_INT_ARRAY;
18035            instantUserIds = EMPTY_INT_ARRAY;
18036            for (int i = userIds.length - 1; i >= 0; --i) {
18037                final int userId = userIds[i];
18038                if (deletedPackageSetting.getInstantApp(userId)) {
18039                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18040                } else {
18041                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18042                }
18043            }
18044        }
18045    }
18046
18047    /*
18048     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18049     * flag is not set, the data directory is removed as well.
18050     * make sure this flag is set for partially installed apps. If not its meaningless to
18051     * delete a partially installed application.
18052     */
18053    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18054            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18055        String packageName = ps.name;
18056        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18057        // Retrieve object to delete permissions for shared user later on
18058        final PackageParser.Package deletedPkg;
18059        final PackageSetting deletedPs;
18060        // reader
18061        synchronized (mPackages) {
18062            deletedPkg = mPackages.get(packageName);
18063            deletedPs = mSettings.mPackages.get(packageName);
18064            if (outInfo != null) {
18065                outInfo.removedPackage = packageName;
18066                outInfo.installerPackageName = ps.installerPackageName;
18067                outInfo.isStaticSharedLib = deletedPkg != null
18068                        && deletedPkg.staticSharedLibName != null;
18069                outInfo.populateUsers(deletedPs == null ? null
18070                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18071            }
18072        }
18073
18074        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18075
18076        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18077            final PackageParser.Package resolvedPkg;
18078            if (deletedPkg != null) {
18079                resolvedPkg = deletedPkg;
18080            } else {
18081                // We don't have a parsed package when it lives on an ejected
18082                // adopted storage device, so fake something together
18083                resolvedPkg = new PackageParser.Package(ps.name);
18084                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18085            }
18086            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18087                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18088            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18089            if (outInfo != null) {
18090                outInfo.dataRemoved = true;
18091            }
18092            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18093        }
18094
18095        int removedAppId = -1;
18096
18097        // writer
18098        synchronized (mPackages) {
18099            boolean installedStateChanged = false;
18100            if (deletedPs != null) {
18101                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18102                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18103                    clearDefaultBrowserIfNeeded(packageName);
18104                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18105                    removedAppId = mSettings.removePackageLPw(packageName);
18106                    if (outInfo != null) {
18107                        outInfo.removedAppId = removedAppId;
18108                    }
18109                    mPermissionManager.updatePermissions(
18110                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18111                    if (deletedPs.sharedUser != null) {
18112                        // Remove permissions associated with package. Since runtime
18113                        // permissions are per user we have to kill the removed package
18114                        // or packages running under the shared user of the removed
18115                        // package if revoking the permissions requested only by the removed
18116                        // package is successful and this causes a change in gids.
18117                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18118                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18119                                    userId);
18120                            if (userIdToKill == UserHandle.USER_ALL
18121                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18122                                // If gids changed for this user, kill all affected packages.
18123                                mHandler.post(new Runnable() {
18124                                    @Override
18125                                    public void run() {
18126                                        // This has to happen with no lock held.
18127                                        killApplication(deletedPs.name, deletedPs.appId,
18128                                                KILL_APP_REASON_GIDS_CHANGED);
18129                                    }
18130                                });
18131                                break;
18132                            }
18133                        }
18134                    }
18135                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18136                }
18137                // make sure to preserve per-user disabled state if this removal was just
18138                // a downgrade of a system app to the factory package
18139                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18140                    if (DEBUG_REMOVE) {
18141                        Slog.d(TAG, "Propagating install state across downgrade");
18142                    }
18143                    for (int userId : allUserHandles) {
18144                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18145                        if (DEBUG_REMOVE) {
18146                            Slog.d(TAG, "    user " + userId + " => " + installed);
18147                        }
18148                        if (installed != ps.getInstalled(userId)) {
18149                            installedStateChanged = true;
18150                        }
18151                        ps.setInstalled(installed, userId);
18152                    }
18153                }
18154            }
18155            // can downgrade to reader
18156            if (writeSettings) {
18157                // Save settings now
18158                mSettings.writeLPr();
18159            }
18160            if (installedStateChanged) {
18161                mSettings.writeKernelMappingLPr(ps);
18162            }
18163        }
18164        if (removedAppId != -1) {
18165            // A user ID was deleted here. Go through all users and remove it
18166            // from KeyStore.
18167            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18168        }
18169    }
18170
18171    static boolean locationIsPrivileged(String path) {
18172        try {
18173            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18174            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18175            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18176            return path.startsWith(privilegedAppDir.getCanonicalPath())
18177                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18178                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18179        } catch (IOException e) {
18180            Slog.e(TAG, "Unable to access code path " + path);
18181        }
18182        return false;
18183    }
18184
18185    static boolean locationIsOem(String path) {
18186        try {
18187            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18188        } catch (IOException e) {
18189            Slog.e(TAG, "Unable to access code path " + path);
18190        }
18191        return false;
18192    }
18193
18194    static boolean locationIsVendor(String path) {
18195        try {
18196            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath());
18197        } catch (IOException e) {
18198            Slog.e(TAG, "Unable to access code path " + path);
18199        }
18200        return false;
18201    }
18202
18203    static boolean locationIsProduct(String path) {
18204        try {
18205            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18206        } catch (IOException e) {
18207            Slog.e(TAG, "Unable to access code path " + path);
18208        }
18209        return false;
18210    }
18211
18212    /*
18213     * Tries to delete system package.
18214     */
18215    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18216            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18217            boolean writeSettings) {
18218        if (deletedPs.parentPackageName != null) {
18219            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18220            return false;
18221        }
18222
18223        final boolean applyUserRestrictions
18224                = (allUserHandles != null) && (outInfo.origUsers != null);
18225        final PackageSetting disabledPs;
18226        // Confirm if the system package has been updated
18227        // An updated system app can be deleted. This will also have to restore
18228        // the system pkg from system partition
18229        // reader
18230        synchronized (mPackages) {
18231            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18232        }
18233
18234        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18235                + " disabledPs=" + disabledPs);
18236
18237        if (disabledPs == null) {
18238            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18239            return false;
18240        } else if (DEBUG_REMOVE) {
18241            Slog.d(TAG, "Deleting system pkg from data partition");
18242        }
18243
18244        if (DEBUG_REMOVE) {
18245            if (applyUserRestrictions) {
18246                Slog.d(TAG, "Remembering install states:");
18247                for (int userId : allUserHandles) {
18248                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18249                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18250                }
18251            }
18252        }
18253
18254        // Delete the updated package
18255        outInfo.isRemovedPackageSystemUpdate = true;
18256        if (outInfo.removedChildPackages != null) {
18257            final int childCount = (deletedPs.childPackageNames != null)
18258                    ? deletedPs.childPackageNames.size() : 0;
18259            for (int i = 0; i < childCount; i++) {
18260                String childPackageName = deletedPs.childPackageNames.get(i);
18261                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18262                        .contains(childPackageName)) {
18263                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18264                            childPackageName);
18265                    if (childInfo != null) {
18266                        childInfo.isRemovedPackageSystemUpdate = true;
18267                    }
18268                }
18269            }
18270        }
18271
18272        if (disabledPs.versionCode < deletedPs.versionCode) {
18273            // Delete data for downgrades
18274            flags &= ~PackageManager.DELETE_KEEP_DATA;
18275        } else {
18276            // Preserve data by setting flag
18277            flags |= PackageManager.DELETE_KEEP_DATA;
18278        }
18279
18280        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18281                outInfo, writeSettings, disabledPs.pkg);
18282        if (!ret) {
18283            return false;
18284        }
18285
18286        // writer
18287        synchronized (mPackages) {
18288            // NOTE: The system package always needs to be enabled; even if it's for
18289            // a compressed stub. If we don't, installing the system package fails
18290            // during scan [scanning checks the disabled packages]. We will reverse
18291            // this later, after we've "installed" the stub.
18292            // Reinstate the old system package
18293            enableSystemPackageLPw(disabledPs.pkg);
18294            // Remove any native libraries from the upgraded package.
18295            removeNativeBinariesLI(deletedPs);
18296        }
18297
18298        // Install the system package
18299        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18300        try {
18301            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18302                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18303        } catch (PackageManagerException e) {
18304            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18305                    + e.getMessage());
18306            return false;
18307        } finally {
18308            if (disabledPs.pkg.isStub) {
18309                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18310            }
18311        }
18312        return true;
18313    }
18314
18315    /**
18316     * Installs a package that's already on the system partition.
18317     */
18318    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18319            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18320            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18321                    throws PackageManagerException {
18322        @ParseFlags int parseFlags =
18323                mDefParseFlags
18324                | PackageParser.PARSE_MUST_BE_APK
18325                | PackageParser.PARSE_IS_SYSTEM_DIR;
18326        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18327        if (isPrivileged || locationIsPrivileged(codePathString)) {
18328            scanFlags |= SCAN_AS_PRIVILEGED;
18329        }
18330        if (locationIsOem(codePathString)) {
18331            scanFlags |= SCAN_AS_OEM;
18332        }
18333        if (locationIsVendor(codePathString)) {
18334            scanFlags |= SCAN_AS_VENDOR;
18335        }
18336        if (locationIsProduct(codePathString)) {
18337            scanFlags |= SCAN_AS_PRODUCT;
18338        }
18339
18340        final File codePath = new File(codePathString);
18341        final PackageParser.Package pkg =
18342                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18343
18344        try {
18345            // update shared libraries for the newly re-installed system package
18346            updateSharedLibrariesLPr(pkg, null);
18347        } catch (PackageManagerException e) {
18348            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18349        }
18350
18351        prepareAppDataAfterInstallLIF(pkg);
18352
18353        // writer
18354        synchronized (mPackages) {
18355            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18356
18357            // Propagate the permissions state as we do not want to drop on the floor
18358            // runtime permissions. The update permissions method below will take
18359            // care of removing obsolete permissions and grant install permissions.
18360            if (origPermissionState != null) {
18361                ps.getPermissionsState().copyFrom(origPermissionState);
18362            }
18363            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18364                    mPermissionCallback);
18365
18366            final boolean applyUserRestrictions
18367                    = (allUserHandles != null) && (origUserHandles != null);
18368            if (applyUserRestrictions) {
18369                boolean installedStateChanged = false;
18370                if (DEBUG_REMOVE) {
18371                    Slog.d(TAG, "Propagating install state across reinstall");
18372                }
18373                for (int userId : allUserHandles) {
18374                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18375                    if (DEBUG_REMOVE) {
18376                        Slog.d(TAG, "    user " + userId + " => " + installed);
18377                    }
18378                    if (installed != ps.getInstalled(userId)) {
18379                        installedStateChanged = true;
18380                    }
18381                    ps.setInstalled(installed, userId);
18382
18383                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18384                }
18385                // Regardless of writeSettings we need to ensure that this restriction
18386                // state propagation is persisted
18387                mSettings.writeAllUsersPackageRestrictionsLPr();
18388                if (installedStateChanged) {
18389                    mSettings.writeKernelMappingLPr(ps);
18390                }
18391            }
18392            // can downgrade to reader here
18393            if (writeSettings) {
18394                mSettings.writeLPr();
18395            }
18396        }
18397        return pkg;
18398    }
18399
18400    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18401            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18402            PackageRemovedInfo outInfo, boolean writeSettings,
18403            PackageParser.Package replacingPackage) {
18404        synchronized (mPackages) {
18405            if (outInfo != null) {
18406                outInfo.uid = ps.appId;
18407            }
18408
18409            if (outInfo != null && outInfo.removedChildPackages != null) {
18410                final int childCount = (ps.childPackageNames != null)
18411                        ? ps.childPackageNames.size() : 0;
18412                for (int i = 0; i < childCount; i++) {
18413                    String childPackageName = ps.childPackageNames.get(i);
18414                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18415                    if (childPs == null) {
18416                        return false;
18417                    }
18418                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18419                            childPackageName);
18420                    if (childInfo != null) {
18421                        childInfo.uid = childPs.appId;
18422                    }
18423                }
18424            }
18425        }
18426
18427        // Delete package data from internal structures and also remove data if flag is set
18428        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18429
18430        // Delete the child packages data
18431        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18432        for (int i = 0; i < childCount; i++) {
18433            PackageSetting childPs;
18434            synchronized (mPackages) {
18435                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18436            }
18437            if (childPs != null) {
18438                PackageRemovedInfo childOutInfo = (outInfo != null
18439                        && outInfo.removedChildPackages != null)
18440                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18441                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18442                        && (replacingPackage != null
18443                        && !replacingPackage.hasChildPackage(childPs.name))
18444                        ? flags & ~DELETE_KEEP_DATA : flags;
18445                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18446                        deleteFlags, writeSettings);
18447            }
18448        }
18449
18450        // Delete application code and resources only for parent packages
18451        if (ps.parentPackageName == null) {
18452            if (deleteCodeAndResources && (outInfo != null)) {
18453                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18454                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18455                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18456            }
18457        }
18458
18459        return true;
18460    }
18461
18462    @Override
18463    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18464            int userId) {
18465        mContext.enforceCallingOrSelfPermission(
18466                android.Manifest.permission.DELETE_PACKAGES, null);
18467        synchronized (mPackages) {
18468            // Cannot block uninstall of static shared libs as they are
18469            // considered a part of the using app (emulating static linking).
18470            // Also static libs are installed always on internal storage.
18471            PackageParser.Package pkg = mPackages.get(packageName);
18472            if (pkg != null && pkg.staticSharedLibName != null) {
18473                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18474                        + " providing static shared library: " + pkg.staticSharedLibName);
18475                return false;
18476            }
18477            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18478            mSettings.writePackageRestrictionsLPr(userId);
18479        }
18480        return true;
18481    }
18482
18483    @Override
18484    public boolean getBlockUninstallForUser(String packageName, int userId) {
18485        synchronized (mPackages) {
18486            final PackageSetting ps = mSettings.mPackages.get(packageName);
18487            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18488                return false;
18489            }
18490            return mSettings.getBlockUninstallLPr(userId, packageName);
18491        }
18492    }
18493
18494    @Override
18495    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18496        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18497        synchronized (mPackages) {
18498            PackageSetting ps = mSettings.mPackages.get(packageName);
18499            if (ps == null) {
18500                Log.w(TAG, "Package doesn't exist: " + packageName);
18501                return false;
18502            }
18503            if (systemUserApp) {
18504                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18505            } else {
18506                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18507            }
18508            mSettings.writeLPr();
18509        }
18510        return true;
18511    }
18512
18513    /*
18514     * This method handles package deletion in general
18515     */
18516    private boolean deletePackageLIF(String packageName, UserHandle user,
18517            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18518            PackageRemovedInfo outInfo, boolean writeSettings,
18519            PackageParser.Package replacingPackage) {
18520        if (packageName == null) {
18521            Slog.w(TAG, "Attempt to delete null packageName.");
18522            return false;
18523        }
18524
18525        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18526
18527        PackageSetting ps;
18528        synchronized (mPackages) {
18529            ps = mSettings.mPackages.get(packageName);
18530            if (ps == null) {
18531                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18532                return false;
18533            }
18534
18535            if (ps.parentPackageName != null && (!isSystemApp(ps)
18536                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18537                if (DEBUG_REMOVE) {
18538                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18539                            + ((user == null) ? UserHandle.USER_ALL : user));
18540                }
18541                final int removedUserId = (user != null) ? user.getIdentifier()
18542                        : UserHandle.USER_ALL;
18543                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18544                    return false;
18545                }
18546                markPackageUninstalledForUserLPw(ps, user);
18547                scheduleWritePackageRestrictionsLocked(user);
18548                return true;
18549            }
18550        }
18551
18552        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18553                && user.getIdentifier() != UserHandle.USER_ALL)) {
18554            // The caller is asking that the package only be deleted for a single
18555            // user.  To do this, we just mark its uninstalled state and delete
18556            // its data. If this is a system app, we only allow this to happen if
18557            // they have set the special DELETE_SYSTEM_APP which requests different
18558            // semantics than normal for uninstalling system apps.
18559            markPackageUninstalledForUserLPw(ps, user);
18560
18561            if (!isSystemApp(ps)) {
18562                // Do not uninstall the APK if an app should be cached
18563                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18564                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18565                    // Other user still have this package installed, so all
18566                    // we need to do is clear this user's data and save that
18567                    // it is uninstalled.
18568                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18569                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18570                        return false;
18571                    }
18572                    scheduleWritePackageRestrictionsLocked(user);
18573                    return true;
18574                } else {
18575                    // We need to set it back to 'installed' so the uninstall
18576                    // broadcasts will be sent correctly.
18577                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18578                    ps.setInstalled(true, user.getIdentifier());
18579                    mSettings.writeKernelMappingLPr(ps);
18580                }
18581            } else {
18582                // This is a system app, so we assume that the
18583                // other users still have this package installed, so all
18584                // we need to do is clear this user's data and save that
18585                // it is uninstalled.
18586                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18587                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18588                    return false;
18589                }
18590                scheduleWritePackageRestrictionsLocked(user);
18591                return true;
18592            }
18593        }
18594
18595        // If we are deleting a composite package for all users, keep track
18596        // of result for each child.
18597        if (ps.childPackageNames != null && outInfo != null) {
18598            synchronized (mPackages) {
18599                final int childCount = ps.childPackageNames.size();
18600                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18601                for (int i = 0; i < childCount; i++) {
18602                    String childPackageName = ps.childPackageNames.get(i);
18603                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18604                    childInfo.removedPackage = childPackageName;
18605                    childInfo.installerPackageName = ps.installerPackageName;
18606                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18607                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18608                    if (childPs != null) {
18609                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18610                    }
18611                }
18612            }
18613        }
18614
18615        boolean ret = false;
18616        if (isSystemApp(ps)) {
18617            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18618            // When an updated system application is deleted we delete the existing resources
18619            // as well and fall back to existing code in system partition
18620            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18621        } else {
18622            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18623            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18624                    outInfo, writeSettings, replacingPackage);
18625        }
18626
18627        // Take a note whether we deleted the package for all users
18628        if (outInfo != null) {
18629            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18630            if (outInfo.removedChildPackages != null) {
18631                synchronized (mPackages) {
18632                    final int childCount = outInfo.removedChildPackages.size();
18633                    for (int i = 0; i < childCount; i++) {
18634                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18635                        if (childInfo != null) {
18636                            childInfo.removedForAllUsers = mPackages.get(
18637                                    childInfo.removedPackage) == null;
18638                        }
18639                    }
18640                }
18641            }
18642            // If we uninstalled an update to a system app there may be some
18643            // child packages that appeared as they are declared in the system
18644            // app but were not declared in the update.
18645            if (isSystemApp(ps)) {
18646                synchronized (mPackages) {
18647                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18648                    final int childCount = (updatedPs.childPackageNames != null)
18649                            ? updatedPs.childPackageNames.size() : 0;
18650                    for (int i = 0; i < childCount; i++) {
18651                        String childPackageName = updatedPs.childPackageNames.get(i);
18652                        if (outInfo.removedChildPackages == null
18653                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18654                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18655                            if (childPs == null) {
18656                                continue;
18657                            }
18658                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18659                            installRes.name = childPackageName;
18660                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18661                            installRes.pkg = mPackages.get(childPackageName);
18662                            installRes.uid = childPs.pkg.applicationInfo.uid;
18663                            if (outInfo.appearedChildPackages == null) {
18664                                outInfo.appearedChildPackages = new ArrayMap<>();
18665                            }
18666                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18667                        }
18668                    }
18669                }
18670            }
18671        }
18672
18673        return ret;
18674    }
18675
18676    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18677        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18678                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18679        for (int nextUserId : userIds) {
18680            if (DEBUG_REMOVE) {
18681                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18682            }
18683            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18684                    false /*installed*/,
18685                    true /*stopped*/,
18686                    true /*notLaunched*/,
18687                    false /*hidden*/,
18688                    false /*suspended*/,
18689                    false /*instantApp*/,
18690                    false /*virtualPreload*/,
18691                    null /*lastDisableAppCaller*/,
18692                    null /*enabledComponents*/,
18693                    null /*disabledComponents*/,
18694                    ps.readUserState(nextUserId).domainVerificationStatus,
18695                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18696                    null /*harmfulAppWarning*/);
18697        }
18698        mSettings.writeKernelMappingLPr(ps);
18699    }
18700
18701    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18702            PackageRemovedInfo outInfo) {
18703        final PackageParser.Package pkg;
18704        synchronized (mPackages) {
18705            pkg = mPackages.get(ps.name);
18706        }
18707
18708        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18709                : new int[] {userId};
18710        for (int nextUserId : userIds) {
18711            if (DEBUG_REMOVE) {
18712                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18713                        + nextUserId);
18714            }
18715
18716            destroyAppDataLIF(pkg, userId,
18717                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18718            destroyAppProfilesLIF(pkg, userId);
18719            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18720            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18721            schedulePackageCleaning(ps.name, nextUserId, false);
18722            synchronized (mPackages) {
18723                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18724                    scheduleWritePackageRestrictionsLocked(nextUserId);
18725                }
18726                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18727            }
18728        }
18729
18730        if (outInfo != null) {
18731            outInfo.removedPackage = ps.name;
18732            outInfo.installerPackageName = ps.installerPackageName;
18733            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18734            outInfo.removedAppId = ps.appId;
18735            outInfo.removedUsers = userIds;
18736            outInfo.broadcastUsers = userIds;
18737        }
18738
18739        return true;
18740    }
18741
18742    private static final class ClearStorageConnection implements ServiceConnection {
18743        IMediaContainerService mContainerService;
18744
18745        @Override
18746        public void onServiceConnected(ComponentName name, IBinder service) {
18747            synchronized (this) {
18748                mContainerService = IMediaContainerService.Stub
18749                        .asInterface(Binder.allowBlocking(service));
18750                notifyAll();
18751            }
18752        }
18753
18754        @Override
18755        public void onServiceDisconnected(ComponentName name) {
18756        }
18757    }
18758
18759    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18760        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18761
18762        final boolean mounted;
18763        if (Environment.isExternalStorageEmulated()) {
18764            mounted = true;
18765        } else {
18766            final String status = Environment.getExternalStorageState();
18767
18768            mounted = status.equals(Environment.MEDIA_MOUNTED)
18769                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18770        }
18771
18772        if (!mounted) {
18773            return;
18774        }
18775
18776        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18777        int[] users;
18778        if (userId == UserHandle.USER_ALL) {
18779            users = sUserManager.getUserIds();
18780        } else {
18781            users = new int[] { userId };
18782        }
18783        final ClearStorageConnection conn = new ClearStorageConnection();
18784        if (mContext.bindServiceAsUser(
18785                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18786            try {
18787                for (int curUser : users) {
18788                    long timeout = SystemClock.uptimeMillis() + 5000;
18789                    synchronized (conn) {
18790                        long now;
18791                        while (conn.mContainerService == null &&
18792                                (now = SystemClock.uptimeMillis()) < timeout) {
18793                            try {
18794                                conn.wait(timeout - now);
18795                            } catch (InterruptedException e) {
18796                            }
18797                        }
18798                    }
18799                    if (conn.mContainerService == null) {
18800                        return;
18801                    }
18802
18803                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18804                    clearDirectory(conn.mContainerService,
18805                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18806                    if (allData) {
18807                        clearDirectory(conn.mContainerService,
18808                                userEnv.buildExternalStorageAppDataDirs(packageName));
18809                        clearDirectory(conn.mContainerService,
18810                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18811                    }
18812                }
18813            } finally {
18814                mContext.unbindService(conn);
18815            }
18816        }
18817    }
18818
18819    @Override
18820    public void clearApplicationProfileData(String packageName) {
18821        enforceSystemOrRoot("Only the system can clear all profile data");
18822
18823        final PackageParser.Package pkg;
18824        synchronized (mPackages) {
18825            pkg = mPackages.get(packageName);
18826        }
18827
18828        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18829            synchronized (mInstallLock) {
18830                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18831            }
18832        }
18833    }
18834
18835    @Override
18836    public void clearApplicationUserData(final String packageName,
18837            final IPackageDataObserver observer, final int userId) {
18838        mContext.enforceCallingOrSelfPermission(
18839                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18840
18841        final int callingUid = Binder.getCallingUid();
18842        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18843                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18844
18845        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18846        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18847        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18848            throw new SecurityException("Cannot clear data for a protected package: "
18849                    + packageName);
18850        }
18851        // Queue up an async operation since the package deletion may take a little while.
18852        mHandler.post(new Runnable() {
18853            public void run() {
18854                mHandler.removeCallbacks(this);
18855                final boolean succeeded;
18856                if (!filterApp) {
18857                    try (PackageFreezer freezer = freezePackage(packageName,
18858                            "clearApplicationUserData")) {
18859                        synchronized (mInstallLock) {
18860                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18861                        }
18862                        clearExternalStorageDataSync(packageName, userId, true);
18863                        synchronized (mPackages) {
18864                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18865                                    packageName, userId);
18866                        }
18867                    }
18868                    if (succeeded) {
18869                        // invoke DeviceStorageMonitor's update method to clear any notifications
18870                        DeviceStorageMonitorInternal dsm = LocalServices
18871                                .getService(DeviceStorageMonitorInternal.class);
18872                        if (dsm != null) {
18873                            dsm.checkMemory();
18874                        }
18875                    }
18876                } else {
18877                    succeeded = false;
18878                }
18879                if (observer != null) {
18880                    try {
18881                        observer.onRemoveCompleted(packageName, succeeded);
18882                    } catch (RemoteException e) {
18883                        Log.i(TAG, "Observer no longer exists.");
18884                    }
18885                } //end if observer
18886            } //end run
18887        });
18888    }
18889
18890    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18891        if (packageName == null) {
18892            Slog.w(TAG, "Attempt to delete null packageName.");
18893            return false;
18894        }
18895
18896        // Try finding details about the requested package
18897        PackageParser.Package pkg;
18898        synchronized (mPackages) {
18899            pkg = mPackages.get(packageName);
18900            if (pkg == null) {
18901                final PackageSetting ps = mSettings.mPackages.get(packageName);
18902                if (ps != null) {
18903                    pkg = ps.pkg;
18904                }
18905            }
18906
18907            if (pkg == null) {
18908                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18909                return false;
18910            }
18911
18912            PackageSetting ps = (PackageSetting) pkg.mExtras;
18913            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18914        }
18915
18916        clearAppDataLIF(pkg, userId,
18917                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18918
18919        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18920        removeKeystoreDataIfNeeded(userId, appId);
18921
18922        UserManagerInternal umInternal = getUserManagerInternal();
18923        final int flags;
18924        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18925            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18926        } else if (umInternal.isUserRunning(userId)) {
18927            flags = StorageManager.FLAG_STORAGE_DE;
18928        } else {
18929            flags = 0;
18930        }
18931        prepareAppDataContentsLIF(pkg, userId, flags);
18932
18933        return true;
18934    }
18935
18936    /**
18937     * Reverts user permission state changes (permissions and flags) in
18938     * all packages for a given user.
18939     *
18940     * @param userId The device user for which to do a reset.
18941     */
18942    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18943        final int packageCount = mPackages.size();
18944        for (int i = 0; i < packageCount; i++) {
18945            PackageParser.Package pkg = mPackages.valueAt(i);
18946            PackageSetting ps = (PackageSetting) pkg.mExtras;
18947            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18948        }
18949    }
18950
18951    private void resetNetworkPolicies(int userId) {
18952        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18953    }
18954
18955    /**
18956     * Reverts user permission state changes (permissions and flags).
18957     *
18958     * @param ps The package for which to reset.
18959     * @param userId The device user for which to do a reset.
18960     */
18961    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18962            final PackageSetting ps, final int userId) {
18963        if (ps.pkg == null) {
18964            return;
18965        }
18966
18967        // These are flags that can change base on user actions.
18968        final int userSettableMask = FLAG_PERMISSION_USER_SET
18969                | FLAG_PERMISSION_USER_FIXED
18970                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18971                | FLAG_PERMISSION_REVIEW_REQUIRED;
18972
18973        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18974                | FLAG_PERMISSION_POLICY_FIXED;
18975
18976        boolean writeInstallPermissions = false;
18977        boolean writeRuntimePermissions = false;
18978
18979        final int permissionCount = ps.pkg.requestedPermissions.size();
18980        for (int i = 0; i < permissionCount; i++) {
18981            final String permName = ps.pkg.requestedPermissions.get(i);
18982            final BasePermission bp =
18983                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
18984            if (bp == null) {
18985                continue;
18986            }
18987
18988            // If shared user we just reset the state to which only this app contributed.
18989            if (ps.sharedUser != null) {
18990                boolean used = false;
18991                final int packageCount = ps.sharedUser.packages.size();
18992                for (int j = 0; j < packageCount; j++) {
18993                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18994                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18995                            && pkg.pkg.requestedPermissions.contains(permName)) {
18996                        used = true;
18997                        break;
18998                    }
18999                }
19000                if (used) {
19001                    continue;
19002                }
19003            }
19004
19005            final PermissionsState permissionsState = ps.getPermissionsState();
19006
19007            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19008
19009            // Always clear the user settable flags.
19010            final boolean hasInstallState =
19011                    permissionsState.getInstallPermissionState(permName) != null;
19012            // If permission review is enabled and this is a legacy app, mark the
19013            // permission as requiring a review as this is the initial state.
19014            int flags = 0;
19015            if (mSettings.mPermissions.mPermissionReviewRequired
19016                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19017                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19018            }
19019            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19020                if (hasInstallState) {
19021                    writeInstallPermissions = true;
19022                } else {
19023                    writeRuntimePermissions = true;
19024                }
19025            }
19026
19027            // Below is only runtime permission handling.
19028            if (!bp.isRuntime()) {
19029                continue;
19030            }
19031
19032            // Never clobber system or policy.
19033            if ((oldFlags & policyOrSystemFlags) != 0) {
19034                continue;
19035            }
19036
19037            // If this permission was granted by default, make sure it is.
19038            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19039                if (permissionsState.grantRuntimePermission(bp, userId)
19040                        != PERMISSION_OPERATION_FAILURE) {
19041                    writeRuntimePermissions = true;
19042                }
19043            // If permission review is enabled the permissions for a legacy apps
19044            // are represented as constantly granted runtime ones, so don't revoke.
19045            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19046                // Otherwise, reset the permission.
19047                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19048                switch (revokeResult) {
19049                    case PERMISSION_OPERATION_SUCCESS:
19050                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19051                        writeRuntimePermissions = true;
19052                        final int appId = ps.appId;
19053                        mHandler.post(new Runnable() {
19054                            @Override
19055                            public void run() {
19056                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19057                            }
19058                        });
19059                    } break;
19060                }
19061            }
19062        }
19063
19064        // Synchronously write as we are taking permissions away.
19065        if (writeRuntimePermissions) {
19066            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19067        }
19068
19069        // Synchronously write as we are taking permissions away.
19070        if (writeInstallPermissions) {
19071            mSettings.writeLPr();
19072        }
19073    }
19074
19075    /**
19076     * Remove entries from the keystore daemon. Will only remove it if the
19077     * {@code appId} is valid.
19078     */
19079    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19080        if (appId < 0) {
19081            return;
19082        }
19083
19084        final KeyStore keyStore = KeyStore.getInstance();
19085        if (keyStore != null) {
19086            if (userId == UserHandle.USER_ALL) {
19087                for (final int individual : sUserManager.getUserIds()) {
19088                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19089                }
19090            } else {
19091                keyStore.clearUid(UserHandle.getUid(userId, appId));
19092            }
19093        } else {
19094            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19095        }
19096    }
19097
19098    @Override
19099    public void deleteApplicationCacheFiles(final String packageName,
19100            final IPackageDataObserver observer) {
19101        final int userId = UserHandle.getCallingUserId();
19102        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19103    }
19104
19105    @Override
19106    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19107            final IPackageDataObserver observer) {
19108        final int callingUid = Binder.getCallingUid();
19109        if (mContext.checkCallingOrSelfPermission(
19110                android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
19111                != PackageManager.PERMISSION_GRANTED) {
19112            // If the caller has the old delete cache permission, silently ignore.  Else throw.
19113            if (mContext.checkCallingOrSelfPermission(
19114                    android.Manifest.permission.DELETE_CACHE_FILES)
19115                    == PackageManager.PERMISSION_GRANTED) {
19116                Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
19117                        android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
19118                        ", silently ignoring");
19119                return;
19120            }
19121            mContext.enforceCallingOrSelfPermission(
19122                    android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
19123        }
19124        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19125                /* requireFullPermission= */ true, /* checkShell= */ false,
19126                "delete application cache files");
19127        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19128                android.Manifest.permission.ACCESS_INSTANT_APPS);
19129
19130        final PackageParser.Package pkg;
19131        synchronized (mPackages) {
19132            pkg = mPackages.get(packageName);
19133        }
19134
19135        // Queue up an async operation since the package deletion may take a little while.
19136        mHandler.post(new Runnable() {
19137            public void run() {
19138                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19139                boolean doClearData = true;
19140                if (ps != null) {
19141                    final boolean targetIsInstantApp =
19142                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19143                    doClearData = !targetIsInstantApp
19144                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19145                }
19146                if (doClearData) {
19147                    synchronized (mInstallLock) {
19148                        final int flags = StorageManager.FLAG_STORAGE_DE
19149                                | StorageManager.FLAG_STORAGE_CE;
19150                        // We're only clearing cache files, so we don't care if the
19151                        // app is unfrozen and still able to run
19152                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19153                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19154                    }
19155                    clearExternalStorageDataSync(packageName, userId, false);
19156                }
19157                if (observer != null) {
19158                    try {
19159                        observer.onRemoveCompleted(packageName, true);
19160                    } catch (RemoteException e) {
19161                        Log.i(TAG, "Observer no longer exists.");
19162                    }
19163                }
19164            }
19165        });
19166    }
19167
19168    @Override
19169    public void getPackageSizeInfo(final String packageName, int userHandle,
19170            final IPackageStatsObserver observer) {
19171        throw new UnsupportedOperationException(
19172                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19173    }
19174
19175    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19176        final PackageSetting ps;
19177        synchronized (mPackages) {
19178            ps = mSettings.mPackages.get(packageName);
19179            if (ps == null) {
19180                Slog.w(TAG, "Failed to find settings for " + packageName);
19181                return false;
19182            }
19183        }
19184
19185        final String[] packageNames = { packageName };
19186        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19187        final String[] codePaths = { ps.codePathString };
19188
19189        try {
19190            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19191                    ps.appId, ceDataInodes, codePaths, stats);
19192
19193            // For now, ignore code size of packages on system partition
19194            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19195                stats.codeSize = 0;
19196            }
19197
19198            // External clients expect these to be tracked separately
19199            stats.dataSize -= stats.cacheSize;
19200
19201        } catch (InstallerException e) {
19202            Slog.w(TAG, String.valueOf(e));
19203            return false;
19204        }
19205
19206        return true;
19207    }
19208
19209    private int getUidTargetSdkVersionLockedLPr(int uid) {
19210        Object obj = mSettings.getUserIdLPr(uid);
19211        if (obj instanceof SharedUserSetting) {
19212            final SharedUserSetting sus = (SharedUserSetting) obj;
19213            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19214            final Iterator<PackageSetting> it = sus.packages.iterator();
19215            while (it.hasNext()) {
19216                final PackageSetting ps = it.next();
19217                if (ps.pkg != null) {
19218                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19219                    if (v < vers) vers = v;
19220                }
19221            }
19222            return vers;
19223        } else if (obj instanceof PackageSetting) {
19224            final PackageSetting ps = (PackageSetting) obj;
19225            if (ps.pkg != null) {
19226                return ps.pkg.applicationInfo.targetSdkVersion;
19227            }
19228        }
19229        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19230    }
19231
19232    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19233        final PackageParser.Package p = mPackages.get(packageName);
19234        if (p != null) {
19235            return p.applicationInfo.targetSdkVersion;
19236        }
19237        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19238    }
19239
19240    @Override
19241    public void addPreferredActivity(IntentFilter filter, int match,
19242            ComponentName[] set, ComponentName activity, int userId) {
19243        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19244                "Adding preferred");
19245    }
19246
19247    private void addPreferredActivityInternal(IntentFilter filter, int match,
19248            ComponentName[] set, ComponentName activity, boolean always, int userId,
19249            String opname) {
19250        // writer
19251        int callingUid = Binder.getCallingUid();
19252        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19253                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19254        if (filter.countActions() == 0) {
19255            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19256            return;
19257        }
19258        synchronized (mPackages) {
19259            if (mContext.checkCallingOrSelfPermission(
19260                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19261                    != PackageManager.PERMISSION_GRANTED) {
19262                if (getUidTargetSdkVersionLockedLPr(callingUid)
19263                        < Build.VERSION_CODES.FROYO) {
19264                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19265                            + callingUid);
19266                    return;
19267                }
19268                mContext.enforceCallingOrSelfPermission(
19269                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19270            }
19271
19272            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19273            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19274                    + userId + ":");
19275            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19276            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19277            scheduleWritePackageRestrictionsLocked(userId);
19278            postPreferredActivityChangedBroadcast(userId);
19279        }
19280    }
19281
19282    private void postPreferredActivityChangedBroadcast(int userId) {
19283        mHandler.post(() -> {
19284            final IActivityManager am = ActivityManager.getService();
19285            if (am == null) {
19286                return;
19287            }
19288
19289            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19290            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19291            try {
19292                am.broadcastIntent(null, intent, null, null,
19293                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19294                        null, false, false, userId);
19295            } catch (RemoteException e) {
19296            }
19297        });
19298    }
19299
19300    @Override
19301    public void replacePreferredActivity(IntentFilter filter, int match,
19302            ComponentName[] set, ComponentName activity, int userId) {
19303        if (filter.countActions() != 1) {
19304            throw new IllegalArgumentException(
19305                    "replacePreferredActivity expects filter to have only 1 action.");
19306        }
19307        if (filter.countDataAuthorities() != 0
19308                || filter.countDataPaths() != 0
19309                || filter.countDataSchemes() > 1
19310                || filter.countDataTypes() != 0) {
19311            throw new IllegalArgumentException(
19312                    "replacePreferredActivity expects filter to have no data authorities, " +
19313                    "paths, or types; and at most one scheme.");
19314        }
19315
19316        final int callingUid = Binder.getCallingUid();
19317        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19318                true /* requireFullPermission */, false /* checkShell */,
19319                "replace preferred activity");
19320        synchronized (mPackages) {
19321            if (mContext.checkCallingOrSelfPermission(
19322                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19323                    != PackageManager.PERMISSION_GRANTED) {
19324                if (getUidTargetSdkVersionLockedLPr(callingUid)
19325                        < Build.VERSION_CODES.FROYO) {
19326                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19327                            + Binder.getCallingUid());
19328                    return;
19329                }
19330                mContext.enforceCallingOrSelfPermission(
19331                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19332            }
19333
19334            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19335            if (pir != null) {
19336                // Get all of the existing entries that exactly match this filter.
19337                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19338                if (existing != null && existing.size() == 1) {
19339                    PreferredActivity cur = existing.get(0);
19340                    if (DEBUG_PREFERRED) {
19341                        Slog.i(TAG, "Checking replace of preferred:");
19342                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19343                        if (!cur.mPref.mAlways) {
19344                            Slog.i(TAG, "  -- CUR; not mAlways!");
19345                        } else {
19346                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19347                            Slog.i(TAG, "  -- CUR: mSet="
19348                                    + Arrays.toString(cur.mPref.mSetComponents));
19349                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19350                            Slog.i(TAG, "  -- NEW: mMatch="
19351                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19352                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19353                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19354                        }
19355                    }
19356                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19357                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19358                            && cur.mPref.sameSet(set)) {
19359                        // Setting the preferred activity to what it happens to be already
19360                        if (DEBUG_PREFERRED) {
19361                            Slog.i(TAG, "Replacing with same preferred activity "
19362                                    + cur.mPref.mShortComponent + " for user "
19363                                    + userId + ":");
19364                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19365                        }
19366                        return;
19367                    }
19368                }
19369
19370                if (existing != null) {
19371                    if (DEBUG_PREFERRED) {
19372                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19373                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19374                    }
19375                    for (int i = 0; i < existing.size(); i++) {
19376                        PreferredActivity pa = existing.get(i);
19377                        if (DEBUG_PREFERRED) {
19378                            Slog.i(TAG, "Removing existing preferred activity "
19379                                    + pa.mPref.mComponent + ":");
19380                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19381                        }
19382                        pir.removeFilter(pa);
19383                    }
19384                }
19385            }
19386            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19387                    "Replacing preferred");
19388        }
19389    }
19390
19391    @Override
19392    public void clearPackagePreferredActivities(String packageName) {
19393        final int callingUid = Binder.getCallingUid();
19394        if (getInstantAppPackageName(callingUid) != null) {
19395            return;
19396        }
19397        // writer
19398        synchronized (mPackages) {
19399            PackageParser.Package pkg = mPackages.get(packageName);
19400            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19401                if (mContext.checkCallingOrSelfPermission(
19402                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19403                        != PackageManager.PERMISSION_GRANTED) {
19404                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19405                            < Build.VERSION_CODES.FROYO) {
19406                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19407                                + callingUid);
19408                        return;
19409                    }
19410                    mContext.enforceCallingOrSelfPermission(
19411                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19412                }
19413            }
19414            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19415            if (ps != null
19416                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19417                return;
19418            }
19419            int user = UserHandle.getCallingUserId();
19420            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19421                scheduleWritePackageRestrictionsLocked(user);
19422            }
19423        }
19424    }
19425
19426    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19427    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19428        ArrayList<PreferredActivity> removed = null;
19429        boolean changed = false;
19430        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19431            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19432            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19433            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19434                continue;
19435            }
19436            Iterator<PreferredActivity> it = pir.filterIterator();
19437            while (it.hasNext()) {
19438                PreferredActivity pa = it.next();
19439                // Mark entry for removal only if it matches the package name
19440                // and the entry is of type "always".
19441                if (packageName == null ||
19442                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19443                                && pa.mPref.mAlways)) {
19444                    if (removed == null) {
19445                        removed = new ArrayList<PreferredActivity>();
19446                    }
19447                    removed.add(pa);
19448                }
19449            }
19450            if (removed != null) {
19451                for (int j=0; j<removed.size(); j++) {
19452                    PreferredActivity pa = removed.get(j);
19453                    pir.removeFilter(pa);
19454                }
19455                changed = true;
19456            }
19457        }
19458        if (changed) {
19459            postPreferredActivityChangedBroadcast(userId);
19460        }
19461        return changed;
19462    }
19463
19464    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19465    private void clearIntentFilterVerificationsLPw(int userId) {
19466        final int packageCount = mPackages.size();
19467        for (int i = 0; i < packageCount; i++) {
19468            PackageParser.Package pkg = mPackages.valueAt(i);
19469            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19470        }
19471    }
19472
19473    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19474    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19475        if (userId == UserHandle.USER_ALL) {
19476            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19477                    sUserManager.getUserIds())) {
19478                for (int oneUserId : sUserManager.getUserIds()) {
19479                    scheduleWritePackageRestrictionsLocked(oneUserId);
19480                }
19481            }
19482        } else {
19483            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19484                scheduleWritePackageRestrictionsLocked(userId);
19485            }
19486        }
19487    }
19488
19489    /** Clears state for all users, and touches intent filter verification policy */
19490    void clearDefaultBrowserIfNeeded(String packageName) {
19491        for (int oneUserId : sUserManager.getUserIds()) {
19492            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19493        }
19494    }
19495
19496    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19497        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19498        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19499            if (packageName.equals(defaultBrowserPackageName)) {
19500                setDefaultBrowserPackageName(null, userId);
19501            }
19502        }
19503    }
19504
19505    @Override
19506    public void resetApplicationPreferences(int userId) {
19507        mContext.enforceCallingOrSelfPermission(
19508                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19509        final long identity = Binder.clearCallingIdentity();
19510        // writer
19511        try {
19512            synchronized (mPackages) {
19513                clearPackagePreferredActivitiesLPw(null, userId);
19514                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19515                // TODO: We have to reset the default SMS and Phone. This requires
19516                // significant refactoring to keep all default apps in the package
19517                // manager (cleaner but more work) or have the services provide
19518                // callbacks to the package manager to request a default app reset.
19519                applyFactoryDefaultBrowserLPw(userId);
19520                clearIntentFilterVerificationsLPw(userId);
19521                primeDomainVerificationsLPw(userId);
19522                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19523                scheduleWritePackageRestrictionsLocked(userId);
19524            }
19525            resetNetworkPolicies(userId);
19526        } finally {
19527            Binder.restoreCallingIdentity(identity);
19528        }
19529    }
19530
19531    @Override
19532    public int getPreferredActivities(List<IntentFilter> outFilters,
19533            List<ComponentName> outActivities, String packageName) {
19534        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19535            return 0;
19536        }
19537        int num = 0;
19538        final int userId = UserHandle.getCallingUserId();
19539        // reader
19540        synchronized (mPackages) {
19541            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19542            if (pir != null) {
19543                final Iterator<PreferredActivity> it = pir.filterIterator();
19544                while (it.hasNext()) {
19545                    final PreferredActivity pa = it.next();
19546                    if (packageName == null
19547                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19548                                    && pa.mPref.mAlways)) {
19549                        if (outFilters != null) {
19550                            outFilters.add(new IntentFilter(pa));
19551                        }
19552                        if (outActivities != null) {
19553                            outActivities.add(pa.mPref.mComponent);
19554                        }
19555                    }
19556                }
19557            }
19558        }
19559
19560        return num;
19561    }
19562
19563    @Override
19564    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19565            int userId) {
19566        int callingUid = Binder.getCallingUid();
19567        if (callingUid != Process.SYSTEM_UID) {
19568            throw new SecurityException(
19569                    "addPersistentPreferredActivity can only be run by the system");
19570        }
19571        if (filter.countActions() == 0) {
19572            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19573            return;
19574        }
19575        synchronized (mPackages) {
19576            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19577                    ":");
19578            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19579            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19580                    new PersistentPreferredActivity(filter, activity));
19581            scheduleWritePackageRestrictionsLocked(userId);
19582            postPreferredActivityChangedBroadcast(userId);
19583        }
19584    }
19585
19586    @Override
19587    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19588        int callingUid = Binder.getCallingUid();
19589        if (callingUid != Process.SYSTEM_UID) {
19590            throw new SecurityException(
19591                    "clearPackagePersistentPreferredActivities can only be run by the system");
19592        }
19593        ArrayList<PersistentPreferredActivity> removed = null;
19594        boolean changed = false;
19595        synchronized (mPackages) {
19596            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19597                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19598                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19599                        .valueAt(i);
19600                if (userId != thisUserId) {
19601                    continue;
19602                }
19603                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19604                while (it.hasNext()) {
19605                    PersistentPreferredActivity ppa = it.next();
19606                    // Mark entry for removal only if it matches the package name.
19607                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19608                        if (removed == null) {
19609                            removed = new ArrayList<PersistentPreferredActivity>();
19610                        }
19611                        removed.add(ppa);
19612                    }
19613                }
19614                if (removed != null) {
19615                    for (int j=0; j<removed.size(); j++) {
19616                        PersistentPreferredActivity ppa = removed.get(j);
19617                        ppir.removeFilter(ppa);
19618                    }
19619                    changed = true;
19620                }
19621            }
19622
19623            if (changed) {
19624                scheduleWritePackageRestrictionsLocked(userId);
19625                postPreferredActivityChangedBroadcast(userId);
19626            }
19627        }
19628    }
19629
19630    /**
19631     * Common machinery for picking apart a restored XML blob and passing
19632     * it to a caller-supplied functor to be applied to the running system.
19633     */
19634    private void restoreFromXml(XmlPullParser parser, int userId,
19635            String expectedStartTag, BlobXmlRestorer functor)
19636            throws IOException, XmlPullParserException {
19637        int type;
19638        while ((type = parser.next()) != XmlPullParser.START_TAG
19639                && type != XmlPullParser.END_DOCUMENT) {
19640        }
19641        if (type != XmlPullParser.START_TAG) {
19642            // oops didn't find a start tag?!
19643            if (DEBUG_BACKUP) {
19644                Slog.e(TAG, "Didn't find start tag during restore");
19645            }
19646            return;
19647        }
19648Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19649        // this is supposed to be TAG_PREFERRED_BACKUP
19650        if (!expectedStartTag.equals(parser.getName())) {
19651            if (DEBUG_BACKUP) {
19652                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19653            }
19654            return;
19655        }
19656
19657        // skip interfering stuff, then we're aligned with the backing implementation
19658        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19659Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19660        functor.apply(parser, userId);
19661    }
19662
19663    private interface BlobXmlRestorer {
19664        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19665    }
19666
19667    /**
19668     * Non-Binder method, support for the backup/restore mechanism: write the
19669     * full set of preferred activities in its canonical XML format.  Returns the
19670     * XML output as a byte array, or null if there is none.
19671     */
19672    @Override
19673    public byte[] getPreferredActivityBackup(int userId) {
19674        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19675            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19676        }
19677
19678        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19679        try {
19680            final XmlSerializer serializer = new FastXmlSerializer();
19681            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19682            serializer.startDocument(null, true);
19683            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19684
19685            synchronized (mPackages) {
19686                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19687            }
19688
19689            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19690            serializer.endDocument();
19691            serializer.flush();
19692        } catch (Exception e) {
19693            if (DEBUG_BACKUP) {
19694                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19695            }
19696            return null;
19697        }
19698
19699        return dataStream.toByteArray();
19700    }
19701
19702    @Override
19703    public void restorePreferredActivities(byte[] backup, int userId) {
19704        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19705            throw new SecurityException("Only the system may call restorePreferredActivities()");
19706        }
19707
19708        try {
19709            final XmlPullParser parser = Xml.newPullParser();
19710            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19711            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19712                    new BlobXmlRestorer() {
19713                        @Override
19714                        public void apply(XmlPullParser parser, int userId)
19715                                throws XmlPullParserException, IOException {
19716                            synchronized (mPackages) {
19717                                mSettings.readPreferredActivitiesLPw(parser, userId);
19718                            }
19719                        }
19720                    } );
19721        } catch (Exception e) {
19722            if (DEBUG_BACKUP) {
19723                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19724            }
19725        }
19726    }
19727
19728    /**
19729     * Non-Binder method, support for the backup/restore mechanism: write the
19730     * default browser (etc) settings in its canonical XML format.  Returns the default
19731     * browser XML representation as a byte array, or null if there is none.
19732     */
19733    @Override
19734    public byte[] getDefaultAppsBackup(int userId) {
19735        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19736            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19737        }
19738
19739        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19740        try {
19741            final XmlSerializer serializer = new FastXmlSerializer();
19742            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19743            serializer.startDocument(null, true);
19744            serializer.startTag(null, TAG_DEFAULT_APPS);
19745
19746            synchronized (mPackages) {
19747                mSettings.writeDefaultAppsLPr(serializer, userId);
19748            }
19749
19750            serializer.endTag(null, TAG_DEFAULT_APPS);
19751            serializer.endDocument();
19752            serializer.flush();
19753        } catch (Exception e) {
19754            if (DEBUG_BACKUP) {
19755                Slog.e(TAG, "Unable to write default apps for backup", e);
19756            }
19757            return null;
19758        }
19759
19760        return dataStream.toByteArray();
19761    }
19762
19763    @Override
19764    public void restoreDefaultApps(byte[] backup, int userId) {
19765        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19766            throw new SecurityException("Only the system may call restoreDefaultApps()");
19767        }
19768
19769        try {
19770            final XmlPullParser parser = Xml.newPullParser();
19771            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19772            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19773                    new BlobXmlRestorer() {
19774                        @Override
19775                        public void apply(XmlPullParser parser, int userId)
19776                                throws XmlPullParserException, IOException {
19777                            synchronized (mPackages) {
19778                                mSettings.readDefaultAppsLPw(parser, userId);
19779                            }
19780                        }
19781                    } );
19782        } catch (Exception e) {
19783            if (DEBUG_BACKUP) {
19784                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19785            }
19786        }
19787    }
19788
19789    @Override
19790    public byte[] getIntentFilterVerificationBackup(int userId) {
19791        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19792            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19793        }
19794
19795        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19796        try {
19797            final XmlSerializer serializer = new FastXmlSerializer();
19798            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19799            serializer.startDocument(null, true);
19800            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19801
19802            synchronized (mPackages) {
19803                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19804            }
19805
19806            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19807            serializer.endDocument();
19808            serializer.flush();
19809        } catch (Exception e) {
19810            if (DEBUG_BACKUP) {
19811                Slog.e(TAG, "Unable to write default apps for backup", e);
19812            }
19813            return null;
19814        }
19815
19816        return dataStream.toByteArray();
19817    }
19818
19819    @Override
19820    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19821        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19822            throw new SecurityException("Only the system may call restorePreferredActivities()");
19823        }
19824
19825        try {
19826            final XmlPullParser parser = Xml.newPullParser();
19827            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19828            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19829                    new BlobXmlRestorer() {
19830                        @Override
19831                        public void apply(XmlPullParser parser, int userId)
19832                                throws XmlPullParserException, IOException {
19833                            synchronized (mPackages) {
19834                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19835                                mSettings.writeLPr();
19836                            }
19837                        }
19838                    } );
19839        } catch (Exception e) {
19840            if (DEBUG_BACKUP) {
19841                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19842            }
19843        }
19844    }
19845
19846    @Override
19847    public byte[] getPermissionGrantBackup(int userId) {
19848        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19849            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19850        }
19851
19852        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19853        try {
19854            final XmlSerializer serializer = new FastXmlSerializer();
19855            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19856            serializer.startDocument(null, true);
19857            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19858
19859            synchronized (mPackages) {
19860                serializeRuntimePermissionGrantsLPr(serializer, userId);
19861            }
19862
19863            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19864            serializer.endDocument();
19865            serializer.flush();
19866        } catch (Exception e) {
19867            if (DEBUG_BACKUP) {
19868                Slog.e(TAG, "Unable to write default apps for backup", e);
19869            }
19870            return null;
19871        }
19872
19873        return dataStream.toByteArray();
19874    }
19875
19876    @Override
19877    public void restorePermissionGrants(byte[] backup, int userId) {
19878        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19879            throw new SecurityException("Only the system may call restorePermissionGrants()");
19880        }
19881
19882        try {
19883            final XmlPullParser parser = Xml.newPullParser();
19884            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19885            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19886                    new BlobXmlRestorer() {
19887                        @Override
19888                        public void apply(XmlPullParser parser, int userId)
19889                                throws XmlPullParserException, IOException {
19890                            synchronized (mPackages) {
19891                                processRestoredPermissionGrantsLPr(parser, userId);
19892                            }
19893                        }
19894                    } );
19895        } catch (Exception e) {
19896            if (DEBUG_BACKUP) {
19897                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19898            }
19899        }
19900    }
19901
19902    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19903            throws IOException {
19904        serializer.startTag(null, TAG_ALL_GRANTS);
19905
19906        final int N = mSettings.mPackages.size();
19907        for (int i = 0; i < N; i++) {
19908            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19909            boolean pkgGrantsKnown = false;
19910
19911            PermissionsState packagePerms = ps.getPermissionsState();
19912
19913            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19914                final int grantFlags = state.getFlags();
19915                // only look at grants that are not system/policy fixed
19916                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19917                    final boolean isGranted = state.isGranted();
19918                    // And only back up the user-twiddled state bits
19919                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19920                        final String packageName = mSettings.mPackages.keyAt(i);
19921                        if (!pkgGrantsKnown) {
19922                            serializer.startTag(null, TAG_GRANT);
19923                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19924                            pkgGrantsKnown = true;
19925                        }
19926
19927                        final boolean userSet =
19928                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19929                        final boolean userFixed =
19930                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19931                        final boolean revoke =
19932                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19933
19934                        serializer.startTag(null, TAG_PERMISSION);
19935                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19936                        if (isGranted) {
19937                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19938                        }
19939                        if (userSet) {
19940                            serializer.attribute(null, ATTR_USER_SET, "true");
19941                        }
19942                        if (userFixed) {
19943                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19944                        }
19945                        if (revoke) {
19946                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19947                        }
19948                        serializer.endTag(null, TAG_PERMISSION);
19949                    }
19950                }
19951            }
19952
19953            if (pkgGrantsKnown) {
19954                serializer.endTag(null, TAG_GRANT);
19955            }
19956        }
19957
19958        serializer.endTag(null, TAG_ALL_GRANTS);
19959    }
19960
19961    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19962            throws XmlPullParserException, IOException {
19963        String pkgName = null;
19964        int outerDepth = parser.getDepth();
19965        int type;
19966        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19967                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19968            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19969                continue;
19970            }
19971
19972            final String tagName = parser.getName();
19973            if (tagName.equals(TAG_GRANT)) {
19974                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19975                if (DEBUG_BACKUP) {
19976                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19977                }
19978            } else if (tagName.equals(TAG_PERMISSION)) {
19979
19980                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19981                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19982
19983                int newFlagSet = 0;
19984                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19985                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19986                }
19987                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19988                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19989                }
19990                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19991                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19992                }
19993                if (DEBUG_BACKUP) {
19994                    Slog.v(TAG, "  + Restoring grant:"
19995                            + " pkg=" + pkgName
19996                            + " perm=" + permName
19997                            + " granted=" + isGranted
19998                            + " bits=0x" + Integer.toHexString(newFlagSet));
19999                }
20000                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20001                if (ps != null) {
20002                    // Already installed so we apply the grant immediately
20003                    if (DEBUG_BACKUP) {
20004                        Slog.v(TAG, "        + already installed; applying");
20005                    }
20006                    PermissionsState perms = ps.getPermissionsState();
20007                    BasePermission bp =
20008                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20009                    if (bp != null) {
20010                        if (isGranted) {
20011                            perms.grantRuntimePermission(bp, userId);
20012                        }
20013                        if (newFlagSet != 0) {
20014                            perms.updatePermissionFlags(
20015                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20016                        }
20017                    }
20018                } else {
20019                    // Need to wait for post-restore install to apply the grant
20020                    if (DEBUG_BACKUP) {
20021                        Slog.v(TAG, "        - not yet installed; saving for later");
20022                    }
20023                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20024                            isGranted, newFlagSet, userId);
20025                }
20026            } else {
20027                PackageManagerService.reportSettingsProblem(Log.WARN,
20028                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20029                XmlUtils.skipCurrentTag(parser);
20030            }
20031        }
20032
20033        scheduleWriteSettingsLocked();
20034        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20035    }
20036
20037    @Override
20038    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20039            int sourceUserId, int targetUserId, int flags) {
20040        mContext.enforceCallingOrSelfPermission(
20041                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20042        int callingUid = Binder.getCallingUid();
20043        enforceOwnerRights(ownerPackage, callingUid);
20044        PackageManagerServiceUtils.enforceShellRestriction(
20045                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20046        if (intentFilter.countActions() == 0) {
20047            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20048            return;
20049        }
20050        synchronized (mPackages) {
20051            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20052                    ownerPackage, targetUserId, flags);
20053            CrossProfileIntentResolver resolver =
20054                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20055            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20056            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20057            if (existing != null) {
20058                int size = existing.size();
20059                for (int i = 0; i < size; i++) {
20060                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20061                        return;
20062                    }
20063                }
20064            }
20065            resolver.addFilter(newFilter);
20066            scheduleWritePackageRestrictionsLocked(sourceUserId);
20067        }
20068    }
20069
20070    @Override
20071    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20072        mContext.enforceCallingOrSelfPermission(
20073                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20074        final int callingUid = Binder.getCallingUid();
20075        enforceOwnerRights(ownerPackage, callingUid);
20076        PackageManagerServiceUtils.enforceShellRestriction(
20077                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20078        synchronized (mPackages) {
20079            CrossProfileIntentResolver resolver =
20080                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20081            ArraySet<CrossProfileIntentFilter> set =
20082                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20083            for (CrossProfileIntentFilter filter : set) {
20084                if (filter.getOwnerPackage().equals(ownerPackage)) {
20085                    resolver.removeFilter(filter);
20086                }
20087            }
20088            scheduleWritePackageRestrictionsLocked(sourceUserId);
20089        }
20090    }
20091
20092    // Enforcing that callingUid is owning pkg on userId
20093    private void enforceOwnerRights(String pkg, int callingUid) {
20094        // The system owns everything.
20095        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20096            return;
20097        }
20098        final int callingUserId = UserHandle.getUserId(callingUid);
20099        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20100        if (pi == null) {
20101            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20102                    + callingUserId);
20103        }
20104        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20105            throw new SecurityException("Calling uid " + callingUid
20106                    + " does not own package " + pkg);
20107        }
20108    }
20109
20110    @Override
20111    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20112        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20113            return null;
20114        }
20115        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20116    }
20117
20118    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20119        UserManagerService ums = UserManagerService.getInstance();
20120        if (ums != null) {
20121            final UserInfo parent = ums.getProfileParent(userId);
20122            final int launcherUid = (parent != null) ? parent.id : userId;
20123            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20124            if (launcherComponent != null) {
20125                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20126                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20127                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20128                        .setPackage(launcherComponent.getPackageName());
20129                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20130            }
20131        }
20132    }
20133
20134    /**
20135     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20136     * then reports the most likely home activity or null if there are more than one.
20137     */
20138    private ComponentName getDefaultHomeActivity(int userId) {
20139        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20140        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20141        if (cn != null) {
20142            return cn;
20143        }
20144
20145        // Find the launcher with the highest priority and return that component if there are no
20146        // other home activity with the same priority.
20147        int lastPriority = Integer.MIN_VALUE;
20148        ComponentName lastComponent = null;
20149        final int size = allHomeCandidates.size();
20150        for (int i = 0; i < size; i++) {
20151            final ResolveInfo ri = allHomeCandidates.get(i);
20152            if (ri.priority > lastPriority) {
20153                lastComponent = ri.activityInfo.getComponentName();
20154                lastPriority = ri.priority;
20155            } else if (ri.priority == lastPriority) {
20156                // Two components found with same priority.
20157                lastComponent = null;
20158            }
20159        }
20160        return lastComponent;
20161    }
20162
20163    private Intent getHomeIntent() {
20164        Intent intent = new Intent(Intent.ACTION_MAIN);
20165        intent.addCategory(Intent.CATEGORY_HOME);
20166        intent.addCategory(Intent.CATEGORY_DEFAULT);
20167        return intent;
20168    }
20169
20170    private IntentFilter getHomeFilter() {
20171        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20172        filter.addCategory(Intent.CATEGORY_HOME);
20173        filter.addCategory(Intent.CATEGORY_DEFAULT);
20174        return filter;
20175    }
20176
20177    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20178            int userId) {
20179        Intent intent  = getHomeIntent();
20180        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20181                PackageManager.GET_META_DATA, userId);
20182        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20183                true, false, false, userId);
20184
20185        allHomeCandidates.clear();
20186        if (list != null) {
20187            for (ResolveInfo ri : list) {
20188                allHomeCandidates.add(ri);
20189            }
20190        }
20191        return (preferred == null || preferred.activityInfo == null)
20192                ? null
20193                : new ComponentName(preferred.activityInfo.packageName,
20194                        preferred.activityInfo.name);
20195    }
20196
20197    @Override
20198    public void setHomeActivity(ComponentName comp, int userId) {
20199        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20200            return;
20201        }
20202        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20203        getHomeActivitiesAsUser(homeActivities, userId);
20204
20205        boolean found = false;
20206
20207        final int size = homeActivities.size();
20208        final ComponentName[] set = new ComponentName[size];
20209        for (int i = 0; i < size; i++) {
20210            final ResolveInfo candidate = homeActivities.get(i);
20211            final ActivityInfo info = candidate.activityInfo;
20212            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20213            set[i] = activityName;
20214            if (!found && activityName.equals(comp)) {
20215                found = true;
20216            }
20217        }
20218        if (!found) {
20219            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20220                    + userId);
20221        }
20222        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20223                set, comp, userId);
20224    }
20225
20226    private @Nullable String getSetupWizardPackageName() {
20227        final Intent intent = new Intent(Intent.ACTION_MAIN);
20228        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20229
20230        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20231                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20232                        | MATCH_DISABLED_COMPONENTS,
20233                UserHandle.myUserId());
20234        if (matches.size() == 1) {
20235            return matches.get(0).getComponentInfo().packageName;
20236        } else {
20237            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20238                    + ": matches=" + matches);
20239            return null;
20240        }
20241    }
20242
20243    private @Nullable String getStorageManagerPackageName() {
20244        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20245
20246        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20247                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20248                        | MATCH_DISABLED_COMPONENTS,
20249                UserHandle.myUserId());
20250        if (matches.size() == 1) {
20251            return matches.get(0).getComponentInfo().packageName;
20252        } else {
20253            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20254                    + matches.size() + ": matches=" + matches);
20255            return null;
20256        }
20257    }
20258
20259    @Override
20260    public String getSystemTextClassifierPackageName() {
20261        return mContext.getString(R.string.config_defaultTextClassifierPackage);
20262    }
20263
20264    @Override
20265    public void setApplicationEnabledSetting(String appPackageName,
20266            int newState, int flags, int userId, String callingPackage) {
20267        if (!sUserManager.exists(userId)) return;
20268        if (callingPackage == null) {
20269            callingPackage = Integer.toString(Binder.getCallingUid());
20270        }
20271        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20272    }
20273
20274    @Override
20275    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20276        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20277        synchronized (mPackages) {
20278            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20279            if (pkgSetting != null) {
20280                pkgSetting.setUpdateAvailable(updateAvailable);
20281            }
20282        }
20283    }
20284
20285    @Override
20286    public void setComponentEnabledSetting(ComponentName componentName,
20287            int newState, int flags, int userId) {
20288        if (!sUserManager.exists(userId)) return;
20289        setEnabledSetting(componentName.getPackageName(),
20290                componentName.getClassName(), newState, flags, userId, null);
20291    }
20292
20293    private void setEnabledSetting(final String packageName, String className, int newState,
20294            final int flags, int userId, String callingPackage) {
20295        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20296              || newState == COMPONENT_ENABLED_STATE_ENABLED
20297              || newState == COMPONENT_ENABLED_STATE_DISABLED
20298              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20299              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20300            throw new IllegalArgumentException("Invalid new component state: "
20301                    + newState);
20302        }
20303        PackageSetting pkgSetting;
20304        final int callingUid = Binder.getCallingUid();
20305        final int permission;
20306        if (callingUid == Process.SYSTEM_UID) {
20307            permission = PackageManager.PERMISSION_GRANTED;
20308        } else {
20309            permission = mContext.checkCallingOrSelfPermission(
20310                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20311        }
20312        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20313                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20314        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20315        boolean sendNow = false;
20316        boolean isApp = (className == null);
20317        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20318        String componentName = isApp ? packageName : className;
20319        int packageUid = -1;
20320        ArrayList<String> components;
20321
20322        // reader
20323        synchronized (mPackages) {
20324            pkgSetting = mSettings.mPackages.get(packageName);
20325            if (pkgSetting == null) {
20326                if (!isCallerInstantApp) {
20327                    if (className == null) {
20328                        throw new IllegalArgumentException("Unknown package: " + packageName);
20329                    }
20330                    throw new IllegalArgumentException(
20331                            "Unknown component: " + packageName + "/" + className);
20332                } else {
20333                    // throw SecurityException to prevent leaking package information
20334                    throw new SecurityException(
20335                            "Attempt to change component state; "
20336                            + "pid=" + Binder.getCallingPid()
20337                            + ", uid=" + callingUid
20338                            + (className == null
20339                                    ? ", package=" + packageName
20340                                    : ", component=" + packageName + "/" + className));
20341                }
20342            }
20343        }
20344
20345        // Limit who can change which apps
20346        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20347            // Don't allow apps that don't have permission to modify other apps
20348            if (!allowedByPermission
20349                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20350                throw new SecurityException(
20351                        "Attempt to change component state; "
20352                        + "pid=" + Binder.getCallingPid()
20353                        + ", uid=" + callingUid
20354                        + (className == null
20355                                ? ", package=" + packageName
20356                                : ", component=" + packageName + "/" + className));
20357            }
20358            // Don't allow changing protected packages.
20359            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20360                throw new SecurityException("Cannot disable a protected package: " + packageName);
20361            }
20362        }
20363
20364        synchronized (mPackages) {
20365            if (callingUid == Process.SHELL_UID
20366                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20367                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20368                // unless it is a test package.
20369                int oldState = pkgSetting.getEnabled(userId);
20370                if (className == null
20371                        &&
20372                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20373                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20374                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20375                        &&
20376                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20377                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20378                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20379                    // ok
20380                } else {
20381                    throw new SecurityException(
20382                            "Shell cannot change component state for " + packageName + "/"
20383                                    + className + " to " + newState);
20384                }
20385            }
20386        }
20387        if (className == null) {
20388            // We're dealing with an application/package level state change
20389            synchronized (mPackages) {
20390                if (pkgSetting.getEnabled(userId) == newState) {
20391                    // Nothing to do
20392                    return;
20393                }
20394            }
20395            // If we're enabling a system stub, there's a little more work to do.
20396            // Prior to enabling the package, we need to decompress the APK(s) to the
20397            // data partition and then replace the version on the system partition.
20398            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20399            final boolean isSystemStub = deletedPkg.isStub
20400                    && deletedPkg.isSystem();
20401            if (isSystemStub
20402                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20403                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20404                final File codePath = decompressPackage(deletedPkg);
20405                if (codePath == null) {
20406                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20407                    return;
20408                }
20409                // TODO remove direct parsing of the package object during internal cleanup
20410                // of scan package
20411                // We need to call parse directly here for no other reason than we need
20412                // the new package in order to disable the old one [we use the information
20413                // for some internal optimization to optionally create a new package setting
20414                // object on replace]. However, we can't get the package from the scan
20415                // because the scan modifies live structures and we need to remove the
20416                // old [system] package from the system before a scan can be attempted.
20417                // Once scan is indempotent we can remove this parse and use the package
20418                // object we scanned, prior to adding it to package settings.
20419                final PackageParser pp = new PackageParser();
20420                pp.setSeparateProcesses(mSeparateProcesses);
20421                pp.setDisplayMetrics(mMetrics);
20422                pp.setCallback(mPackageParserCallback);
20423                final PackageParser.Package tmpPkg;
20424                try {
20425                    final @ParseFlags int parseFlags = mDefParseFlags
20426                            | PackageParser.PARSE_MUST_BE_APK
20427                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20428                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20429                } catch (PackageParserException e) {
20430                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20431                    return;
20432                }
20433                synchronized (mInstallLock) {
20434                    // Disable the stub and remove any package entries
20435                    removePackageLI(deletedPkg, true);
20436                    synchronized (mPackages) {
20437                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20438                    }
20439                    final PackageParser.Package pkg;
20440                    try (PackageFreezer freezer =
20441                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20442                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20443                                | PackageParser.PARSE_ENFORCE_CODE;
20444                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20445                                0 /*currentTime*/, null /*user*/);
20446                        prepareAppDataAfterInstallLIF(pkg);
20447                        synchronized (mPackages) {
20448                            try {
20449                                updateSharedLibrariesLPr(pkg, null);
20450                            } catch (PackageManagerException e) {
20451                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20452                            }
20453                            mPermissionManager.updatePermissions(
20454                                    pkg.packageName, pkg, true, mPackages.values(),
20455                                    mPermissionCallback);
20456                            mSettings.writeLPr();
20457                        }
20458                    } catch (PackageManagerException e) {
20459                        // Whoops! Something went wrong; try to roll back to the stub
20460                        Slog.w(TAG, "Failed to install compressed system package:"
20461                                + pkgSetting.name, e);
20462                        // Remove the failed install
20463                        removeCodePathLI(codePath);
20464
20465                        // Install the system package
20466                        try (PackageFreezer freezer =
20467                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20468                            synchronized (mPackages) {
20469                                // NOTE: The system package always needs to be enabled; even
20470                                // if it's for a compressed stub. If we don't, installing the
20471                                // system package fails during scan [scanning checks the disabled
20472                                // packages]. We will reverse this later, after we've "installed"
20473                                // the stub.
20474                                // This leaves us in a fragile state; the stub should never be
20475                                // enabled, so, cross your fingers and hope nothing goes wrong
20476                                // until we can disable the package later.
20477                                enableSystemPackageLPw(deletedPkg);
20478                            }
20479                            installPackageFromSystemLIF(deletedPkg.codePath,
20480                                    false /*isPrivileged*/, null /*allUserHandles*/,
20481                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20482                                    true /*writeSettings*/);
20483                        } catch (PackageManagerException pme) {
20484                            Slog.w(TAG, "Failed to restore system package:"
20485                                    + deletedPkg.packageName, pme);
20486                        } finally {
20487                            synchronized (mPackages) {
20488                                mSettings.disableSystemPackageLPw(
20489                                        deletedPkg.packageName, true /*replaced*/);
20490                                mSettings.writeLPr();
20491                            }
20492                        }
20493                        return;
20494                    }
20495                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20496                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20497                    mDexManager.notifyPackageUpdated(pkg.packageName,
20498                            pkg.baseCodePath, pkg.splitCodePaths);
20499                }
20500            }
20501            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20502                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20503                // Don't care about who enables an app.
20504                callingPackage = null;
20505            }
20506            synchronized (mPackages) {
20507                pkgSetting.setEnabled(newState, userId, callingPackage);
20508            }
20509        } else {
20510            synchronized (mPackages) {
20511                // We're dealing with a component level state change
20512                // First, verify that this is a valid class name.
20513                PackageParser.Package pkg = pkgSetting.pkg;
20514                if (pkg == null || !pkg.hasComponentClassName(className)) {
20515                    if (pkg != null &&
20516                            pkg.applicationInfo.targetSdkVersion >=
20517                                    Build.VERSION_CODES.JELLY_BEAN) {
20518                        throw new IllegalArgumentException("Component class " + className
20519                                + " does not exist in " + packageName);
20520                    } else {
20521                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20522                                + className + " does not exist in " + packageName);
20523                    }
20524                }
20525                switch (newState) {
20526                    case COMPONENT_ENABLED_STATE_ENABLED:
20527                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20528                            return;
20529                        }
20530                        break;
20531                    case COMPONENT_ENABLED_STATE_DISABLED:
20532                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20533                            return;
20534                        }
20535                        break;
20536                    case COMPONENT_ENABLED_STATE_DEFAULT:
20537                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20538                            return;
20539                        }
20540                        break;
20541                    default:
20542                        Slog.e(TAG, "Invalid new component state: " + newState);
20543                        return;
20544                }
20545            }
20546        }
20547        synchronized (mPackages) {
20548            scheduleWritePackageRestrictionsLocked(userId);
20549            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20550            final long callingId = Binder.clearCallingIdentity();
20551            try {
20552                updateInstantAppInstallerLocked(packageName);
20553            } finally {
20554                Binder.restoreCallingIdentity(callingId);
20555            }
20556            components = mPendingBroadcasts.get(userId, packageName);
20557            final boolean newPackage = components == null;
20558            if (newPackage) {
20559                components = new ArrayList<String>();
20560            }
20561            if (!components.contains(componentName)) {
20562                components.add(componentName);
20563            }
20564            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20565                sendNow = true;
20566                // Purge entry from pending broadcast list if another one exists already
20567                // since we are sending one right away.
20568                mPendingBroadcasts.remove(userId, packageName);
20569            } else {
20570                if (newPackage) {
20571                    mPendingBroadcasts.put(userId, packageName, components);
20572                }
20573                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20574                    // Schedule a message
20575                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20576                }
20577            }
20578        }
20579
20580        long callingId = Binder.clearCallingIdentity();
20581        try {
20582            if (sendNow) {
20583                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20584                sendPackageChangedBroadcast(packageName,
20585                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20586            }
20587        } finally {
20588            Binder.restoreCallingIdentity(callingId);
20589        }
20590    }
20591
20592    @Override
20593    public void flushPackageRestrictionsAsUser(int userId) {
20594        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20595            return;
20596        }
20597        if (!sUserManager.exists(userId)) {
20598            return;
20599        }
20600        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20601                false /* checkShell */, "flushPackageRestrictions");
20602        synchronized (mPackages) {
20603            mSettings.writePackageRestrictionsLPr(userId);
20604            mDirtyUsers.remove(userId);
20605            if (mDirtyUsers.isEmpty()) {
20606                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20607            }
20608        }
20609    }
20610
20611    private void sendPackageChangedBroadcast(String packageName,
20612            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20613        if (DEBUG_INSTALL)
20614            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20615                    + componentNames);
20616        Bundle extras = new Bundle(4);
20617        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20618        String nameList[] = new String[componentNames.size()];
20619        componentNames.toArray(nameList);
20620        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20621        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20622        extras.putInt(Intent.EXTRA_UID, packageUid);
20623        // If this is not reporting a change of the overall package, then only send it
20624        // to registered receivers.  We don't want to launch a swath of apps for every
20625        // little component state change.
20626        final int flags = !componentNames.contains(packageName)
20627                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20628        final int userId = UserHandle.getUserId(packageUid);
20629        final boolean isInstantApp = isInstantApp(packageName, userId);
20630        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20631        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20632        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20633                userIds, instantUserIds);
20634    }
20635
20636    @Override
20637    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20638        if (!sUserManager.exists(userId)) return;
20639        final int callingUid = Binder.getCallingUid();
20640        if (getInstantAppPackageName(callingUid) != null) {
20641            return;
20642        }
20643        final int permission = mContext.checkCallingOrSelfPermission(
20644                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20645        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20646        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20647                true /* requireFullPermission */, true /* checkShell */, "stop package");
20648        // writer
20649        synchronized (mPackages) {
20650            final PackageSetting ps = mSettings.mPackages.get(packageName);
20651            if (!filterAppAccessLPr(ps, callingUid, userId)
20652                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20653                            allowedByPermission, callingUid, userId)) {
20654                scheduleWritePackageRestrictionsLocked(userId);
20655            }
20656        }
20657    }
20658
20659    @Override
20660    public String getInstallerPackageName(String packageName) {
20661        final int callingUid = Binder.getCallingUid();
20662        synchronized (mPackages) {
20663            final PackageSetting ps = mSettings.mPackages.get(packageName);
20664            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20665                return null;
20666            }
20667            return mSettings.getInstallerPackageNameLPr(packageName);
20668        }
20669    }
20670
20671    public boolean isOrphaned(String packageName) {
20672        // reader
20673        synchronized (mPackages) {
20674            return mSettings.isOrphaned(packageName);
20675        }
20676    }
20677
20678    @Override
20679    public int getApplicationEnabledSetting(String packageName, int userId) {
20680        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20681        int callingUid = Binder.getCallingUid();
20682        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20683                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20684        // reader
20685        synchronized (mPackages) {
20686            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20687                return COMPONENT_ENABLED_STATE_DISABLED;
20688            }
20689            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20690        }
20691    }
20692
20693    @Override
20694    public int getComponentEnabledSetting(ComponentName component, int userId) {
20695        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20696        int callingUid = Binder.getCallingUid();
20697        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20698                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20699        synchronized (mPackages) {
20700            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20701                    component, TYPE_UNKNOWN, userId)) {
20702                return COMPONENT_ENABLED_STATE_DISABLED;
20703            }
20704            return mSettings.getComponentEnabledSettingLPr(component, userId);
20705        }
20706    }
20707
20708    @Override
20709    public void enterSafeMode() {
20710        enforceSystemOrRoot("Only the system can request entering safe mode");
20711
20712        if (!mSystemReady) {
20713            mSafeMode = true;
20714        }
20715    }
20716
20717    @Override
20718    public void systemReady() {
20719        enforceSystemOrRoot("Only the system can claim the system is ready");
20720
20721        mSystemReady = true;
20722        final ContentResolver resolver = mContext.getContentResolver();
20723        ContentObserver co = new ContentObserver(mHandler) {
20724            @Override
20725            public void onChange(boolean selfChange) {
20726                mWebInstantAppsDisabled =
20727                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20728                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20729            }
20730        };
20731        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20732                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20733                false, co, UserHandle.USER_SYSTEM);
20734        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
20735                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20736        co.onChange(true);
20737
20738        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20739        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20740        // it is done.
20741        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20742            @Override
20743            public void onChange(boolean selfChange) {
20744                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20745                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20746                        oobEnabled == 1 ? "true" : "false");
20747            }
20748        };
20749        mContext.getContentResolver().registerContentObserver(
20750                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20751                UserHandle.USER_SYSTEM);
20752        // At boot, restore the value from the setting, which persists across reboot.
20753        privAppOobObserver.onChange(true);
20754
20755        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20756        // disabled after already being started.
20757        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20758                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20759
20760        // Read the compatibilty setting when the system is ready.
20761        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20762                mContext.getContentResolver(),
20763                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20764        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20765        if (DEBUG_SETTINGS) {
20766            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20767        }
20768
20769        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20770
20771        synchronized (mPackages) {
20772            // Verify that all of the preferred activity components actually
20773            // exist.  It is possible for applications to be updated and at
20774            // that point remove a previously declared activity component that
20775            // had been set as a preferred activity.  We try to clean this up
20776            // the next time we encounter that preferred activity, but it is
20777            // possible for the user flow to never be able to return to that
20778            // situation so here we do a sanity check to make sure we haven't
20779            // left any junk around.
20780            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20781            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20782                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20783                removed.clear();
20784                for (PreferredActivity pa : pir.filterSet()) {
20785                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20786                        removed.add(pa);
20787                    }
20788                }
20789                if (removed.size() > 0) {
20790                    for (int r=0; r<removed.size(); r++) {
20791                        PreferredActivity pa = removed.get(r);
20792                        Slog.w(TAG, "Removing dangling preferred activity: "
20793                                + pa.mPref.mComponent);
20794                        pir.removeFilter(pa);
20795                    }
20796                    mSettings.writePackageRestrictionsLPr(
20797                            mSettings.mPreferredActivities.keyAt(i));
20798                }
20799            }
20800
20801            for (int userId : UserManagerService.getInstance().getUserIds()) {
20802                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20803                    grantPermissionsUserIds = ArrayUtils.appendInt(
20804                            grantPermissionsUserIds, userId);
20805                }
20806            }
20807        }
20808        sUserManager.systemReady();
20809        // If we upgraded grant all default permissions before kicking off.
20810        for (int userId : grantPermissionsUserIds) {
20811            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20812        }
20813
20814        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20815            // If we did not grant default permissions, we preload from this the
20816            // default permission exceptions lazily to ensure we don't hit the
20817            // disk on a new user creation.
20818            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20819        }
20820
20821        // Now that we've scanned all packages, and granted any default
20822        // permissions, ensure permissions are updated. Beware of dragons if you
20823        // try optimizing this.
20824        synchronized (mPackages) {
20825            mPermissionManager.updateAllPermissions(
20826                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20827                    mPermissionCallback);
20828        }
20829
20830        // Kick off any messages waiting for system ready
20831        if (mPostSystemReadyMessages != null) {
20832            for (Message msg : mPostSystemReadyMessages) {
20833                msg.sendToTarget();
20834            }
20835            mPostSystemReadyMessages = null;
20836        }
20837
20838        // Watch for external volumes that come and go over time
20839        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20840        storage.registerListener(mStorageListener);
20841
20842        mInstallerService.systemReady();
20843        mPackageDexOptimizer.systemReady();
20844
20845        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20846                StorageManagerInternal.class);
20847        StorageManagerInternal.addExternalStoragePolicy(
20848                new StorageManagerInternal.ExternalStorageMountPolicy() {
20849            @Override
20850            public int getMountMode(int uid, String packageName) {
20851                if (Process.isIsolated(uid)) {
20852                    return Zygote.MOUNT_EXTERNAL_NONE;
20853                }
20854                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20855                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20856                }
20857                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20858                    return Zygote.MOUNT_EXTERNAL_READ;
20859                }
20860                return Zygote.MOUNT_EXTERNAL_WRITE;
20861            }
20862
20863            @Override
20864            public boolean hasExternalStorage(int uid, String packageName) {
20865                return true;
20866            }
20867        });
20868
20869        // Now that we're mostly running, clean up stale users and apps
20870        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20871        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20872
20873        mPermissionManager.systemReady();
20874    }
20875
20876    public void waitForAppDataPrepared() {
20877        if (mPrepareAppDataFuture == null) {
20878            return;
20879        }
20880        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20881        mPrepareAppDataFuture = null;
20882    }
20883
20884    @Override
20885    public boolean isSafeMode() {
20886        // allow instant applications
20887        return mSafeMode;
20888    }
20889
20890    @Override
20891    public boolean hasSystemUidErrors() {
20892        // allow instant applications
20893        return mHasSystemUidErrors;
20894    }
20895
20896    static String arrayToString(int[] array) {
20897        StringBuffer buf = new StringBuffer(128);
20898        buf.append('[');
20899        if (array != null) {
20900            for (int i=0; i<array.length; i++) {
20901                if (i > 0) buf.append(", ");
20902                buf.append(array[i]);
20903            }
20904        }
20905        buf.append(']');
20906        return buf.toString();
20907    }
20908
20909    @Override
20910    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20911            FileDescriptor err, String[] args, ShellCallback callback,
20912            ResultReceiver resultReceiver) {
20913        (new PackageManagerShellCommand(this)).exec(
20914                this, in, out, err, args, callback, resultReceiver);
20915    }
20916
20917    @Override
20918    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20919        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20920
20921        DumpState dumpState = new DumpState();
20922        boolean fullPreferred = false;
20923        boolean checkin = false;
20924
20925        String packageName = null;
20926        ArraySet<String> permissionNames = null;
20927
20928        int opti = 0;
20929        while (opti < args.length) {
20930            String opt = args[opti];
20931            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20932                break;
20933            }
20934            opti++;
20935
20936            if ("-a".equals(opt)) {
20937                // Right now we only know how to print all.
20938            } else if ("-h".equals(opt)) {
20939                pw.println("Package manager dump options:");
20940                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20941                pw.println("    --checkin: dump for a checkin");
20942                pw.println("    -f: print details of intent filters");
20943                pw.println("    -h: print this help");
20944                pw.println("  cmd may be one of:");
20945                pw.println("    l[ibraries]: list known shared libraries");
20946                pw.println("    f[eatures]: list device features");
20947                pw.println("    k[eysets]: print known keysets");
20948                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20949                pw.println("    perm[issions]: dump permissions");
20950                pw.println("    permission [name ...]: dump declaration and use of given permission");
20951                pw.println("    pref[erred]: print preferred package settings");
20952                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20953                pw.println("    prov[iders]: dump content providers");
20954                pw.println("    p[ackages]: dump installed packages");
20955                pw.println("    s[hared-users]: dump shared user IDs");
20956                pw.println("    m[essages]: print collected runtime messages");
20957                pw.println("    v[erifiers]: print package verifier info");
20958                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20959                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20960                pw.println("    version: print database version info");
20961                pw.println("    write: write current settings now");
20962                pw.println("    installs: details about install sessions");
20963                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20964                pw.println("    dexopt: dump dexopt state");
20965                pw.println("    compiler-stats: dump compiler statistics");
20966                pw.println("    service-permissions: dump permissions required by services");
20967                pw.println("    <package.name>: info about given package");
20968                return;
20969            } else if ("--checkin".equals(opt)) {
20970                checkin = true;
20971            } else if ("-f".equals(opt)) {
20972                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20973            } else if ("--proto".equals(opt)) {
20974                dumpProto(fd);
20975                return;
20976            } else {
20977                pw.println("Unknown argument: " + opt + "; use -h for help");
20978            }
20979        }
20980
20981        // Is the caller requesting to dump a particular piece of data?
20982        if (opti < args.length) {
20983            String cmd = args[opti];
20984            opti++;
20985            // Is this a package name?
20986            if ("android".equals(cmd) || cmd.contains(".")) {
20987                packageName = cmd;
20988                // When dumping a single package, we always dump all of its
20989                // filter information since the amount of data will be reasonable.
20990                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20991            } else if ("check-permission".equals(cmd)) {
20992                if (opti >= args.length) {
20993                    pw.println("Error: check-permission missing permission argument");
20994                    return;
20995                }
20996                String perm = args[opti];
20997                opti++;
20998                if (opti >= args.length) {
20999                    pw.println("Error: check-permission missing package argument");
21000                    return;
21001                }
21002
21003                String pkg = args[opti];
21004                opti++;
21005                int user = UserHandle.getUserId(Binder.getCallingUid());
21006                if (opti < args.length) {
21007                    try {
21008                        user = Integer.parseInt(args[opti]);
21009                    } catch (NumberFormatException e) {
21010                        pw.println("Error: check-permission user argument is not a number: "
21011                                + args[opti]);
21012                        return;
21013                    }
21014                }
21015
21016                // Normalize package name to handle renamed packages and static libs
21017                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21018
21019                pw.println(checkPermission(perm, pkg, user));
21020                return;
21021            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21022                dumpState.setDump(DumpState.DUMP_LIBS);
21023            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21024                dumpState.setDump(DumpState.DUMP_FEATURES);
21025            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21026                if (opti >= args.length) {
21027                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21028                            | DumpState.DUMP_SERVICE_RESOLVERS
21029                            | DumpState.DUMP_RECEIVER_RESOLVERS
21030                            | DumpState.DUMP_CONTENT_RESOLVERS);
21031                } else {
21032                    while (opti < args.length) {
21033                        String name = args[opti];
21034                        if ("a".equals(name) || "activity".equals(name)) {
21035                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21036                        } else if ("s".equals(name) || "service".equals(name)) {
21037                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21038                        } else if ("r".equals(name) || "receiver".equals(name)) {
21039                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21040                        } else if ("c".equals(name) || "content".equals(name)) {
21041                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21042                        } else {
21043                            pw.println("Error: unknown resolver table type: " + name);
21044                            return;
21045                        }
21046                        opti++;
21047                    }
21048                }
21049            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21050                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21051            } else if ("permission".equals(cmd)) {
21052                if (opti >= args.length) {
21053                    pw.println("Error: permission requires permission name");
21054                    return;
21055                }
21056                permissionNames = new ArraySet<>();
21057                while (opti < args.length) {
21058                    permissionNames.add(args[opti]);
21059                    opti++;
21060                }
21061                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21062                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21063            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21064                dumpState.setDump(DumpState.DUMP_PREFERRED);
21065            } else if ("preferred-xml".equals(cmd)) {
21066                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21067                if (opti < args.length && "--full".equals(args[opti])) {
21068                    fullPreferred = true;
21069                    opti++;
21070                }
21071            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21072                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21073            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21074                dumpState.setDump(DumpState.DUMP_PACKAGES);
21075            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21076                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21077            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21078                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21079            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21080                dumpState.setDump(DumpState.DUMP_MESSAGES);
21081            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21082                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21083            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21084                    || "intent-filter-verifiers".equals(cmd)) {
21085                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21086            } else if ("version".equals(cmd)) {
21087                dumpState.setDump(DumpState.DUMP_VERSION);
21088            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21089                dumpState.setDump(DumpState.DUMP_KEYSETS);
21090            } else if ("installs".equals(cmd)) {
21091                dumpState.setDump(DumpState.DUMP_INSTALLS);
21092            } else if ("frozen".equals(cmd)) {
21093                dumpState.setDump(DumpState.DUMP_FROZEN);
21094            } else if ("volumes".equals(cmd)) {
21095                dumpState.setDump(DumpState.DUMP_VOLUMES);
21096            } else if ("dexopt".equals(cmd)) {
21097                dumpState.setDump(DumpState.DUMP_DEXOPT);
21098            } else if ("compiler-stats".equals(cmd)) {
21099                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21100            } else if ("changes".equals(cmd)) {
21101                dumpState.setDump(DumpState.DUMP_CHANGES);
21102            } else if ("service-permissions".equals(cmd)) {
21103                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21104            } else if ("write".equals(cmd)) {
21105                synchronized (mPackages) {
21106                    mSettings.writeLPr();
21107                    pw.println("Settings written.");
21108                    return;
21109                }
21110            }
21111        }
21112
21113        if (checkin) {
21114            pw.println("vers,1");
21115        }
21116
21117        // reader
21118        synchronized (mPackages) {
21119            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21120                if (!checkin) {
21121                    if (dumpState.onTitlePrinted())
21122                        pw.println();
21123                    pw.println("Database versions:");
21124                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21125                }
21126            }
21127
21128            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21129                if (!checkin) {
21130                    if (dumpState.onTitlePrinted())
21131                        pw.println();
21132                    pw.println("Verifiers:");
21133                    pw.print("  Required: ");
21134                    pw.print(mRequiredVerifierPackage);
21135                    pw.print(" (uid=");
21136                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21137                            UserHandle.USER_SYSTEM));
21138                    pw.println(")");
21139                } else if (mRequiredVerifierPackage != null) {
21140                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21141                    pw.print(",");
21142                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21143                            UserHandle.USER_SYSTEM));
21144                }
21145            }
21146
21147            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21148                    packageName == null) {
21149                if (mIntentFilterVerifierComponent != null) {
21150                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21151                    if (!checkin) {
21152                        if (dumpState.onTitlePrinted())
21153                            pw.println();
21154                        pw.println("Intent Filter Verifier:");
21155                        pw.print("  Using: ");
21156                        pw.print(verifierPackageName);
21157                        pw.print(" (uid=");
21158                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21159                                UserHandle.USER_SYSTEM));
21160                        pw.println(")");
21161                    } else if (verifierPackageName != null) {
21162                        pw.print("ifv,"); pw.print(verifierPackageName);
21163                        pw.print(",");
21164                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21165                                UserHandle.USER_SYSTEM));
21166                    }
21167                } else {
21168                    pw.println();
21169                    pw.println("No Intent Filter Verifier available!");
21170                }
21171            }
21172
21173            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21174                boolean printedHeader = false;
21175                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21176                while (it.hasNext()) {
21177                    String libName = it.next();
21178                    LongSparseArray<SharedLibraryEntry> versionedLib
21179                            = mSharedLibraries.get(libName);
21180                    if (versionedLib == null) {
21181                        continue;
21182                    }
21183                    final int versionCount = versionedLib.size();
21184                    for (int i = 0; i < versionCount; i++) {
21185                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21186                        if (!checkin) {
21187                            if (!printedHeader) {
21188                                if (dumpState.onTitlePrinted())
21189                                    pw.println();
21190                                pw.println("Libraries:");
21191                                printedHeader = true;
21192                            }
21193                            pw.print("  ");
21194                        } else {
21195                            pw.print("lib,");
21196                        }
21197                        pw.print(libEntry.info.getName());
21198                        if (libEntry.info.isStatic()) {
21199                            pw.print(" version=" + libEntry.info.getLongVersion());
21200                        }
21201                        if (!checkin) {
21202                            pw.print(" -> ");
21203                        }
21204                        if (libEntry.path != null) {
21205                            pw.print(" (jar) ");
21206                            pw.print(libEntry.path);
21207                        } else {
21208                            pw.print(" (apk) ");
21209                            pw.print(libEntry.apk);
21210                        }
21211                        pw.println();
21212                    }
21213                }
21214            }
21215
21216            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21217                if (dumpState.onTitlePrinted())
21218                    pw.println();
21219                if (!checkin) {
21220                    pw.println("Features:");
21221                }
21222
21223                synchronized (mAvailableFeatures) {
21224                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21225                        if (checkin) {
21226                            pw.print("feat,");
21227                            pw.print(feat.name);
21228                            pw.print(",");
21229                            pw.println(feat.version);
21230                        } else {
21231                            pw.print("  ");
21232                            pw.print(feat.name);
21233                            if (feat.version > 0) {
21234                                pw.print(" version=");
21235                                pw.print(feat.version);
21236                            }
21237                            pw.println();
21238                        }
21239                    }
21240                }
21241            }
21242
21243            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21244                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21245                        : "Activity Resolver Table:", "  ", packageName,
21246                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21247                    dumpState.setTitlePrinted(true);
21248                }
21249            }
21250            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21251                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21252                        : "Receiver Resolver Table:", "  ", packageName,
21253                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21254                    dumpState.setTitlePrinted(true);
21255                }
21256            }
21257            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21258                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21259                        : "Service Resolver Table:", "  ", packageName,
21260                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21261                    dumpState.setTitlePrinted(true);
21262                }
21263            }
21264            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21265                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21266                        : "Provider Resolver Table:", "  ", packageName,
21267                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21268                    dumpState.setTitlePrinted(true);
21269                }
21270            }
21271
21272            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21273                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21274                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21275                    int user = mSettings.mPreferredActivities.keyAt(i);
21276                    if (pir.dump(pw,
21277                            dumpState.getTitlePrinted()
21278                                ? "\nPreferred Activities User " + user + ":"
21279                                : "Preferred Activities User " + user + ":", "  ",
21280                            packageName, true, false)) {
21281                        dumpState.setTitlePrinted(true);
21282                    }
21283                }
21284            }
21285
21286            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21287                pw.flush();
21288                FileOutputStream fout = new FileOutputStream(fd);
21289                BufferedOutputStream str = new BufferedOutputStream(fout);
21290                XmlSerializer serializer = new FastXmlSerializer();
21291                try {
21292                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21293                    serializer.startDocument(null, true);
21294                    serializer.setFeature(
21295                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21296                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21297                    serializer.endDocument();
21298                    serializer.flush();
21299                } catch (IllegalArgumentException e) {
21300                    pw.println("Failed writing: " + e);
21301                } catch (IllegalStateException e) {
21302                    pw.println("Failed writing: " + e);
21303                } catch (IOException e) {
21304                    pw.println("Failed writing: " + e);
21305                }
21306            }
21307
21308            if (!checkin
21309                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21310                    && packageName == null) {
21311                pw.println();
21312                int count = mSettings.mPackages.size();
21313                if (count == 0) {
21314                    pw.println("No applications!");
21315                    pw.println();
21316                } else {
21317                    final String prefix = "  ";
21318                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21319                    if (allPackageSettings.size() == 0) {
21320                        pw.println("No domain preferred apps!");
21321                        pw.println();
21322                    } else {
21323                        pw.println("App verification status:");
21324                        pw.println();
21325                        count = 0;
21326                        for (PackageSetting ps : allPackageSettings) {
21327                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21328                            if (ivi == null || ivi.getPackageName() == null) continue;
21329                            pw.println(prefix + "Package: " + ivi.getPackageName());
21330                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21331                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21332                            pw.println();
21333                            count++;
21334                        }
21335                        if (count == 0) {
21336                            pw.println(prefix + "No app verification established.");
21337                            pw.println();
21338                        }
21339                        for (int userId : sUserManager.getUserIds()) {
21340                            pw.println("App linkages for user " + userId + ":");
21341                            pw.println();
21342                            count = 0;
21343                            for (PackageSetting ps : allPackageSettings) {
21344                                final long status = ps.getDomainVerificationStatusForUser(userId);
21345                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21346                                        && !DEBUG_DOMAIN_VERIFICATION) {
21347                                    continue;
21348                                }
21349                                pw.println(prefix + "Package: " + ps.name);
21350                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21351                                String statusStr = IntentFilterVerificationInfo.
21352                                        getStatusStringFromValue(status);
21353                                pw.println(prefix + "Status:  " + statusStr);
21354                                pw.println();
21355                                count++;
21356                            }
21357                            if (count == 0) {
21358                                pw.println(prefix + "No configured app linkages.");
21359                                pw.println();
21360                            }
21361                        }
21362                    }
21363                }
21364            }
21365
21366            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21367                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21368            }
21369
21370            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21371                boolean printedSomething = false;
21372                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21373                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21374                        continue;
21375                    }
21376                    if (!printedSomething) {
21377                        if (dumpState.onTitlePrinted())
21378                            pw.println();
21379                        pw.println("Registered ContentProviders:");
21380                        printedSomething = true;
21381                    }
21382                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21383                    pw.print("    "); pw.println(p.toString());
21384                }
21385                printedSomething = false;
21386                for (Map.Entry<String, PackageParser.Provider> entry :
21387                        mProvidersByAuthority.entrySet()) {
21388                    PackageParser.Provider p = entry.getValue();
21389                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21390                        continue;
21391                    }
21392                    if (!printedSomething) {
21393                        if (dumpState.onTitlePrinted())
21394                            pw.println();
21395                        pw.println("ContentProvider Authorities:");
21396                        printedSomething = true;
21397                    }
21398                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21399                    pw.print("    "); pw.println(p.toString());
21400                    if (p.info != null && p.info.applicationInfo != null) {
21401                        final String appInfo = p.info.applicationInfo.toString();
21402                        pw.print("      applicationInfo="); pw.println(appInfo);
21403                    }
21404                }
21405            }
21406
21407            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21408                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21409            }
21410
21411            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21412                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21413            }
21414
21415            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21416                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21417            }
21418
21419            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21420                if (dumpState.onTitlePrinted()) pw.println();
21421                pw.println("Package Changes:");
21422                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21423                final int K = mChangedPackages.size();
21424                for (int i = 0; i < K; i++) {
21425                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21426                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21427                    final int N = changes.size();
21428                    if (N == 0) {
21429                        pw.print("    "); pw.println("No packages changed");
21430                    } else {
21431                        for (int j = 0; j < N; j++) {
21432                            final String pkgName = changes.valueAt(j);
21433                            final int sequenceNumber = changes.keyAt(j);
21434                            pw.print("    ");
21435                            pw.print("seq=");
21436                            pw.print(sequenceNumber);
21437                            pw.print(", package=");
21438                            pw.println(pkgName);
21439                        }
21440                    }
21441                }
21442            }
21443
21444            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21445                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21446            }
21447
21448            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21449                // XXX should handle packageName != null by dumping only install data that
21450                // the given package is involved with.
21451                if (dumpState.onTitlePrinted()) pw.println();
21452
21453                try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120)) {
21454                    ipw.println();
21455                    ipw.println("Frozen packages:");
21456                    ipw.increaseIndent();
21457                    if (mFrozenPackages.size() == 0) {
21458                        ipw.println("(none)");
21459                    } else {
21460                        for (int i = 0; i < mFrozenPackages.size(); i++) {
21461                            ipw.println(mFrozenPackages.valueAt(i));
21462                        }
21463                    }
21464                    ipw.decreaseIndent();
21465                }
21466            }
21467
21468            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21469                if (dumpState.onTitlePrinted()) pw.println();
21470
21471                try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120)) {
21472                    ipw.println();
21473                    ipw.println("Loaded volumes:");
21474                    ipw.increaseIndent();
21475                    if (mLoadedVolumes.size() == 0) {
21476                        ipw.println("(none)");
21477                    } else {
21478                        for (int i = 0; i < mLoadedVolumes.size(); i++) {
21479                            ipw.println(mLoadedVolumes.valueAt(i));
21480                        }
21481                    }
21482                    ipw.decreaseIndent();
21483                }
21484            }
21485
21486            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21487                    && packageName == null) {
21488                if (dumpState.onTitlePrinted()) pw.println();
21489                pw.println("Service permissions:");
21490
21491                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21492                while (filterIterator.hasNext()) {
21493                    final ServiceIntentInfo info = filterIterator.next();
21494                    final ServiceInfo serviceInfo = info.service.info;
21495                    final String permission = serviceInfo.permission;
21496                    if (permission != null) {
21497                        pw.print("    ");
21498                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21499                        pw.print(": ");
21500                        pw.println(permission);
21501                    }
21502                }
21503            }
21504
21505            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21506                if (dumpState.onTitlePrinted()) pw.println();
21507                dumpDexoptStateLPr(pw, packageName);
21508            }
21509
21510            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21511                if (dumpState.onTitlePrinted()) pw.println();
21512                dumpCompilerStatsLPr(pw, packageName);
21513            }
21514
21515            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21516                if (dumpState.onTitlePrinted()) pw.println();
21517                mSettings.dumpReadMessagesLPr(pw, dumpState);
21518
21519                pw.println();
21520                pw.println("Package warning messages:");
21521                dumpCriticalInfo(pw, null);
21522            }
21523
21524            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21525                dumpCriticalInfo(pw, "msg,");
21526            }
21527        }
21528
21529        // PackageInstaller should be called outside of mPackages lock
21530        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21531            // XXX should handle packageName != null by dumping only install data that
21532            // the given package is involved with.
21533            if (dumpState.onTitlePrinted()) pw.println();
21534            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21535        }
21536    }
21537
21538    private void dumpProto(FileDescriptor fd) {
21539        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21540
21541        synchronized (mPackages) {
21542            final long requiredVerifierPackageToken =
21543                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21544            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21545            proto.write(
21546                    PackageServiceDumpProto.PackageShortProto.UID,
21547                    getPackageUid(
21548                            mRequiredVerifierPackage,
21549                            MATCH_DEBUG_TRIAGED_MISSING,
21550                            UserHandle.USER_SYSTEM));
21551            proto.end(requiredVerifierPackageToken);
21552
21553            if (mIntentFilterVerifierComponent != null) {
21554                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21555                final long verifierPackageToken =
21556                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21557                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21558                proto.write(
21559                        PackageServiceDumpProto.PackageShortProto.UID,
21560                        getPackageUid(
21561                                verifierPackageName,
21562                                MATCH_DEBUG_TRIAGED_MISSING,
21563                                UserHandle.USER_SYSTEM));
21564                proto.end(verifierPackageToken);
21565            }
21566
21567            dumpSharedLibrariesProto(proto);
21568            dumpFeaturesProto(proto);
21569            mSettings.dumpPackagesProto(proto);
21570            mSettings.dumpSharedUsersProto(proto);
21571            dumpCriticalInfo(proto);
21572        }
21573        proto.flush();
21574    }
21575
21576    private void dumpFeaturesProto(ProtoOutputStream proto) {
21577        synchronized (mAvailableFeatures) {
21578            final int count = mAvailableFeatures.size();
21579            for (int i = 0; i < count; i++) {
21580                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21581            }
21582        }
21583    }
21584
21585    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21586        final int count = mSharedLibraries.size();
21587        for (int i = 0; i < count; i++) {
21588            final String libName = mSharedLibraries.keyAt(i);
21589            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21590            if (versionedLib == null) {
21591                continue;
21592            }
21593            final int versionCount = versionedLib.size();
21594            for (int j = 0; j < versionCount; j++) {
21595                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21596                final long sharedLibraryToken =
21597                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21598                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21599                final boolean isJar = (libEntry.path != null);
21600                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21601                if (isJar) {
21602                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21603                } else {
21604                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21605                }
21606                proto.end(sharedLibraryToken);
21607            }
21608        }
21609    }
21610
21611    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21612        try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ")) {
21613            ipw.println();
21614            ipw.println("Dexopt state:");
21615            ipw.increaseIndent();
21616            Collection<PackageParser.Package> packages = null;
21617            if (packageName != null) {
21618                PackageParser.Package targetPackage = mPackages.get(packageName);
21619                if (targetPackage != null) {
21620                    packages = Collections.singletonList(targetPackage);
21621                } else {
21622                    ipw.println("Unable to find package: " + packageName);
21623                    return;
21624                }
21625            } else {
21626                packages = mPackages.values();
21627            }
21628
21629            for (PackageParser.Package pkg : packages) {
21630                ipw.println("[" + pkg.packageName + "]");
21631                ipw.increaseIndent();
21632                mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21633                        mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21634                ipw.decreaseIndent();
21635            }
21636        }
21637    }
21638
21639    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21640        try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ")) {
21641            ipw.println();
21642            ipw.println("Compiler stats:");
21643            ipw.increaseIndent();
21644            Collection<PackageParser.Package> packages = null;
21645            if (packageName != null) {
21646                PackageParser.Package targetPackage = mPackages.get(packageName);
21647                if (targetPackage != null) {
21648                    packages = Collections.singletonList(targetPackage);
21649                } else {
21650                    ipw.println("Unable to find package: " + packageName);
21651                    return;
21652                }
21653            } else {
21654                packages = mPackages.values();
21655            }
21656
21657            for (PackageParser.Package pkg : packages) {
21658                ipw.println("[" + pkg.packageName + "]");
21659                ipw.increaseIndent();
21660
21661                CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21662                if (stats == null) {
21663                    ipw.println("(No recorded stats)");
21664                } else {
21665                    stats.dump(ipw);
21666                }
21667                ipw.decreaseIndent();
21668            }
21669        }
21670    }
21671
21672    private String dumpDomainString(String packageName) {
21673        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21674                .getList();
21675        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21676
21677        ArraySet<String> result = new ArraySet<>();
21678        if (iviList.size() > 0) {
21679            for (IntentFilterVerificationInfo ivi : iviList) {
21680                for (String host : ivi.getDomains()) {
21681                    result.add(host);
21682                }
21683            }
21684        }
21685        if (filters != null && filters.size() > 0) {
21686            for (IntentFilter filter : filters) {
21687                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21688                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21689                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21690                    result.addAll(filter.getHostsList());
21691                }
21692            }
21693        }
21694
21695        StringBuilder sb = new StringBuilder(result.size() * 16);
21696        for (String domain : result) {
21697            if (sb.length() > 0) sb.append(" ");
21698            sb.append(domain);
21699        }
21700        return sb.toString();
21701    }
21702
21703    // ------- apps on sdcard specific code -------
21704    static final boolean DEBUG_SD_INSTALL = false;
21705
21706    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21707
21708    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21709
21710    private boolean mMediaMounted = false;
21711
21712    static String getEncryptKey() {
21713        try {
21714            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21715                    SD_ENCRYPTION_KEYSTORE_NAME);
21716            if (sdEncKey == null) {
21717                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21718                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21719                if (sdEncKey == null) {
21720                    Slog.e(TAG, "Failed to create encryption keys");
21721                    return null;
21722                }
21723            }
21724            return sdEncKey;
21725        } catch (NoSuchAlgorithmException nsae) {
21726            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21727            return null;
21728        } catch (IOException ioe) {
21729            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21730            return null;
21731        }
21732    }
21733
21734    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21735            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21736        final int size = infos.size();
21737        final String[] packageNames = new String[size];
21738        final int[] packageUids = new int[size];
21739        for (int i = 0; i < size; i++) {
21740            final ApplicationInfo info = infos.get(i);
21741            packageNames[i] = info.packageName;
21742            packageUids[i] = info.uid;
21743        }
21744        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21745                finishedReceiver);
21746    }
21747
21748    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21749            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21750        sendResourcesChangedBroadcast(mediaStatus, replacing,
21751                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21752    }
21753
21754    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21755            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21756        int size = pkgList.length;
21757        if (size > 0) {
21758            // Send broadcasts here
21759            Bundle extras = new Bundle();
21760            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21761            if (uidArr != null) {
21762                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21763            }
21764            if (replacing) {
21765                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21766            }
21767            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21768                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21769            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
21770        }
21771    }
21772
21773    private void loadPrivatePackages(final VolumeInfo vol) {
21774        mHandler.post(new Runnable() {
21775            @Override
21776            public void run() {
21777                loadPrivatePackagesInner(vol);
21778            }
21779        });
21780    }
21781
21782    private void loadPrivatePackagesInner(VolumeInfo vol) {
21783        final String volumeUuid = vol.fsUuid;
21784        if (TextUtils.isEmpty(volumeUuid)) {
21785            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21786            return;
21787        }
21788
21789        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21790        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21791        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21792
21793        final VersionInfo ver;
21794        final List<PackageSetting> packages;
21795        synchronized (mPackages) {
21796            ver = mSettings.findOrCreateVersion(volumeUuid);
21797            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21798        }
21799
21800        for (PackageSetting ps : packages) {
21801            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21802            synchronized (mInstallLock) {
21803                final PackageParser.Package pkg;
21804                try {
21805                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21806                    loaded.add(pkg.applicationInfo);
21807
21808                } catch (PackageManagerException e) {
21809                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21810                }
21811
21812                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21813                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21814                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21815                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21816                }
21817            }
21818        }
21819
21820        // Reconcile app data for all started/unlocked users
21821        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21822        final UserManager um = mContext.getSystemService(UserManager.class);
21823        UserManagerInternal umInternal = getUserManagerInternal();
21824        for (UserInfo user : um.getUsers()) {
21825            final int flags;
21826            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21827                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21828            } else if (umInternal.isUserRunning(user.id)) {
21829                flags = StorageManager.FLAG_STORAGE_DE;
21830            } else {
21831                continue;
21832            }
21833
21834            try {
21835                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21836                synchronized (mInstallLock) {
21837                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21838                }
21839            } catch (IllegalStateException e) {
21840                // Device was probably ejected, and we'll process that event momentarily
21841                Slog.w(TAG, "Failed to prepare storage: " + e);
21842            }
21843        }
21844
21845        synchronized (mPackages) {
21846            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
21847            if (sdkUpdated) {
21848                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21849                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21850            }
21851            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
21852                    mPermissionCallback);
21853
21854            // Yay, everything is now upgraded
21855            ver.forceCurrent();
21856
21857            mSettings.writeLPr();
21858        }
21859
21860        for (PackageFreezer freezer : freezers) {
21861            freezer.close();
21862        }
21863
21864        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21865        sendResourcesChangedBroadcast(true, false, loaded, null);
21866        mLoadedVolumes.add(vol.getId());
21867    }
21868
21869    private void unloadPrivatePackages(final VolumeInfo vol) {
21870        mHandler.post(new Runnable() {
21871            @Override
21872            public void run() {
21873                unloadPrivatePackagesInner(vol);
21874            }
21875        });
21876    }
21877
21878    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21879        final String volumeUuid = vol.fsUuid;
21880        if (TextUtils.isEmpty(volumeUuid)) {
21881            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21882            return;
21883        }
21884
21885        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21886        synchronized (mInstallLock) {
21887        synchronized (mPackages) {
21888            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21889            for (PackageSetting ps : packages) {
21890                if (ps.pkg == null) continue;
21891
21892                final ApplicationInfo info = ps.pkg.applicationInfo;
21893                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21894                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21895
21896                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21897                        "unloadPrivatePackagesInner")) {
21898                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21899                            false, null)) {
21900                        unloaded.add(info);
21901                    } else {
21902                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21903                    }
21904                }
21905
21906                // Try very hard to release any references to this package
21907                // so we don't risk the system server being killed due to
21908                // open FDs
21909                AttributeCache.instance().removePackage(ps.name);
21910            }
21911
21912            mSettings.writeLPr();
21913        }
21914        }
21915
21916        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21917        sendResourcesChangedBroadcast(false, false, unloaded, null);
21918        mLoadedVolumes.remove(vol.getId());
21919
21920        // Try very hard to release any references to this path so we don't risk
21921        // the system server being killed due to open FDs
21922        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21923
21924        for (int i = 0; i < 3; i++) {
21925            System.gc();
21926            System.runFinalization();
21927        }
21928    }
21929
21930    private void assertPackageKnown(String volumeUuid, String packageName)
21931            throws PackageManagerException {
21932        synchronized (mPackages) {
21933            // Normalize package name to handle renamed packages
21934            packageName = normalizePackageNameLPr(packageName);
21935
21936            final PackageSetting ps = mSettings.mPackages.get(packageName);
21937            if (ps == null) {
21938                throw new PackageManagerException("Package " + packageName + " is unknown");
21939            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21940                throw new PackageManagerException(
21941                        "Package " + packageName + " found on unknown volume " + volumeUuid
21942                                + "; expected volume " + ps.volumeUuid);
21943            }
21944        }
21945    }
21946
21947    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21948            throws PackageManagerException {
21949        synchronized (mPackages) {
21950            // Normalize package name to handle renamed packages
21951            packageName = normalizePackageNameLPr(packageName);
21952
21953            final PackageSetting ps = mSettings.mPackages.get(packageName);
21954            if (ps == null) {
21955                throw new PackageManagerException("Package " + packageName + " is unknown");
21956            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21957                throw new PackageManagerException(
21958                        "Package " + packageName + " found on unknown volume " + volumeUuid
21959                                + "; expected volume " + ps.volumeUuid);
21960            } else if (!ps.getInstalled(userId)) {
21961                throw new PackageManagerException(
21962                        "Package " + packageName + " not installed for user " + userId);
21963            }
21964        }
21965    }
21966
21967    private List<String> collectAbsoluteCodePaths() {
21968        synchronized (mPackages) {
21969            List<String> codePaths = new ArrayList<>();
21970            final int packageCount = mSettings.mPackages.size();
21971            for (int i = 0; i < packageCount; i++) {
21972                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21973                codePaths.add(ps.codePath.getAbsolutePath());
21974            }
21975            return codePaths;
21976        }
21977    }
21978
21979    /**
21980     * Examine all apps present on given mounted volume, and destroy apps that
21981     * aren't expected, either due to uninstallation or reinstallation on
21982     * another volume.
21983     */
21984    private void reconcileApps(String volumeUuid) {
21985        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21986        List<File> filesToDelete = null;
21987
21988        final File[] files = FileUtils.listFilesOrEmpty(
21989                Environment.getDataAppDirectory(volumeUuid));
21990        for (File file : files) {
21991            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21992                    && !PackageInstallerService.isStageName(file.getName());
21993            if (!isPackage) {
21994                // Ignore entries which are not packages
21995                continue;
21996            }
21997
21998            String absolutePath = file.getAbsolutePath();
21999
22000            boolean pathValid = false;
22001            final int absoluteCodePathCount = absoluteCodePaths.size();
22002            for (int i = 0; i < absoluteCodePathCount; i++) {
22003                String absoluteCodePath = absoluteCodePaths.get(i);
22004                if (absolutePath.startsWith(absoluteCodePath)) {
22005                    pathValid = true;
22006                    break;
22007                }
22008            }
22009
22010            if (!pathValid) {
22011                if (filesToDelete == null) {
22012                    filesToDelete = new ArrayList<>();
22013                }
22014                filesToDelete.add(file);
22015            }
22016        }
22017
22018        if (filesToDelete != null) {
22019            final int fileToDeleteCount = filesToDelete.size();
22020            for (int i = 0; i < fileToDeleteCount; i++) {
22021                File fileToDelete = filesToDelete.get(i);
22022                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22023                synchronized (mInstallLock) {
22024                    removeCodePathLI(fileToDelete);
22025                }
22026            }
22027        }
22028    }
22029
22030    /**
22031     * Reconcile all app data for the given user.
22032     * <p>
22033     * Verifies that directories exist and that ownership and labeling is
22034     * correct for all installed apps on all mounted volumes.
22035     */
22036    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22037        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22038        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22039            final String volumeUuid = vol.getFsUuid();
22040            synchronized (mInstallLock) {
22041                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22042            }
22043        }
22044    }
22045
22046    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22047            boolean migrateAppData) {
22048        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22049    }
22050
22051    /**
22052     * Reconcile all app data on given mounted volume.
22053     * <p>
22054     * Destroys app data that isn't expected, either due to uninstallation or
22055     * reinstallation on another volume.
22056     * <p>
22057     * Verifies that directories exist and that ownership and labeling is
22058     * correct for all installed apps.
22059     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22060     */
22061    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22062            boolean migrateAppData, boolean onlyCoreApps) {
22063        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22064                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22065        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22066
22067        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22068        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22069
22070        // First look for stale data that doesn't belong, and check if things
22071        // have changed since we did our last restorecon
22072        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22073            if (StorageManager.isFileEncryptedNativeOrEmulated()
22074                    && !StorageManager.isUserKeyUnlocked(userId)) {
22075                throw new RuntimeException(
22076                        "Yikes, someone asked us to reconcile CE storage while " + userId
22077                                + " was still locked; this would have caused massive data loss!");
22078            }
22079
22080            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22081            for (File file : files) {
22082                final String packageName = file.getName();
22083                try {
22084                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22085                } catch (PackageManagerException e) {
22086                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22087                    try {
22088                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22089                                StorageManager.FLAG_STORAGE_CE, 0);
22090                    } catch (InstallerException e2) {
22091                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22092                    }
22093                }
22094            }
22095        }
22096        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22097            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22098            for (File file : files) {
22099                final String packageName = file.getName();
22100                try {
22101                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22102                } catch (PackageManagerException e) {
22103                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22104                    try {
22105                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22106                                StorageManager.FLAG_STORAGE_DE, 0);
22107                    } catch (InstallerException e2) {
22108                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22109                    }
22110                }
22111            }
22112        }
22113
22114        // Ensure that data directories are ready to roll for all packages
22115        // installed for this volume and user
22116        final List<PackageSetting> packages;
22117        synchronized (mPackages) {
22118            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22119        }
22120        int preparedCount = 0;
22121        for (PackageSetting ps : packages) {
22122            final String packageName = ps.name;
22123            if (ps.pkg == null) {
22124                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22125                // TODO: might be due to legacy ASEC apps; we should circle back
22126                // and reconcile again once they're scanned
22127                continue;
22128            }
22129            // Skip non-core apps if requested
22130            if (onlyCoreApps && !ps.pkg.coreApp) {
22131                result.add(packageName);
22132                continue;
22133            }
22134
22135            if (ps.getInstalled(userId)) {
22136                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22137                preparedCount++;
22138            }
22139        }
22140
22141        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22142        return result;
22143    }
22144
22145    /**
22146     * Prepare app data for the given app just after it was installed or
22147     * upgraded. This method carefully only touches users that it's installed
22148     * for, and it forces a restorecon to handle any seinfo changes.
22149     * <p>
22150     * Verifies that directories exist and that ownership and labeling is
22151     * correct for all installed apps. If there is an ownership mismatch, it
22152     * will try recovering system apps by wiping data; third-party app data is
22153     * left intact.
22154     * <p>
22155     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22156     */
22157    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22158        final PackageSetting ps;
22159        synchronized (mPackages) {
22160            ps = mSettings.mPackages.get(pkg.packageName);
22161            mSettings.writeKernelMappingLPr(ps);
22162        }
22163
22164        final UserManager um = mContext.getSystemService(UserManager.class);
22165        UserManagerInternal umInternal = getUserManagerInternal();
22166        for (UserInfo user : um.getUsers()) {
22167            final int flags;
22168            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22169                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22170            } else if (umInternal.isUserRunning(user.id)) {
22171                flags = StorageManager.FLAG_STORAGE_DE;
22172            } else {
22173                continue;
22174            }
22175
22176            if (ps.getInstalled(user.id)) {
22177                // TODO: when user data is locked, mark that we're still dirty
22178                prepareAppDataLIF(pkg, user.id, flags);
22179            }
22180        }
22181    }
22182
22183    /**
22184     * Prepare app data for the given app.
22185     * <p>
22186     * Verifies that directories exist and that ownership and labeling is
22187     * correct for all installed apps. If there is an ownership mismatch, this
22188     * will try recovering system apps by wiping data; third-party app data is
22189     * left intact.
22190     */
22191    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22192        if (pkg == null) {
22193            Slog.wtf(TAG, "Package was null!", new Throwable());
22194            return;
22195        }
22196        prepareAppDataLeafLIF(pkg, userId, flags);
22197        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22198        for (int i = 0; i < childCount; i++) {
22199            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22200        }
22201    }
22202
22203    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22204            boolean maybeMigrateAppData) {
22205        prepareAppDataLIF(pkg, userId, flags);
22206
22207        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22208            // We may have just shuffled around app data directories, so
22209            // prepare them one more time
22210            prepareAppDataLIF(pkg, userId, flags);
22211        }
22212    }
22213
22214    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22215        if (DEBUG_APP_DATA) {
22216            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22217                    + Integer.toHexString(flags));
22218        }
22219
22220        final String volumeUuid = pkg.volumeUuid;
22221        final String packageName = pkg.packageName;
22222        final ApplicationInfo app = pkg.applicationInfo;
22223        final int appId = UserHandle.getAppId(app.uid);
22224
22225        Preconditions.checkNotNull(app.seInfo);
22226
22227        long ceDataInode = -1;
22228        try {
22229            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22230                    appId, app.seInfo, app.targetSdkVersion);
22231        } catch (InstallerException e) {
22232            if (app.isSystemApp()) {
22233                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22234                        + ", but trying to recover: " + e);
22235                destroyAppDataLeafLIF(pkg, userId, flags);
22236                try {
22237                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22238                            appId, app.seInfo, app.targetSdkVersion);
22239                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22240                } catch (InstallerException e2) {
22241                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22242                }
22243            } else {
22244                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22245            }
22246        }
22247        // Prepare the application profiles only for upgrades and first boot (so that we don't
22248        // repeat the same operation at each boot).
22249        // We only have to cover the upgrade and first boot here because for app installs we
22250        // prepare the profiles before invoking dexopt (in installPackageLI).
22251        //
22252        // We also have to cover non system users because we do not call the usual install package
22253        // methods for them.
22254        if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) {
22255            mArtManagerService.prepareAppProfiles(pkg, userId);
22256        }
22257
22258        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22259            // TODO: mark this structure as dirty so we persist it!
22260            synchronized (mPackages) {
22261                final PackageSetting ps = mSettings.mPackages.get(packageName);
22262                if (ps != null) {
22263                    ps.setCeDataInode(ceDataInode, userId);
22264                }
22265            }
22266        }
22267
22268        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22269    }
22270
22271    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22272        if (pkg == null) {
22273            Slog.wtf(TAG, "Package was null!", new Throwable());
22274            return;
22275        }
22276        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22277        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22278        for (int i = 0; i < childCount; i++) {
22279            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22280        }
22281    }
22282
22283    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22284        final String volumeUuid = pkg.volumeUuid;
22285        final String packageName = pkg.packageName;
22286        final ApplicationInfo app = pkg.applicationInfo;
22287
22288        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22289            // Create a native library symlink only if we have native libraries
22290            // and if the native libraries are 32 bit libraries. We do not provide
22291            // this symlink for 64 bit libraries.
22292            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22293                final String nativeLibPath = app.nativeLibraryDir;
22294                try {
22295                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22296                            nativeLibPath, userId);
22297                } catch (InstallerException e) {
22298                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22299                }
22300            }
22301        }
22302    }
22303
22304    /**
22305     * For system apps on non-FBE devices, this method migrates any existing
22306     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22307     * requested by the app.
22308     */
22309    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22310        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22311                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22312            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22313                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22314            try {
22315                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22316                        storageTarget);
22317            } catch (InstallerException e) {
22318                logCriticalInfo(Log.WARN,
22319                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22320            }
22321            return true;
22322        } else {
22323            return false;
22324        }
22325    }
22326
22327    public PackageFreezer freezePackage(String packageName, String killReason) {
22328        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22329    }
22330
22331    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22332        return new PackageFreezer(packageName, userId, killReason);
22333    }
22334
22335    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22336            String killReason) {
22337        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22338    }
22339
22340    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22341            String killReason) {
22342        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22343            return new PackageFreezer();
22344        } else {
22345            return freezePackage(packageName, userId, killReason);
22346        }
22347    }
22348
22349    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22350            String killReason) {
22351        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22352    }
22353
22354    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22355            String killReason) {
22356        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22357            return new PackageFreezer();
22358        } else {
22359            return freezePackage(packageName, userId, killReason);
22360        }
22361    }
22362
22363    /**
22364     * Class that freezes and kills the given package upon creation, and
22365     * unfreezes it upon closing. This is typically used when doing surgery on
22366     * app code/data to prevent the app from running while you're working.
22367     */
22368    private class PackageFreezer implements AutoCloseable {
22369        private final String mPackageName;
22370        private final PackageFreezer[] mChildren;
22371
22372        private final boolean mWeFroze;
22373
22374        private final AtomicBoolean mClosed = new AtomicBoolean();
22375        private final CloseGuard mCloseGuard = CloseGuard.get();
22376
22377        /**
22378         * Create and return a stub freezer that doesn't actually do anything,
22379         * typically used when someone requested
22380         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22381         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22382         */
22383        public PackageFreezer() {
22384            mPackageName = null;
22385            mChildren = null;
22386            mWeFroze = false;
22387            mCloseGuard.open("close");
22388        }
22389
22390        public PackageFreezer(String packageName, int userId, String killReason) {
22391            synchronized (mPackages) {
22392                mPackageName = packageName;
22393                mWeFroze = mFrozenPackages.add(mPackageName);
22394
22395                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22396                if (ps != null) {
22397                    killApplication(ps.name, ps.appId, userId, killReason);
22398                }
22399
22400                final PackageParser.Package p = mPackages.get(packageName);
22401                if (p != null && p.childPackages != null) {
22402                    final int N = p.childPackages.size();
22403                    mChildren = new PackageFreezer[N];
22404                    for (int i = 0; i < N; i++) {
22405                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22406                                userId, killReason);
22407                    }
22408                } else {
22409                    mChildren = null;
22410                }
22411            }
22412            mCloseGuard.open("close");
22413        }
22414
22415        @Override
22416        protected void finalize() throws Throwable {
22417            try {
22418                if (mCloseGuard != null) {
22419                    mCloseGuard.warnIfOpen();
22420                }
22421
22422                close();
22423            } finally {
22424                super.finalize();
22425            }
22426        }
22427
22428        @Override
22429        public void close() {
22430            mCloseGuard.close();
22431            if (mClosed.compareAndSet(false, true)) {
22432                synchronized (mPackages) {
22433                    if (mWeFroze) {
22434                        mFrozenPackages.remove(mPackageName);
22435                    }
22436
22437                    if (mChildren != null) {
22438                        for (PackageFreezer freezer : mChildren) {
22439                            freezer.close();
22440                        }
22441                    }
22442                }
22443            }
22444        }
22445    }
22446
22447    /**
22448     * Verify that given package is currently frozen.
22449     */
22450    private void checkPackageFrozen(String packageName) {
22451        synchronized (mPackages) {
22452            if (!mFrozenPackages.contains(packageName)) {
22453                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22454            }
22455        }
22456    }
22457
22458    @Override
22459    public int movePackage(final String packageName, final String volumeUuid) {
22460        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22461
22462        final int callingUid = Binder.getCallingUid();
22463        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22464        final int moveId = mNextMoveId.getAndIncrement();
22465        mHandler.post(new Runnable() {
22466            @Override
22467            public void run() {
22468                try {
22469                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22470                } catch (PackageManagerException e) {
22471                    Slog.w(TAG, "Failed to move " + packageName, e);
22472                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22473                }
22474            }
22475        });
22476        return moveId;
22477    }
22478
22479    private void movePackageInternal(final String packageName, final String volumeUuid,
22480            final int moveId, final int callingUid, UserHandle user)
22481                    throws PackageManagerException {
22482        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22483        final PackageManager pm = mContext.getPackageManager();
22484
22485        final boolean currentAsec;
22486        final String currentVolumeUuid;
22487        final File codeFile;
22488        final String installerPackageName;
22489        final String packageAbiOverride;
22490        final int appId;
22491        final String seinfo;
22492        final String label;
22493        final int targetSdkVersion;
22494        final PackageFreezer freezer;
22495        final int[] installedUserIds;
22496
22497        // reader
22498        synchronized (mPackages) {
22499            final PackageParser.Package pkg = mPackages.get(packageName);
22500            final PackageSetting ps = mSettings.mPackages.get(packageName);
22501            if (pkg == null
22502                    || ps == null
22503                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22504                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22505            }
22506            if (pkg.applicationInfo.isSystemApp()) {
22507                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22508                        "Cannot move system application");
22509            }
22510
22511            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22512            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22513                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22514            if (isInternalStorage && !allow3rdPartyOnInternal) {
22515                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22516                        "3rd party apps are not allowed on internal storage");
22517            }
22518
22519            if (pkg.applicationInfo.isExternalAsec()) {
22520                currentAsec = true;
22521                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22522            } else if (pkg.applicationInfo.isForwardLocked()) {
22523                currentAsec = true;
22524                currentVolumeUuid = "forward_locked";
22525            } else {
22526                currentAsec = false;
22527                currentVolumeUuid = ps.volumeUuid;
22528
22529                final File probe = new File(pkg.codePath);
22530                final File probeOat = new File(probe, "oat");
22531                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22532                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22533                            "Move only supported for modern cluster style installs");
22534                }
22535            }
22536
22537            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22538                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22539                        "Package already moved to " + volumeUuid);
22540            }
22541            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22542                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22543                        "Device admin cannot be moved");
22544            }
22545
22546            if (mFrozenPackages.contains(packageName)) {
22547                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22548                        "Failed to move already frozen package");
22549            }
22550
22551            codeFile = new File(pkg.codePath);
22552            installerPackageName = ps.installerPackageName;
22553            packageAbiOverride = ps.cpuAbiOverrideString;
22554            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22555            seinfo = pkg.applicationInfo.seInfo;
22556            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22557            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22558            freezer = freezePackage(packageName, "movePackageInternal");
22559            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22560        }
22561
22562        final Bundle extras = new Bundle();
22563        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22564        extras.putString(Intent.EXTRA_TITLE, label);
22565        mMoveCallbacks.notifyCreated(moveId, extras);
22566
22567        int installFlags;
22568        final boolean moveCompleteApp;
22569        final File measurePath;
22570
22571        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22572            installFlags = INSTALL_INTERNAL;
22573            moveCompleteApp = !currentAsec;
22574            measurePath = Environment.getDataAppDirectory(volumeUuid);
22575        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22576            installFlags = INSTALL_EXTERNAL;
22577            moveCompleteApp = false;
22578            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22579        } else {
22580            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22581            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22582                    || !volume.isMountedWritable()) {
22583                freezer.close();
22584                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22585                        "Move location not mounted private volume");
22586            }
22587
22588            Preconditions.checkState(!currentAsec);
22589
22590            installFlags = INSTALL_INTERNAL;
22591            moveCompleteApp = true;
22592            measurePath = Environment.getDataAppDirectory(volumeUuid);
22593        }
22594
22595        // If we're moving app data around, we need all the users unlocked
22596        if (moveCompleteApp) {
22597            for (int userId : installedUserIds) {
22598                if (StorageManager.isFileEncryptedNativeOrEmulated()
22599                        && !StorageManager.isUserKeyUnlocked(userId)) {
22600                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22601                            "User " + userId + " must be unlocked");
22602                }
22603            }
22604        }
22605
22606        final PackageStats stats = new PackageStats(null, -1);
22607        synchronized (mInstaller) {
22608            for (int userId : installedUserIds) {
22609                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22610                    freezer.close();
22611                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22612                            "Failed to measure package size");
22613                }
22614            }
22615        }
22616
22617        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22618                + stats.dataSize);
22619
22620        final long startFreeBytes = measurePath.getUsableSpace();
22621        final long sizeBytes;
22622        if (moveCompleteApp) {
22623            sizeBytes = stats.codeSize + stats.dataSize;
22624        } else {
22625            sizeBytes = stats.codeSize;
22626        }
22627
22628        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22629            freezer.close();
22630            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22631                    "Not enough free space to move");
22632        }
22633
22634        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22635
22636        final CountDownLatch installedLatch = new CountDownLatch(1);
22637        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22638            @Override
22639            public void onUserActionRequired(Intent intent) throws RemoteException {
22640                throw new IllegalStateException();
22641            }
22642
22643            @Override
22644            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22645                    Bundle extras) throws RemoteException {
22646                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22647                        + PackageManager.installStatusToString(returnCode, msg));
22648
22649                installedLatch.countDown();
22650                freezer.close();
22651
22652                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22653                switch (status) {
22654                    case PackageInstaller.STATUS_SUCCESS:
22655                        mMoveCallbacks.notifyStatusChanged(moveId,
22656                                PackageManager.MOVE_SUCCEEDED);
22657                        break;
22658                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22659                        mMoveCallbacks.notifyStatusChanged(moveId,
22660                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22661                        break;
22662                    default:
22663                        mMoveCallbacks.notifyStatusChanged(moveId,
22664                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22665                        break;
22666                }
22667            }
22668        };
22669
22670        final MoveInfo move;
22671        if (moveCompleteApp) {
22672            // Kick off a thread to report progress estimates
22673            new Thread() {
22674                @Override
22675                public void run() {
22676                    while (true) {
22677                        try {
22678                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22679                                break;
22680                            }
22681                        } catch (InterruptedException ignored) {
22682                        }
22683
22684                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22685                        final int progress = 10 + (int) MathUtils.constrain(
22686                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22687                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22688                    }
22689                }
22690            }.start();
22691
22692            final String dataAppName = codeFile.getName();
22693            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22694                    dataAppName, appId, seinfo, targetSdkVersion);
22695        } else {
22696            move = null;
22697        }
22698
22699        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22700
22701        final Message msg = mHandler.obtainMessage(INIT_COPY);
22702        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22703        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22704                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22705                packageAbiOverride, null /*grantedPermissions*/,
22706                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22707        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22708        msg.obj = params;
22709
22710        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22711                System.identityHashCode(msg.obj));
22712        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22713                System.identityHashCode(msg.obj));
22714
22715        mHandler.sendMessage(msg);
22716    }
22717
22718    @Override
22719    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22720        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22721
22722        final int realMoveId = mNextMoveId.getAndIncrement();
22723        final Bundle extras = new Bundle();
22724        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22725        mMoveCallbacks.notifyCreated(realMoveId, extras);
22726
22727        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22728            @Override
22729            public void onCreated(int moveId, Bundle extras) {
22730                // Ignored
22731            }
22732
22733            @Override
22734            public void onStatusChanged(int moveId, int status, long estMillis) {
22735                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22736            }
22737        };
22738
22739        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22740        storage.setPrimaryStorageUuid(volumeUuid, callback);
22741        return realMoveId;
22742    }
22743
22744    @Override
22745    public int getMoveStatus(int moveId) {
22746        mContext.enforceCallingOrSelfPermission(
22747                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22748        return mMoveCallbacks.mLastStatus.get(moveId);
22749    }
22750
22751    @Override
22752    public void registerMoveCallback(IPackageMoveObserver callback) {
22753        mContext.enforceCallingOrSelfPermission(
22754                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22755        mMoveCallbacks.register(callback);
22756    }
22757
22758    @Override
22759    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22760        mContext.enforceCallingOrSelfPermission(
22761                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22762        mMoveCallbacks.unregister(callback);
22763    }
22764
22765    @Override
22766    public boolean setInstallLocation(int loc) {
22767        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22768                null);
22769        if (getInstallLocation() == loc) {
22770            return true;
22771        }
22772        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22773                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22774            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22775                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22776            return true;
22777        }
22778        return false;
22779   }
22780
22781    @Override
22782    public int getInstallLocation() {
22783        // allow instant app access
22784        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22785                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22786                PackageHelper.APP_INSTALL_AUTO);
22787    }
22788
22789    /** Called by UserManagerService */
22790    void cleanUpUser(UserManagerService userManager, int userHandle) {
22791        synchronized (mPackages) {
22792            mDirtyUsers.remove(userHandle);
22793            mUserNeedsBadging.delete(userHandle);
22794            mSettings.removeUserLPw(userHandle);
22795            mPendingBroadcasts.remove(userHandle);
22796            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22797            removeUnusedPackagesLPw(userManager, userHandle);
22798        }
22799    }
22800
22801    /**
22802     * We're removing userHandle and would like to remove any downloaded packages
22803     * that are no longer in use by any other user.
22804     * @param userHandle the user being removed
22805     */
22806    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22807        final boolean DEBUG_CLEAN_APKS = false;
22808        int [] users = userManager.getUserIds();
22809        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22810        while (psit.hasNext()) {
22811            PackageSetting ps = psit.next();
22812            if (ps.pkg == null) {
22813                continue;
22814            }
22815            final String packageName = ps.pkg.packageName;
22816            // Skip over if system app
22817            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22818                continue;
22819            }
22820            if (DEBUG_CLEAN_APKS) {
22821                Slog.i(TAG, "Checking package " + packageName);
22822            }
22823            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22824            if (keep) {
22825                if (DEBUG_CLEAN_APKS) {
22826                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22827                }
22828            } else {
22829                for (int i = 0; i < users.length; i++) {
22830                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22831                        keep = true;
22832                        if (DEBUG_CLEAN_APKS) {
22833                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22834                                    + users[i]);
22835                        }
22836                        break;
22837                    }
22838                }
22839            }
22840            if (!keep) {
22841                if (DEBUG_CLEAN_APKS) {
22842                    Slog.i(TAG, "  Removing package " + packageName);
22843                }
22844                mHandler.post(new Runnable() {
22845                    public void run() {
22846                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22847                                userHandle, 0);
22848                    } //end run
22849                });
22850            }
22851        }
22852    }
22853
22854    /** Called by UserManagerService */
22855    void createNewUser(int userId, String[] disallowedPackages) {
22856        synchronized (mInstallLock) {
22857            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22858        }
22859        synchronized (mPackages) {
22860            scheduleWritePackageRestrictionsLocked(userId);
22861            scheduleWritePackageListLocked(userId);
22862            applyFactoryDefaultBrowserLPw(userId);
22863            primeDomainVerificationsLPw(userId);
22864        }
22865    }
22866
22867    void onNewUserCreated(final int userId) {
22868        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22869        synchronized(mPackages) {
22870            // If permission review for legacy apps is required, we represent
22871            // dagerous permissions for such apps as always granted runtime
22872            // permissions to keep per user flag state whether review is needed.
22873            // Hence, if a new user is added we have to propagate dangerous
22874            // permission grants for these legacy apps.
22875            if (mSettings.mPermissions.mPermissionReviewRequired) {
22876// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
22877                mPermissionManager.updateAllPermissions(
22878                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
22879                        mPermissionCallback);
22880            }
22881        }
22882    }
22883
22884    @Override
22885    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22886        mContext.enforceCallingOrSelfPermission(
22887                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22888                "Only package verification agents can read the verifier device identity");
22889
22890        synchronized (mPackages) {
22891            return mSettings.getVerifierDeviceIdentityLPw();
22892        }
22893    }
22894
22895    @Override
22896    public void setPermissionEnforced(String permission, boolean enforced) {
22897        // TODO: Now that we no longer change GID for storage, this should to away.
22898        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22899                "setPermissionEnforced");
22900        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22901            synchronized (mPackages) {
22902                if (mSettings.mReadExternalStorageEnforced == null
22903                        || mSettings.mReadExternalStorageEnforced != enforced) {
22904                    mSettings.mReadExternalStorageEnforced =
22905                            enforced ? Boolean.TRUE : Boolean.FALSE;
22906                    mSettings.writeLPr();
22907                }
22908            }
22909            // kill any non-foreground processes so we restart them and
22910            // grant/revoke the GID.
22911            final IActivityManager am = ActivityManager.getService();
22912            if (am != null) {
22913                final long token = Binder.clearCallingIdentity();
22914                try {
22915                    am.killProcessesBelowForeground("setPermissionEnforcement");
22916                } catch (RemoteException e) {
22917                } finally {
22918                    Binder.restoreCallingIdentity(token);
22919                }
22920            }
22921        } else {
22922            throw new IllegalArgumentException("No selective enforcement for " + permission);
22923        }
22924    }
22925
22926    @Override
22927    @Deprecated
22928    public boolean isPermissionEnforced(String permission) {
22929        // allow instant applications
22930        return true;
22931    }
22932
22933    @Override
22934    public boolean isStorageLow() {
22935        // allow instant applications
22936        final long token = Binder.clearCallingIdentity();
22937        try {
22938            final DeviceStorageMonitorInternal
22939                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22940            if (dsm != null) {
22941                return dsm.isMemoryLow();
22942            } else {
22943                return false;
22944            }
22945        } finally {
22946            Binder.restoreCallingIdentity(token);
22947        }
22948    }
22949
22950    @Override
22951    public IPackageInstaller getPackageInstaller() {
22952        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22953            return null;
22954        }
22955        return mInstallerService;
22956    }
22957
22958    @Override
22959    public IArtManager getArtManager() {
22960        return mArtManagerService;
22961    }
22962
22963    private boolean userNeedsBadging(int userId) {
22964        int index = mUserNeedsBadging.indexOfKey(userId);
22965        if (index < 0) {
22966            final UserInfo userInfo;
22967            final long token = Binder.clearCallingIdentity();
22968            try {
22969                userInfo = sUserManager.getUserInfo(userId);
22970            } finally {
22971                Binder.restoreCallingIdentity(token);
22972            }
22973            final boolean b;
22974            if (userInfo != null && userInfo.isManagedProfile()) {
22975                b = true;
22976            } else {
22977                b = false;
22978            }
22979            mUserNeedsBadging.put(userId, b);
22980            return b;
22981        }
22982        return mUserNeedsBadging.valueAt(index);
22983    }
22984
22985    @Override
22986    public KeySet getKeySetByAlias(String packageName, String alias) {
22987        if (packageName == null || alias == null) {
22988            return null;
22989        }
22990        synchronized(mPackages) {
22991            final PackageParser.Package pkg = mPackages.get(packageName);
22992            if (pkg == null) {
22993                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22994                throw new IllegalArgumentException("Unknown package: " + packageName);
22995            }
22996            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22997            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
22998                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
22999                throw new IllegalArgumentException("Unknown package: " + packageName);
23000            }
23001            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23002            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23003        }
23004    }
23005
23006    @Override
23007    public KeySet getSigningKeySet(String packageName) {
23008        if (packageName == null) {
23009            return null;
23010        }
23011        synchronized(mPackages) {
23012            final int callingUid = Binder.getCallingUid();
23013            final int callingUserId = UserHandle.getUserId(callingUid);
23014            final PackageParser.Package pkg = mPackages.get(packageName);
23015            if (pkg == null) {
23016                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23017                throw new IllegalArgumentException("Unknown package: " + packageName);
23018            }
23019            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23020            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23021                // filter and pretend the package doesn't exist
23022                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23023                        + ", uid:" + callingUid);
23024                throw new IllegalArgumentException("Unknown package: " + packageName);
23025            }
23026            if (pkg.applicationInfo.uid != callingUid
23027                    && Process.SYSTEM_UID != callingUid) {
23028                throw new SecurityException("May not access signing KeySet of other apps.");
23029            }
23030            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23031            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23032        }
23033    }
23034
23035    @Override
23036    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23037        final int callingUid = Binder.getCallingUid();
23038        if (getInstantAppPackageName(callingUid) != null) {
23039            return false;
23040        }
23041        if (packageName == null || ks == null) {
23042            return false;
23043        }
23044        synchronized(mPackages) {
23045            final PackageParser.Package pkg = mPackages.get(packageName);
23046            if (pkg == null
23047                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23048                            UserHandle.getUserId(callingUid))) {
23049                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23050                throw new IllegalArgumentException("Unknown package: " + packageName);
23051            }
23052            IBinder ksh = ks.getToken();
23053            if (ksh instanceof KeySetHandle) {
23054                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23055                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23056            }
23057            return false;
23058        }
23059    }
23060
23061    @Override
23062    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23063        final int callingUid = Binder.getCallingUid();
23064        if (getInstantAppPackageName(callingUid) != null) {
23065            return false;
23066        }
23067        if (packageName == null || ks == null) {
23068            return false;
23069        }
23070        synchronized(mPackages) {
23071            final PackageParser.Package pkg = mPackages.get(packageName);
23072            if (pkg == null
23073                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23074                            UserHandle.getUserId(callingUid))) {
23075                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23076                throw new IllegalArgumentException("Unknown package: " + packageName);
23077            }
23078            IBinder ksh = ks.getToken();
23079            if (ksh instanceof KeySetHandle) {
23080                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23081                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23082            }
23083            return false;
23084        }
23085    }
23086
23087    private void deletePackageIfUnusedLPr(final String packageName) {
23088        PackageSetting ps = mSettings.mPackages.get(packageName);
23089        if (ps == null) {
23090            return;
23091        }
23092        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23093            // TODO Implement atomic delete if package is unused
23094            // It is currently possible that the package will be deleted even if it is installed
23095            // after this method returns.
23096            mHandler.post(new Runnable() {
23097                public void run() {
23098                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23099                            0, PackageManager.DELETE_ALL_USERS);
23100                }
23101            });
23102        }
23103    }
23104
23105    /**
23106     * Check and throw if the given before/after packages would be considered a
23107     * downgrade.
23108     */
23109    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23110            throws PackageManagerException {
23111        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23112            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23113                    "Update version code " + after.versionCode + " is older than current "
23114                    + before.getLongVersionCode());
23115        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23116            if (after.baseRevisionCode < before.baseRevisionCode) {
23117                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23118                        "Update base revision code " + after.baseRevisionCode
23119                        + " is older than current " + before.baseRevisionCode);
23120            }
23121
23122            if (!ArrayUtils.isEmpty(after.splitNames)) {
23123                for (int i = 0; i < after.splitNames.length; i++) {
23124                    final String splitName = after.splitNames[i];
23125                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23126                    if (j != -1) {
23127                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23128                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23129                                    "Update split " + splitName + " revision code "
23130                                    + after.splitRevisionCodes[i] + " is older than current "
23131                                    + before.splitRevisionCodes[j]);
23132                        }
23133                    }
23134                }
23135            }
23136        }
23137    }
23138
23139    private static class MoveCallbacks extends Handler {
23140        private static final int MSG_CREATED = 1;
23141        private static final int MSG_STATUS_CHANGED = 2;
23142
23143        private final RemoteCallbackList<IPackageMoveObserver>
23144                mCallbacks = new RemoteCallbackList<>();
23145
23146        private final SparseIntArray mLastStatus = new SparseIntArray();
23147
23148        public MoveCallbacks(Looper looper) {
23149            super(looper);
23150        }
23151
23152        public void register(IPackageMoveObserver callback) {
23153            mCallbacks.register(callback);
23154        }
23155
23156        public void unregister(IPackageMoveObserver callback) {
23157            mCallbacks.unregister(callback);
23158        }
23159
23160        @Override
23161        public void handleMessage(Message msg) {
23162            final SomeArgs args = (SomeArgs) msg.obj;
23163            final int n = mCallbacks.beginBroadcast();
23164            for (int i = 0; i < n; i++) {
23165                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23166                try {
23167                    invokeCallback(callback, msg.what, args);
23168                } catch (RemoteException ignored) {
23169                }
23170            }
23171            mCallbacks.finishBroadcast();
23172            args.recycle();
23173        }
23174
23175        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23176                throws RemoteException {
23177            switch (what) {
23178                case MSG_CREATED: {
23179                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23180                    break;
23181                }
23182                case MSG_STATUS_CHANGED: {
23183                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23184                    break;
23185                }
23186            }
23187        }
23188
23189        private void notifyCreated(int moveId, Bundle extras) {
23190            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23191
23192            final SomeArgs args = SomeArgs.obtain();
23193            args.argi1 = moveId;
23194            args.arg2 = extras;
23195            obtainMessage(MSG_CREATED, args).sendToTarget();
23196        }
23197
23198        private void notifyStatusChanged(int moveId, int status) {
23199            notifyStatusChanged(moveId, status, -1);
23200        }
23201
23202        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23203            Slog.v(TAG, "Move " + moveId + " status " + status);
23204
23205            final SomeArgs args = SomeArgs.obtain();
23206            args.argi1 = moveId;
23207            args.argi2 = status;
23208            args.arg3 = estMillis;
23209            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23210
23211            synchronized (mLastStatus) {
23212                mLastStatus.put(moveId, status);
23213            }
23214        }
23215    }
23216
23217    private final static class OnPermissionChangeListeners extends Handler {
23218        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23219
23220        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23221                new RemoteCallbackList<>();
23222
23223        public OnPermissionChangeListeners(Looper looper) {
23224            super(looper);
23225        }
23226
23227        @Override
23228        public void handleMessage(Message msg) {
23229            switch (msg.what) {
23230                case MSG_ON_PERMISSIONS_CHANGED: {
23231                    final int uid = msg.arg1;
23232                    handleOnPermissionsChanged(uid);
23233                } break;
23234            }
23235        }
23236
23237        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23238            mPermissionListeners.register(listener);
23239
23240        }
23241
23242        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23243            mPermissionListeners.unregister(listener);
23244        }
23245
23246        public void onPermissionsChanged(int uid) {
23247            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23248                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23249            }
23250        }
23251
23252        private void handleOnPermissionsChanged(int uid) {
23253            final int count = mPermissionListeners.beginBroadcast();
23254            try {
23255                for (int i = 0; i < count; i++) {
23256                    IOnPermissionsChangeListener callback = mPermissionListeners
23257                            .getBroadcastItem(i);
23258                    try {
23259                        callback.onPermissionsChanged(uid);
23260                    } catch (RemoteException e) {
23261                        Log.e(TAG, "Permission listener is dead", e);
23262                    }
23263                }
23264            } finally {
23265                mPermissionListeners.finishBroadcast();
23266            }
23267        }
23268    }
23269
23270    private class PackageManagerNative extends IPackageManagerNative.Stub {
23271        @Override
23272        public String[] getNamesForUids(int[] uids) throws RemoteException {
23273            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23274            // massage results so they can be parsed by the native binder
23275            for (int i = results.length - 1; i >= 0; --i) {
23276                if (results[i] == null) {
23277                    results[i] = "";
23278                }
23279            }
23280            return results;
23281        }
23282
23283        // NB: this differentiates between preloads and sideloads
23284        @Override
23285        public String getInstallerForPackage(String packageName) throws RemoteException {
23286            final String installerName = getInstallerPackageName(packageName);
23287            if (!TextUtils.isEmpty(installerName)) {
23288                return installerName;
23289            }
23290            // differentiate between preload and sideload
23291            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23292            ApplicationInfo appInfo = getApplicationInfo(packageName,
23293                                    /*flags*/ 0,
23294                                    /*userId*/ callingUser);
23295            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23296                return "preload";
23297            }
23298            return "";
23299        }
23300
23301        @Override
23302        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23303            try {
23304                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23305                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23306                if (pInfo != null) {
23307                    return pInfo.getLongVersionCode();
23308                }
23309            } catch (Exception e) {
23310            }
23311            return 0;
23312        }
23313    }
23314
23315    private class PackageManagerInternalImpl extends PackageManagerInternal {
23316        @Override
23317        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23318                int flagValues, int userId) {
23319            PackageManagerService.this.updatePermissionFlags(
23320                    permName, packageName, flagMask, flagValues, userId);
23321        }
23322
23323        @Override
23324        public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) {
23325            SigningDetails sd = getSigningDetails(packageName);
23326            if (sd == null) {
23327                return false;
23328            }
23329            return sd.hasSha256Certificate(restoringFromSigHash,
23330                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23331        }
23332
23333        @Override
23334        public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) {
23335            SigningDetails sd = getSigningDetails(packageName);
23336            if (sd == null) {
23337                return false;
23338            }
23339            return sd.hasCertificate(restoringFromSig,
23340                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23341        }
23342
23343        private SigningDetails getSigningDetails(String packageName) {
23344            synchronized (mPackages) {
23345                if (packageName == null) {
23346                    return null;
23347                }
23348                PackageParser.Package p = mPackages.get(packageName);
23349                if (p == null) {
23350                    return null;
23351                }
23352                return p.mSigningDetails;
23353            }
23354        }
23355
23356        @Override
23357        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23358            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23359        }
23360
23361        @Override
23362        public boolean isInstantApp(String packageName, int userId) {
23363            return PackageManagerService.this.isInstantApp(packageName, userId);
23364        }
23365
23366        @Override
23367        public String getInstantAppPackageName(int uid) {
23368            return PackageManagerService.this.getInstantAppPackageName(uid);
23369        }
23370
23371        @Override
23372        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23373            synchronized (mPackages) {
23374                return PackageManagerService.this.filterAppAccessLPr(
23375                        (PackageSetting) pkg.mExtras, callingUid, userId);
23376            }
23377        }
23378
23379        @Override
23380        public PackageParser.Package getPackage(String packageName) {
23381            synchronized (mPackages) {
23382                packageName = resolveInternalPackageNameLPr(
23383                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23384                return mPackages.get(packageName);
23385            }
23386        }
23387
23388        @Override
23389        public PackageList getPackageList(PackageListObserver observer) {
23390            synchronized (mPackages) {
23391                final int N = mPackages.size();
23392                final ArrayList<String> list = new ArrayList<>(N);
23393                for (int i = 0; i < N; i++) {
23394                    list.add(mPackages.keyAt(i));
23395                }
23396                final PackageList packageList = new PackageList(list, observer);
23397                if (observer != null) {
23398                    mPackageListObservers.add(packageList);
23399                }
23400                return packageList;
23401            }
23402        }
23403
23404        @Override
23405        public void removePackageListObserver(PackageListObserver observer) {
23406            synchronized (mPackages) {
23407                mPackageListObservers.remove(observer);
23408            }
23409        }
23410
23411        @Override
23412        public PackageParser.Package getDisabledPackage(String packageName) {
23413            synchronized (mPackages) {
23414                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23415                return (ps != null) ? ps.pkg : null;
23416            }
23417        }
23418
23419        @Override
23420        public String getKnownPackageName(int knownPackage, int userId) {
23421            switch(knownPackage) {
23422                case PackageManagerInternal.PACKAGE_BROWSER:
23423                    return getDefaultBrowserPackageName(userId);
23424                case PackageManagerInternal.PACKAGE_INSTALLER:
23425                    return mRequiredInstallerPackage;
23426                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23427                    return mSetupWizardPackage;
23428                case PackageManagerInternal.PACKAGE_SYSTEM:
23429                    return "android";
23430                case PackageManagerInternal.PACKAGE_VERIFIER:
23431                    return mRequiredVerifierPackage;
23432                case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER:
23433                    return mSystemTextClassifierPackage;
23434            }
23435            return null;
23436        }
23437
23438        @Override
23439        public boolean isResolveActivityComponent(ComponentInfo component) {
23440            return mResolveActivity.packageName.equals(component.packageName)
23441                    && mResolveActivity.name.equals(component.name);
23442        }
23443
23444        @Override
23445        public void setLocationPackagesProvider(PackagesProvider provider) {
23446            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23447        }
23448
23449        @Override
23450        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23451            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23452        }
23453
23454        @Override
23455        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23456            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23457        }
23458
23459        @Override
23460        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23461            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23462        }
23463
23464        @Override
23465        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23466            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23467        }
23468
23469        @Override
23470        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23471            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23472        }
23473
23474        @Override
23475        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23476            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23477        }
23478
23479        @Override
23480        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23481            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23482        }
23483
23484        @Override
23485        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23486            synchronized (mPackages) {
23487                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23488            }
23489            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23490        }
23491
23492        @Override
23493        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23494            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23495                    packageName, userId);
23496        }
23497
23498        @Override
23499        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23500            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23501                    packageName, userId);
23502        }
23503
23504        @Override
23505        public void setKeepUninstalledPackages(final List<String> packageList) {
23506            Preconditions.checkNotNull(packageList);
23507            List<String> removedFromList = null;
23508            synchronized (mPackages) {
23509                if (mKeepUninstalledPackages != null) {
23510                    final int packagesCount = mKeepUninstalledPackages.size();
23511                    for (int i = 0; i < packagesCount; i++) {
23512                        String oldPackage = mKeepUninstalledPackages.get(i);
23513                        if (packageList != null && packageList.contains(oldPackage)) {
23514                            continue;
23515                        }
23516                        if (removedFromList == null) {
23517                            removedFromList = new ArrayList<>();
23518                        }
23519                        removedFromList.add(oldPackage);
23520                    }
23521                }
23522                mKeepUninstalledPackages = new ArrayList<>(packageList);
23523                if (removedFromList != null) {
23524                    final int removedCount = removedFromList.size();
23525                    for (int i = 0; i < removedCount; i++) {
23526                        deletePackageIfUnusedLPr(removedFromList.get(i));
23527                    }
23528                }
23529            }
23530        }
23531
23532        @Override
23533        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23534            synchronized (mPackages) {
23535                return mPermissionManager.isPermissionsReviewRequired(
23536                        mPackages.get(packageName), userId);
23537            }
23538        }
23539
23540        @Override
23541        public PackageInfo getPackageInfo(
23542                String packageName, int flags, int filterCallingUid, int userId) {
23543            return PackageManagerService.this
23544                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23545                            flags, filterCallingUid, userId);
23546        }
23547
23548        @Override
23549        public int getPackageUid(String packageName, int flags, int userId) {
23550            return PackageManagerService.this
23551                    .getPackageUid(packageName, flags, userId);
23552        }
23553
23554        @Override
23555        public ApplicationInfo getApplicationInfo(
23556                String packageName, int flags, int filterCallingUid, int userId) {
23557            return PackageManagerService.this
23558                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23559        }
23560
23561        @Override
23562        public ActivityInfo getActivityInfo(
23563                ComponentName component, int flags, int filterCallingUid, int userId) {
23564            return PackageManagerService.this
23565                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23566        }
23567
23568        @Override
23569        public List<ResolveInfo> queryIntentActivities(
23570                Intent intent, int flags, int filterCallingUid, int userId) {
23571            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23572            return PackageManagerService.this
23573                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23574                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23575        }
23576
23577        @Override
23578        public List<ResolveInfo> queryIntentServices(
23579                Intent intent, int flags, int callingUid, int userId) {
23580            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23581            return PackageManagerService.this
23582                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23583                            false);
23584        }
23585
23586        @Override
23587        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23588                int userId) {
23589            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23590        }
23591
23592        @Override
23593        public void setDeviceAndProfileOwnerPackages(
23594                int deviceOwnerUserId, String deviceOwnerPackage,
23595                SparseArray<String> profileOwnerPackages) {
23596            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23597                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23598        }
23599
23600        @Override
23601        public boolean isPackageDataProtected(int userId, String packageName) {
23602            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23603        }
23604
23605        @Override
23606        public boolean isPackageEphemeral(int userId, String packageName) {
23607            synchronized (mPackages) {
23608                final PackageSetting ps = mSettings.mPackages.get(packageName);
23609                return ps != null ? ps.getInstantApp(userId) : false;
23610            }
23611        }
23612
23613        @Override
23614        public boolean wasPackageEverLaunched(String packageName, int userId) {
23615            synchronized (mPackages) {
23616                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23617            }
23618        }
23619
23620        @Override
23621        public void grantRuntimePermission(String packageName, String permName, int userId,
23622                boolean overridePolicy) {
23623            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23624                    permName, packageName, overridePolicy, getCallingUid(), userId,
23625                    mPermissionCallback);
23626        }
23627
23628        @Override
23629        public void revokeRuntimePermission(String packageName, String permName, int userId,
23630                boolean overridePolicy) {
23631            mPermissionManager.revokeRuntimePermission(
23632                    permName, packageName, overridePolicy, getCallingUid(), userId,
23633                    mPermissionCallback);
23634        }
23635
23636        @Override
23637        public String getNameForUid(int uid) {
23638            return PackageManagerService.this.getNameForUid(uid);
23639        }
23640
23641        @Override
23642        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23643                Intent origIntent, String resolvedType, String callingPackage,
23644                Bundle verificationBundle, int userId) {
23645            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23646                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23647                    userId);
23648        }
23649
23650        @Override
23651        public void grantEphemeralAccess(int userId, Intent intent,
23652                int targetAppId, int ephemeralAppId) {
23653            synchronized (mPackages) {
23654                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23655                        targetAppId, ephemeralAppId);
23656            }
23657        }
23658
23659        @Override
23660        public boolean isInstantAppInstallerComponent(ComponentName component) {
23661            synchronized (mPackages) {
23662                return mInstantAppInstallerActivity != null
23663                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23664            }
23665        }
23666
23667        @Override
23668        public void pruneInstantApps() {
23669            mInstantAppRegistry.pruneInstantApps();
23670        }
23671
23672        @Override
23673        public String getSetupWizardPackageName() {
23674            return mSetupWizardPackage;
23675        }
23676
23677        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23678            if (policy != null) {
23679                mExternalSourcesPolicy = policy;
23680            }
23681        }
23682
23683        @Override
23684        public boolean isPackagePersistent(String packageName) {
23685            synchronized (mPackages) {
23686                PackageParser.Package pkg = mPackages.get(packageName);
23687                return pkg != null
23688                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23689                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23690                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23691                        : false;
23692            }
23693        }
23694
23695        @Override
23696        public boolean isLegacySystemApp(Package pkg) {
23697            synchronized (mPackages) {
23698                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23699                return mPromoteSystemApps
23700                        && ps.isSystem()
23701                        && mExistingSystemPackages.contains(ps.name);
23702            }
23703        }
23704
23705        @Override
23706        public List<PackageInfo> getOverlayPackages(int userId) {
23707            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23708            synchronized (mPackages) {
23709                for (PackageParser.Package p : mPackages.values()) {
23710                    if (p.mOverlayTarget != null) {
23711                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23712                        if (pkg != null) {
23713                            overlayPackages.add(pkg);
23714                        }
23715                    }
23716                }
23717            }
23718            return overlayPackages;
23719        }
23720
23721        @Override
23722        public List<String> getTargetPackageNames(int userId) {
23723            List<String> targetPackages = new ArrayList<>();
23724            synchronized (mPackages) {
23725                for (PackageParser.Package p : mPackages.values()) {
23726                    if (p.mOverlayTarget == null) {
23727                        targetPackages.add(p.packageName);
23728                    }
23729                }
23730            }
23731            return targetPackages;
23732        }
23733
23734        @Override
23735        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23736                @Nullable List<String> overlayPackageNames) {
23737            synchronized (mPackages) {
23738                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23739                    Slog.e(TAG, "failed to find package " + targetPackageName);
23740                    return false;
23741                }
23742                ArrayList<String> overlayPaths = null;
23743                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23744                    final int N = overlayPackageNames.size();
23745                    overlayPaths = new ArrayList<>(N);
23746                    for (int i = 0; i < N; i++) {
23747                        final String packageName = overlayPackageNames.get(i);
23748                        final PackageParser.Package pkg = mPackages.get(packageName);
23749                        if (pkg == null) {
23750                            Slog.e(TAG, "failed to find package " + packageName);
23751                            return false;
23752                        }
23753                        overlayPaths.add(pkg.baseCodePath);
23754                    }
23755                }
23756
23757                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23758                ps.setOverlayPaths(overlayPaths, userId);
23759                return true;
23760            }
23761        }
23762
23763        @Override
23764        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23765                int flags, int userId, boolean resolveForStart) {
23766            return resolveIntentInternal(
23767                    intent, resolvedType, flags, userId, resolveForStart);
23768        }
23769
23770        @Override
23771        public ResolveInfo resolveService(Intent intent, String resolvedType,
23772                int flags, int userId, int callingUid) {
23773            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23774        }
23775
23776        @Override
23777        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23778            return PackageManagerService.this.resolveContentProviderInternal(
23779                    name, flags, userId);
23780        }
23781
23782        @Override
23783        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23784            synchronized (mPackages) {
23785                mIsolatedOwners.put(isolatedUid, ownerUid);
23786            }
23787        }
23788
23789        @Override
23790        public void removeIsolatedUid(int isolatedUid) {
23791            synchronized (mPackages) {
23792                mIsolatedOwners.delete(isolatedUid);
23793            }
23794        }
23795
23796        @Override
23797        public int getUidTargetSdkVersion(int uid) {
23798            synchronized (mPackages) {
23799                return getUidTargetSdkVersionLockedLPr(uid);
23800            }
23801        }
23802
23803        @Override
23804        public int getPackageTargetSdkVersion(String packageName) {
23805            synchronized (mPackages) {
23806                return getPackageTargetSdkVersionLockedLPr(packageName);
23807            }
23808        }
23809
23810        @Override
23811        public boolean canAccessInstantApps(int callingUid, int userId) {
23812            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
23813        }
23814
23815        @Override
23816        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
23817            synchronized (mPackages) {
23818                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
23819            }
23820        }
23821
23822        @Override
23823        public void notifyPackageUse(String packageName, int reason) {
23824            synchronized (mPackages) {
23825                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
23826            }
23827        }
23828    }
23829
23830    @Override
23831    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23832        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23833        synchronized (mPackages) {
23834            final long identity = Binder.clearCallingIdentity();
23835            try {
23836                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
23837                        packageNames, userId);
23838            } finally {
23839                Binder.restoreCallingIdentity(identity);
23840            }
23841        }
23842    }
23843
23844    @Override
23845    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23846        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23847        synchronized (mPackages) {
23848            final long identity = Binder.clearCallingIdentity();
23849            try {
23850                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
23851                        packageNames, userId);
23852            } finally {
23853                Binder.restoreCallingIdentity(identity);
23854            }
23855        }
23856    }
23857
23858    private static void enforceSystemOrPhoneCaller(String tag) {
23859        int callingUid = Binder.getCallingUid();
23860        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23861            throw new SecurityException(
23862                    "Cannot call " + tag + " from UID " + callingUid);
23863        }
23864    }
23865
23866    boolean isHistoricalPackageUsageAvailable() {
23867        return mPackageUsage.isHistoricalPackageUsageAvailable();
23868    }
23869
23870    /**
23871     * Return a <b>copy</b> of the collection of packages known to the package manager.
23872     * @return A copy of the values of mPackages.
23873     */
23874    Collection<PackageParser.Package> getPackages() {
23875        synchronized (mPackages) {
23876            return new ArrayList<>(mPackages.values());
23877        }
23878    }
23879
23880    /**
23881     * Logs process start information (including base APK hash) to the security log.
23882     * @hide
23883     */
23884    @Override
23885    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23886            String apkFile, int pid) {
23887        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23888            return;
23889        }
23890        if (!SecurityLog.isLoggingEnabled()) {
23891            return;
23892        }
23893        Bundle data = new Bundle();
23894        data.putLong("startTimestamp", System.currentTimeMillis());
23895        data.putString("processName", processName);
23896        data.putInt("uid", uid);
23897        data.putString("seinfo", seinfo);
23898        data.putString("apkFile", apkFile);
23899        data.putInt("pid", pid);
23900        Message msg = mProcessLoggingHandler.obtainMessage(
23901                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23902        msg.setData(data);
23903        mProcessLoggingHandler.sendMessage(msg);
23904    }
23905
23906    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23907        return mCompilerStats.getPackageStats(pkgName);
23908    }
23909
23910    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23911        return getOrCreateCompilerPackageStats(pkg.packageName);
23912    }
23913
23914    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23915        return mCompilerStats.getOrCreatePackageStats(pkgName);
23916    }
23917
23918    public void deleteCompilerPackageStats(String pkgName) {
23919        mCompilerStats.deletePackageStats(pkgName);
23920    }
23921
23922    @Override
23923    public int getInstallReason(String packageName, int userId) {
23924        final int callingUid = Binder.getCallingUid();
23925        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23926                true /* requireFullPermission */, false /* checkShell */,
23927                "get install reason");
23928        synchronized (mPackages) {
23929            final PackageSetting ps = mSettings.mPackages.get(packageName);
23930            if (filterAppAccessLPr(ps, callingUid, userId)) {
23931                return PackageManager.INSTALL_REASON_UNKNOWN;
23932            }
23933            if (ps != null) {
23934                return ps.getInstallReason(userId);
23935            }
23936        }
23937        return PackageManager.INSTALL_REASON_UNKNOWN;
23938    }
23939
23940    @Override
23941    public boolean canRequestPackageInstalls(String packageName, int userId) {
23942        return canRequestPackageInstallsInternal(packageName, 0, userId,
23943                true /* throwIfPermNotDeclared*/);
23944    }
23945
23946    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
23947            boolean throwIfPermNotDeclared) {
23948        int callingUid = Binder.getCallingUid();
23949        int uid = getPackageUid(packageName, 0, userId);
23950        if (callingUid != uid && callingUid != Process.ROOT_UID
23951                && callingUid != Process.SYSTEM_UID) {
23952            throw new SecurityException(
23953                    "Caller uid " + callingUid + " does not own package " + packageName);
23954        }
23955        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
23956        if (info == null) {
23957            return false;
23958        }
23959        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23960            return false;
23961        }
23962        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23963        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23964        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23965            if (throwIfPermNotDeclared) {
23966                throw new SecurityException("Need to declare " + appOpPermission
23967                        + " to call this api");
23968            } else {
23969                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
23970                return false;
23971            }
23972        }
23973        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23974            return false;
23975        }
23976        if (mExternalSourcesPolicy != null) {
23977            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23978            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23979                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23980            }
23981        }
23982        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23983    }
23984
23985    @Override
23986    public ComponentName getInstantAppResolverSettingsComponent() {
23987        return mInstantAppResolverSettingsComponent;
23988    }
23989
23990    @Override
23991    public ComponentName getInstantAppInstallerComponent() {
23992        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23993            return null;
23994        }
23995        return mInstantAppInstallerActivity == null
23996                ? null : mInstantAppInstallerActivity.getComponentName();
23997    }
23998
23999    @Override
24000    public String getInstantAppAndroidId(String packageName, int userId) {
24001        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24002                "getInstantAppAndroidId");
24003        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24004                true /* requireFullPermission */, false /* checkShell */,
24005                "getInstantAppAndroidId");
24006        // Make sure the target is an Instant App.
24007        if (!isInstantApp(packageName, userId)) {
24008            return null;
24009        }
24010        synchronized (mPackages) {
24011            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24012        }
24013    }
24014
24015    boolean canHaveOatDir(String packageName) {
24016        synchronized (mPackages) {
24017            PackageParser.Package p = mPackages.get(packageName);
24018            if (p == null) {
24019                return false;
24020            }
24021            return p.canHaveOatDir();
24022        }
24023    }
24024
24025    private String getOatDir(PackageParser.Package pkg) {
24026        if (!pkg.canHaveOatDir()) {
24027            return null;
24028        }
24029        File codePath = new File(pkg.codePath);
24030        if (codePath.isDirectory()) {
24031            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24032        }
24033        return null;
24034    }
24035
24036    void deleteOatArtifactsOfPackage(String packageName) {
24037        final String[] instructionSets;
24038        final List<String> codePaths;
24039        final String oatDir;
24040        final PackageParser.Package pkg;
24041        synchronized (mPackages) {
24042            pkg = mPackages.get(packageName);
24043        }
24044        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24045        codePaths = pkg.getAllCodePaths();
24046        oatDir = getOatDir(pkg);
24047
24048        for (String codePath : codePaths) {
24049            for (String isa : instructionSets) {
24050                try {
24051                    mInstaller.deleteOdex(codePath, isa, oatDir);
24052                } catch (InstallerException e) {
24053                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24054                }
24055            }
24056        }
24057    }
24058
24059    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24060        Set<String> unusedPackages = new HashSet<>();
24061        long currentTimeInMillis = System.currentTimeMillis();
24062        synchronized (mPackages) {
24063            for (PackageParser.Package pkg : mPackages.values()) {
24064                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24065                if (ps == null) {
24066                    continue;
24067                }
24068                PackageDexUsage.PackageUseInfo packageUseInfo =
24069                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24070                if (PackageManagerServiceUtils
24071                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24072                                downgradeTimeThresholdMillis, packageUseInfo,
24073                                pkg.getLatestPackageUseTimeInMills(),
24074                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24075                    unusedPackages.add(pkg.packageName);
24076                }
24077            }
24078        }
24079        return unusedPackages;
24080    }
24081
24082    @Override
24083    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24084            int userId) {
24085        final int callingUid = Binder.getCallingUid();
24086        final int callingAppId = UserHandle.getAppId(callingUid);
24087
24088        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24089                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24090
24091        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24092                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24093            throw new SecurityException("Caller must have the "
24094                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24095        }
24096
24097        synchronized(mPackages) {
24098            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24099            scheduleWritePackageRestrictionsLocked(userId);
24100        }
24101    }
24102
24103    @Nullable
24104    @Override
24105    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24106        final int callingUid = Binder.getCallingUid();
24107        final int callingAppId = UserHandle.getAppId(callingUid);
24108
24109        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24110                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24111
24112        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24113                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24114            throw new SecurityException("Caller must have the "
24115                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24116        }
24117
24118        synchronized(mPackages) {
24119            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24120        }
24121    }
24122}
24123
24124interface PackageSender {
24125    /**
24126     * @param userIds User IDs where the action occurred on a full application
24127     * @param instantUserIds User IDs where the action occurred on an instant application
24128     */
24129    void sendPackageBroadcast(final String action, final String pkg,
24130        final Bundle extras, final int flags, final String targetPkg,
24131        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24132    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24133        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24134    void notifyPackageAdded(String packageName);
24135    void notifyPackageRemoved(String packageName);
24136}
24137