PackageManagerService.java revision 1b794faeace9e992a33b2d8bbd9a56836c459135
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.SET_HARMFUL_APP_WARNINGS;
21import static android.Manifest.permission.INSTALL_PACKAGES;
22import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
23import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
24import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
25import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
26import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
27import static android.content.pm.PackageManager.CERT_INPUT_RAW_X509;
28import static android.content.pm.PackageManager.CERT_INPUT_SHA256;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
31import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
32import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
33import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
34import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
39import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
40import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
41import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
42import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
43import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
44import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
45import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
50import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
51import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
52import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
53import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
54import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
57import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
58import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.isApkFile;
86import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
87import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
88import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
89import static android.system.OsConstants.O_CREAT;
90import static android.system.OsConstants.O_RDWR;
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendInt;
96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
104import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
105import static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
106import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
107import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
108import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
109import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
110import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
111import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
115
116import android.Manifest;
117import android.annotation.IntDef;
118import android.annotation.NonNull;
119import android.annotation.Nullable;
120import android.app.ActivityManager;
121import android.app.ActivityManagerInternal;
122import android.app.AppOpsManager;
123import android.app.IActivityManager;
124import android.app.ResourcesManager;
125import android.app.admin.IDevicePolicyManager;
126import android.app.admin.SecurityLog;
127import android.app.backup.IBackupManager;
128import android.content.BroadcastReceiver;
129import android.content.ComponentName;
130import android.content.ContentResolver;
131import android.content.Context;
132import android.content.IIntentReceiver;
133import android.content.Intent;
134import android.content.IntentFilter;
135import android.content.IntentSender;
136import android.content.IntentSender.SendIntentException;
137import android.content.ServiceConnection;
138import android.content.pm.ActivityInfo;
139import android.content.pm.ApplicationInfo;
140import android.content.pm.AppsQueryHelper;
141import android.content.pm.AuxiliaryResolveInfo;
142import android.content.pm.ChangedPackages;
143import android.content.pm.ComponentInfo;
144import android.content.pm.FallbackCategoryProvider;
145import android.content.pm.FeatureInfo;
146import android.content.pm.IDexModuleRegisterCallback;
147import android.content.pm.IOnPermissionsChangeListener;
148import android.content.pm.IPackageDataObserver;
149import android.content.pm.IPackageDeleteObserver;
150import android.content.pm.IPackageDeleteObserver2;
151import android.content.pm.IPackageInstallObserver2;
152import android.content.pm.IPackageInstaller;
153import android.content.pm.IPackageManager;
154import android.content.pm.IPackageManagerNative;
155import android.content.pm.IPackageMoveObserver;
156import android.content.pm.IPackageStatsObserver;
157import android.content.pm.InstantAppInfo;
158import android.content.pm.InstantAppRequest;
159import android.content.pm.InstantAppResolveInfo;
160import android.content.pm.InstrumentationInfo;
161import android.content.pm.IntentFilterVerificationInfo;
162import android.content.pm.KeySet;
163import android.content.pm.PackageCleanItem;
164import android.content.pm.PackageInfo;
165import android.content.pm.PackageInfoLite;
166import android.content.pm.PackageInstaller;
167import android.content.pm.PackageList;
168import android.content.pm.PackageManager;
169import android.content.pm.PackageManagerInternal;
170import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
171import android.content.pm.PackageManagerInternal.PackageListObserver;
172import android.content.pm.PackageParser;
173import android.content.pm.PackageParser.ActivityIntentInfo;
174import android.content.pm.PackageParser.Package;
175import android.content.pm.PackageParser.PackageLite;
176import android.content.pm.PackageParser.PackageParserException;
177import android.content.pm.PackageParser.ParseFlags;
178import android.content.pm.PackageParser.ServiceIntentInfo;
179import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion;
180import android.content.pm.PackageStats;
181import android.content.pm.PackageUserState;
182import android.content.pm.ParceledListSlice;
183import android.content.pm.PermissionGroupInfo;
184import android.content.pm.PermissionInfo;
185import android.content.pm.ProviderInfo;
186import android.content.pm.ResolveInfo;
187import android.content.pm.ServiceInfo;
188import android.content.pm.SharedLibraryInfo;
189import android.content.pm.Signature;
190import android.content.pm.UserInfo;
191import android.content.pm.VerifierDeviceIdentity;
192import android.content.pm.VerifierInfo;
193import android.content.pm.VersionedPackage;
194import android.content.pm.dex.ArtManager;
195import android.content.pm.dex.DexMetadataHelper;
196import android.content.pm.dex.IArtManager;
197import android.content.res.Resources;
198import android.database.ContentObserver;
199import android.graphics.Bitmap;
200import android.hardware.display.DisplayManager;
201import android.net.Uri;
202import android.os.Binder;
203import android.os.Build;
204import android.os.Bundle;
205import android.os.Debug;
206import android.os.Environment;
207import android.os.Environment.UserEnvironment;
208import android.os.FileUtils;
209import android.os.Handler;
210import android.os.IBinder;
211import android.os.Looper;
212import android.os.Message;
213import android.os.Parcel;
214import android.os.ParcelFileDescriptor;
215import android.os.PatternMatcher;
216import android.os.Process;
217import android.os.RemoteCallbackList;
218import android.os.RemoteException;
219import android.os.ResultReceiver;
220import android.os.SELinux;
221import android.os.ServiceManager;
222import android.os.ShellCallback;
223import android.os.SystemClock;
224import android.os.SystemProperties;
225import android.os.Trace;
226import android.os.UserHandle;
227import android.os.UserManager;
228import android.os.UserManagerInternal;
229import android.os.storage.IStorageManager;
230import android.os.storage.StorageEventListener;
231import android.os.storage.StorageManager;
232import android.os.storage.StorageManagerInternal;
233import android.os.storage.VolumeInfo;
234import android.os.storage.VolumeRecord;
235import android.provider.Settings.Global;
236import android.provider.Settings.Secure;
237import android.security.KeyStore;
238import android.security.SystemKeyStore;
239import android.service.pm.PackageServiceDumpProto;
240import android.system.ErrnoException;
241import android.system.Os;
242import android.text.TextUtils;
243import android.text.format.DateUtils;
244import android.util.ArrayMap;
245import android.util.ArraySet;
246import android.util.Base64;
247import android.util.ByteStringUtils;
248import android.util.DisplayMetrics;
249import android.util.EventLog;
250import android.util.ExceptionUtils;
251import android.util.Log;
252import android.util.LogPrinter;
253import android.util.LongSparseArray;
254import android.util.LongSparseLongArray;
255import android.util.MathUtils;
256import android.util.PackageUtils;
257import android.util.Pair;
258import android.util.PrintStreamPrinter;
259import android.util.Slog;
260import android.util.SparseArray;
261import android.util.SparseBooleanArray;
262import android.util.SparseIntArray;
263import android.util.TimingsTraceLog;
264import android.util.Xml;
265import android.util.jar.StrictJarFile;
266import android.util.proto.ProtoOutputStream;
267import android.view.Display;
268
269import com.android.internal.R;
270import com.android.internal.annotations.GuardedBy;
271import com.android.internal.app.IMediaContainerService;
272import com.android.internal.app.ResolverActivity;
273import com.android.internal.content.NativeLibraryHelper;
274import com.android.internal.content.PackageHelper;
275import com.android.internal.logging.MetricsLogger;
276import com.android.internal.os.IParcelFileDescriptorFactory;
277import com.android.internal.os.SomeArgs;
278import com.android.internal.os.Zygote;
279import com.android.internal.telephony.CarrierAppUtils;
280import com.android.internal.util.ArrayUtils;
281import com.android.internal.util.ConcurrentUtils;
282import com.android.internal.util.DumpUtils;
283import com.android.internal.util.FastXmlSerializer;
284import com.android.internal.util.IndentingPrintWriter;
285import com.android.internal.util.Preconditions;
286import com.android.internal.util.XmlUtils;
287import com.android.server.AttributeCache;
288import com.android.server.DeviceIdleController;
289import com.android.server.EventLogTags;
290import com.android.server.FgThread;
291import com.android.server.IntentResolver;
292import com.android.server.LocalServices;
293import com.android.server.LockGuard;
294import com.android.server.ServiceThread;
295import com.android.server.SystemConfig;
296import com.android.server.SystemServerInitThreadPool;
297import com.android.server.Watchdog;
298import com.android.server.net.NetworkPolicyManagerInternal;
299import com.android.server.pm.Installer.InstallerException;
300import com.android.server.pm.Settings.DatabaseVersion;
301import com.android.server.pm.Settings.VersionInfo;
302import com.android.server.pm.dex.ArtManagerService;
303import com.android.server.pm.dex.DexLogger;
304import com.android.server.pm.dex.DexManager;
305import com.android.server.pm.dex.DexoptOptions;
306import com.android.server.pm.dex.PackageDexUsage;
307import com.android.server.pm.permission.BasePermission;
308import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
309import com.android.server.pm.permission.PermissionManagerService;
310import com.android.server.pm.permission.PermissionManagerInternal;
311import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
312import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
313import com.android.server.pm.permission.PermissionsState;
314import com.android.server.pm.permission.PermissionsState.PermissionState;
315import com.android.server.security.VerityUtils;
316import com.android.server.storage.DeviceStorageMonitorInternal;
317
318import dalvik.system.CloseGuard;
319import dalvik.system.VMRuntime;
320
321import libcore.io.IoUtils;
322
323import org.xmlpull.v1.XmlPullParser;
324import org.xmlpull.v1.XmlPullParserException;
325import org.xmlpull.v1.XmlSerializer;
326
327import java.io.BufferedOutputStream;
328import java.io.ByteArrayInputStream;
329import java.io.ByteArrayOutputStream;
330import java.io.File;
331import java.io.FileDescriptor;
332import java.io.FileInputStream;
333import java.io.FileOutputStream;
334import java.io.FilenameFilter;
335import java.io.IOException;
336import java.io.PrintWriter;
337import java.lang.annotation.Retention;
338import java.lang.annotation.RetentionPolicy;
339import java.nio.charset.StandardCharsets;
340import java.security.DigestException;
341import java.security.DigestInputStream;
342import java.security.MessageDigest;
343import java.security.NoSuchAlgorithmException;
344import java.security.PublicKey;
345import java.security.SecureRandom;
346import java.security.cert.CertificateException;
347import java.util.ArrayList;
348import java.util.Arrays;
349import java.util.Collection;
350import java.util.Collections;
351import java.util.Comparator;
352import java.util.HashMap;
353import java.util.HashSet;
354import java.util.Iterator;
355import java.util.LinkedHashSet;
356import java.util.List;
357import java.util.Map;
358import java.util.Objects;
359import java.util.Set;
360import java.util.concurrent.CountDownLatch;
361import java.util.concurrent.Future;
362import java.util.concurrent.TimeUnit;
363import java.util.concurrent.atomic.AtomicBoolean;
364import java.util.concurrent.atomic.AtomicInteger;
365
366/**
367 * Keep track of all those APKs everywhere.
368 * <p>
369 * Internally there are two important locks:
370 * <ul>
371 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
372 * and other related state. It is a fine-grained lock that should only be held
373 * momentarily, as it's one of the most contended locks in the system.
374 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
375 * operations typically involve heavy lifting of application data on disk. Since
376 * {@code installd} is single-threaded, and it's operations can often be slow,
377 * this lock should never be acquired while already holding {@link #mPackages}.
378 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
379 * holding {@link #mInstallLock}.
380 * </ul>
381 * Many internal methods rely on the caller to hold the appropriate locks, and
382 * this contract is expressed through method name suffixes:
383 * <ul>
384 * <li>fooLI(): the caller must hold {@link #mInstallLock}
385 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
386 * being modified must be frozen
387 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
388 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
389 * </ul>
390 * <p>
391 * Because this class is very central to the platform's security; please run all
392 * CTS and unit tests whenever making modifications:
393 *
394 * <pre>
395 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
396 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
397 * </pre>
398 */
399public class PackageManagerService extends IPackageManager.Stub
400        implements PackageSender {
401    static final String TAG = "PackageManager";
402    public static final boolean DEBUG_SETTINGS = false;
403    static final boolean DEBUG_PREFERRED = false;
404    static final boolean DEBUG_UPGRADE = false;
405    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
406    private static final boolean DEBUG_BACKUP = false;
407    public static final boolean DEBUG_INSTALL = false;
408    public static final boolean DEBUG_REMOVE = false;
409    private static final boolean DEBUG_BROADCASTS = false;
410    private static final boolean DEBUG_SHOW_INFO = false;
411    private static final boolean DEBUG_PACKAGE_INFO = false;
412    private static final boolean DEBUG_INTENT_MATCHING = false;
413    public static final boolean DEBUG_PACKAGE_SCANNING = false;
414    private static final boolean DEBUG_VERIFY = false;
415    private static final boolean DEBUG_FILTERS = false;
416    public static final boolean DEBUG_PERMISSIONS = false;
417    private static final boolean DEBUG_SHARED_LIBRARIES = false;
418    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
419
420    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
421    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
422    // user, but by default initialize to this.
423    public static final boolean DEBUG_DEXOPT = false;
424
425    private static final boolean DEBUG_ABI_SELECTION = false;
426    private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
427    private static final boolean DEBUG_TRIAGED_MISSING = false;
428    private static final boolean DEBUG_APP_DATA = false;
429
430    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
431    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
432
433    private static final boolean HIDE_EPHEMERAL_APIS = false;
434
435    private static final boolean ENABLE_FREE_CACHE_V2 =
436            SystemProperties.getBoolean("fw.free_cache_v2", true);
437
438    private static final int RADIO_UID = Process.PHONE_UID;
439    private static final int LOG_UID = Process.LOG_UID;
440    private static final int NFC_UID = Process.NFC_UID;
441    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
442    private static final int SHELL_UID = Process.SHELL_UID;
443    private static final int SE_UID = Process.SE_UID;
444
445    // Suffix used during package installation when copying/moving
446    // package apks to install directory.
447    private static final String INSTALL_PACKAGE_SUFFIX = "-";
448
449    static final int SCAN_NO_DEX = 1<<0;
450    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
451    static final int SCAN_NEW_INSTALL = 1<<2;
452    static final int SCAN_UPDATE_TIME = 1<<3;
453    static final int SCAN_BOOTING = 1<<4;
454    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
455    static final int SCAN_REQUIRE_KNOWN = 1<<7;
456    static final int SCAN_MOVE = 1<<8;
457    static final int SCAN_INITIAL = 1<<9;
458    static final int SCAN_CHECK_ONLY = 1<<10;
459    static final int SCAN_DONT_KILL_APP = 1<<11;
460    static final int SCAN_IGNORE_FROZEN = 1<<12;
461    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
462    static final int SCAN_AS_INSTANT_APP = 1<<14;
463    static final int SCAN_AS_FULL_APP = 1<<15;
464    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
465    static final int SCAN_AS_SYSTEM = 1<<17;
466    static final int SCAN_AS_PRIVILEGED = 1<<18;
467    static final int SCAN_AS_OEM = 1<<19;
468    static final int SCAN_AS_VENDOR = 1<<20;
469    static final int SCAN_AS_PRODUCT = 1<<21;
470
471    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
472            SCAN_NO_DEX,
473            SCAN_UPDATE_SIGNATURE,
474            SCAN_NEW_INSTALL,
475            SCAN_UPDATE_TIME,
476            SCAN_BOOTING,
477            SCAN_DELETE_DATA_ON_FAILURES,
478            SCAN_REQUIRE_KNOWN,
479            SCAN_MOVE,
480            SCAN_INITIAL,
481            SCAN_CHECK_ONLY,
482            SCAN_DONT_KILL_APP,
483            SCAN_IGNORE_FROZEN,
484            SCAN_FIRST_BOOT_OR_UPGRADE,
485            SCAN_AS_INSTANT_APP,
486            SCAN_AS_FULL_APP,
487            SCAN_AS_VIRTUAL_PRELOAD,
488    })
489    @Retention(RetentionPolicy.SOURCE)
490    public @interface ScanFlags {}
491
492    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
493    /** Extension of the compressed packages */
494    public final static String COMPRESSED_EXTENSION = ".gz";
495    /** Suffix of stub packages on the system partition */
496    public final static String STUB_SUFFIX = "-Stub";
497
498    private static final int[] EMPTY_INT_ARRAY = new int[0];
499
500    private static final int TYPE_UNKNOWN = 0;
501    private static final int TYPE_ACTIVITY = 1;
502    private static final int TYPE_RECEIVER = 2;
503    private static final int TYPE_SERVICE = 3;
504    private static final int TYPE_PROVIDER = 4;
505    @IntDef(prefix = { "TYPE_" }, value = {
506            TYPE_UNKNOWN,
507            TYPE_ACTIVITY,
508            TYPE_RECEIVER,
509            TYPE_SERVICE,
510            TYPE_PROVIDER,
511    })
512    @Retention(RetentionPolicy.SOURCE)
513    public @interface ComponentType {}
514
515    /**
516     * Timeout (in milliseconds) after which the watchdog should declare that
517     * our handler thread is wedged.  The usual default for such things is one
518     * minute but we sometimes do very lengthy I/O operations on this thread,
519     * such as installing multi-gigabyte applications, so ours needs to be longer.
520     */
521    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
522
523    /**
524     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
525     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
526     * settings entry if available, otherwise we use the hardcoded default.  If it's been
527     * more than this long since the last fstrim, we force one during the boot sequence.
528     *
529     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
530     * one gets run at the next available charging+idle time.  This final mandatory
531     * no-fstrim check kicks in only of the other scheduling criteria is never met.
532     */
533    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
534
535    /**
536     * Whether verification is enabled by default.
537     */
538    private static final boolean DEFAULT_VERIFY_ENABLE = true;
539
540    /**
541     * The default maximum time to wait for the verification agent to return in
542     * milliseconds.
543     */
544    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
545
546    /**
547     * The default response for package verification timeout.
548     *
549     * This can be either PackageManager.VERIFICATION_ALLOW or
550     * PackageManager.VERIFICATION_REJECT.
551     */
552    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
553
554    public static final String PLATFORM_PACKAGE_NAME = "android";
555
556    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
557
558    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
559            DEFAULT_CONTAINER_PACKAGE,
560            "com.android.defcontainer.DefaultContainerService");
561
562    private static final String KILL_APP_REASON_GIDS_CHANGED =
563            "permission grant or revoke changed gids";
564
565    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
566            "permissions revoked";
567
568    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
569
570    private static final String PACKAGE_SCHEME = "package";
571
572    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
573
574    private static final String PRODUCT_OVERLAY_DIR = "/product/overlay";
575
576    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
577
578    /** Canonical intent used to identify what counts as a "web browser" app */
579    private static final Intent sBrowserIntent;
580    static {
581        sBrowserIntent = new Intent();
582        sBrowserIntent.setAction(Intent.ACTION_VIEW);
583        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
584        sBrowserIntent.setData(Uri.parse("http:"));
585        sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
586    }
587
588    /**
589     * The set of all protected actions [i.e. those actions for which a high priority
590     * intent filter is disallowed].
591     */
592    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
593    static {
594        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
595        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
596        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
597        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
598    }
599
600    // Compilation reasons.
601    public static final int REASON_FIRST_BOOT = 0;
602    public static final int REASON_BOOT = 1;
603    public static final int REASON_INSTALL = 2;
604    public static final int REASON_BACKGROUND_DEXOPT = 3;
605    public static final int REASON_AB_OTA = 4;
606    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
607    public static final int REASON_SHARED = 6;
608
609    public static final int REASON_LAST = REASON_SHARED;
610
611    /**
612     * Version number for the package parser cache. Increment this whenever the format or
613     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
614     */
615    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
616
617    /**
618     * Whether the package parser cache is enabled.
619     */
620    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
621
622    /**
623     * Permissions required in order to receive instant application lifecycle broadcasts.
624     */
625    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
626            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
627
628    final ServiceThread mHandlerThread;
629
630    final PackageHandler mHandler;
631
632    private final ProcessLoggingHandler mProcessLoggingHandler;
633
634    /**
635     * Messages for {@link #mHandler} that need to wait for system ready before
636     * being dispatched.
637     */
638    private ArrayList<Message> mPostSystemReadyMessages;
639
640    final int mSdkVersion = Build.VERSION.SDK_INT;
641
642    final Context mContext;
643    final boolean mFactoryTest;
644    final boolean mOnlyCore;
645    final DisplayMetrics mMetrics;
646    final int mDefParseFlags;
647    final String[] mSeparateProcesses;
648    final boolean mIsUpgrade;
649    final boolean mIsPreNUpgrade;
650    final boolean mIsPreNMR1Upgrade;
651
652    // Have we told the Activity Manager to whitelist the default container service by uid yet?
653    @GuardedBy("mPackages")
654    boolean mDefaultContainerWhitelisted = false;
655
656    @GuardedBy("mPackages")
657    private boolean mDexOptDialogShown;
658
659    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
660    // LOCK HELD.  Can be called with mInstallLock held.
661    @GuardedBy("mInstallLock")
662    final Installer mInstaller;
663
664    /** Directory where installed applications are stored */
665    private static final File sAppInstallDir =
666            new File(Environment.getDataDirectory(), "app");
667    /** Directory where installed application's 32-bit native libraries are copied. */
668    private static final File sAppLib32InstallDir =
669            new File(Environment.getDataDirectory(), "app-lib");
670    /** Directory where code and non-resource assets of forward-locked applications are stored */
671    private static final File sDrmAppPrivateInstallDir =
672            new File(Environment.getDataDirectory(), "app-private");
673
674    // ----------------------------------------------------------------
675
676    // Lock for state used when installing and doing other long running
677    // operations.  Methods that must be called with this lock held have
678    // the suffix "LI".
679    final Object mInstallLock = new Object();
680
681    // ----------------------------------------------------------------
682
683    // Keys are String (package name), values are Package.  This also serves
684    // as the lock for the global state.  Methods that must be called with
685    // this lock held have the prefix "LP".
686    @GuardedBy("mPackages")
687    final ArrayMap<String, PackageParser.Package> mPackages =
688            new ArrayMap<String, PackageParser.Package>();
689
690    final ArrayMap<String, Set<String>> mKnownCodebase =
691            new ArrayMap<String, Set<String>>();
692
693    // Keys are isolated uids and values are the uid of the application
694    // that created the isolated proccess.
695    @GuardedBy("mPackages")
696    final SparseIntArray mIsolatedOwners = new SparseIntArray();
697
698    /**
699     * Tracks new system packages [received in an OTA] that we expect to
700     * find updated user-installed versions. Keys are package name, values
701     * are package location.
702     */
703    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
704    /**
705     * Tracks high priority intent filters for protected actions. During boot, certain
706     * filter actions are protected and should never be allowed to have a high priority
707     * intent filter for them. However, there is one, and only one exception -- the
708     * setup wizard. It must be able to define a high priority intent filter for these
709     * actions to ensure there are no escapes from the wizard. We need to delay processing
710     * of these during boot as we need to look at all of the system packages in order
711     * to know which component is the setup wizard.
712     */
713    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
714    /**
715     * Whether or not processing protected filters should be deferred.
716     */
717    private boolean mDeferProtectedFilters = true;
718
719    /**
720     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
721     */
722    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
723    /**
724     * Whether or not system app permissions should be promoted from install to runtime.
725     */
726    boolean mPromoteSystemApps;
727
728    @GuardedBy("mPackages")
729    final Settings mSettings;
730
731    /**
732     * Set of package names that are currently "frozen", which means active
733     * surgery is being done on the code/data for that package. The platform
734     * will refuse to launch frozen packages to avoid race conditions.
735     *
736     * @see PackageFreezer
737     */
738    @GuardedBy("mPackages")
739    final ArraySet<String> mFrozenPackages = new ArraySet<>();
740
741    final ProtectedPackages mProtectedPackages;
742
743    @GuardedBy("mLoadedVolumes")
744    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
745
746    boolean mFirstBoot;
747
748    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
749
750    @GuardedBy("mAvailableFeatures")
751    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
752
753    private final InstantAppRegistry mInstantAppRegistry;
754
755    @GuardedBy("mPackages")
756    int mChangedPackagesSequenceNumber;
757    /**
758     * List of changed [installed, removed or updated] packages.
759     * mapping from user id -> sequence number -> package name
760     */
761    @GuardedBy("mPackages")
762    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
763    /**
764     * The sequence number of the last change to a package.
765     * mapping from user id -> package name -> sequence number
766     */
767    @GuardedBy("mPackages")
768    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
769
770    @GuardedBy("mPackages")
771    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
772
773    class PackageParserCallback implements PackageParser.Callback {
774        @Override public final boolean hasFeature(String feature) {
775            return PackageManagerService.this.hasSystemFeature(feature, 0);
776        }
777
778        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
779                Collection<PackageParser.Package> allPackages, String targetPackageName) {
780            List<PackageParser.Package> overlayPackages = null;
781            for (PackageParser.Package p : allPackages) {
782                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
783                    if (overlayPackages == null) {
784                        overlayPackages = new ArrayList<PackageParser.Package>();
785                    }
786                    overlayPackages.add(p);
787                }
788            }
789            if (overlayPackages != null) {
790                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
791                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
792                        return p1.mOverlayPriority - p2.mOverlayPriority;
793                    }
794                };
795                Collections.sort(overlayPackages, cmp);
796            }
797            return overlayPackages;
798        }
799
800        @GuardedBy("mInstallLock")
801        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
802                String targetPackageName, String targetPath) {
803            if ("android".equals(targetPackageName)) {
804                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
805                // native AssetManager.
806                return null;
807            }
808            List<PackageParser.Package> overlayPackages =
809                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
810            if (overlayPackages == null || overlayPackages.isEmpty()) {
811                return null;
812            }
813            List<String> overlayPathList = null;
814            for (PackageParser.Package overlayPackage : overlayPackages) {
815                if (targetPath == null) {
816                    if (overlayPathList == null) {
817                        overlayPathList = new ArrayList<String>();
818                    }
819                    overlayPathList.add(overlayPackage.baseCodePath);
820                    continue;
821                }
822
823                try {
824                    // Creates idmaps for system to parse correctly the Android manifest of the
825                    // target package.
826                    //
827                    // OverlayManagerService will update each of them with a correct gid from its
828                    // target package app id.
829                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
830                            UserHandle.getSharedAppGid(
831                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
832                    if (overlayPathList == null) {
833                        overlayPathList = new ArrayList<String>();
834                    }
835                    overlayPathList.add(overlayPackage.baseCodePath);
836                } catch (InstallerException e) {
837                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
838                            overlayPackage.baseCodePath);
839                }
840            }
841            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
842        }
843
844        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
845            synchronized (mPackages) {
846                return getStaticOverlayPathsLocked(
847                        mPackages.values(), targetPackageName, targetPath);
848            }
849        }
850
851        @Override public final String[] getOverlayApks(String targetPackageName) {
852            return getStaticOverlayPaths(targetPackageName, null);
853        }
854
855        @Override public final String[] getOverlayPaths(String targetPackageName,
856                String targetPath) {
857            return getStaticOverlayPaths(targetPackageName, targetPath);
858        }
859    }
860
861    class ParallelPackageParserCallback extends PackageParserCallback {
862        List<PackageParser.Package> mOverlayPackages = null;
863
864        void findStaticOverlayPackages() {
865            synchronized (mPackages) {
866                for (PackageParser.Package p : mPackages.values()) {
867                    if (p.mOverlayIsStatic) {
868                        if (mOverlayPackages == null) {
869                            mOverlayPackages = new ArrayList<PackageParser.Package>();
870                        }
871                        mOverlayPackages.add(p);
872                    }
873                }
874            }
875        }
876
877        @Override
878        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
879            // We can trust mOverlayPackages without holding mPackages because package uninstall
880            // can't happen while running parallel parsing.
881            // Moreover holding mPackages on each parsing thread causes dead-lock.
882            return mOverlayPackages == null ? null :
883                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
884        }
885    }
886
887    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
888    final ParallelPackageParserCallback mParallelPackageParserCallback =
889            new ParallelPackageParserCallback();
890
891    public static final class SharedLibraryEntry {
892        public final @Nullable String path;
893        public final @Nullable String apk;
894        public final @NonNull SharedLibraryInfo info;
895
896        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
897                String declaringPackageName, long declaringPackageVersionCode) {
898            path = _path;
899            apk = _apk;
900            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
901                    declaringPackageName, declaringPackageVersionCode), null);
902        }
903    }
904
905    // Currently known shared libraries.
906    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
907    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
908            new ArrayMap<>();
909
910    // All available activities, for your resolving pleasure.
911    final ActivityIntentResolver mActivities =
912            new ActivityIntentResolver();
913
914    // All available receivers, for your resolving pleasure.
915    final ActivityIntentResolver mReceivers =
916            new ActivityIntentResolver();
917
918    // All available services, for your resolving pleasure.
919    final ServiceIntentResolver mServices = new ServiceIntentResolver();
920
921    // All available providers, for your resolving pleasure.
922    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
923
924    // Mapping from provider base names (first directory in content URI codePath)
925    // to the provider information.
926    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
927            new ArrayMap<String, PackageParser.Provider>();
928
929    // Mapping from instrumentation class names to info about them.
930    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
931            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
932
933    // Packages whose data we have transfered into another package, thus
934    // should no longer exist.
935    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
936
937    // Broadcast actions that are only available to the system.
938    @GuardedBy("mProtectedBroadcasts")
939    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
940
941    /** List of packages waiting for verification. */
942    final SparseArray<PackageVerificationState> mPendingVerification
943            = new SparseArray<PackageVerificationState>();
944
945    final PackageInstallerService mInstallerService;
946
947    final ArtManagerService mArtManagerService;
948
949    private final PackageDexOptimizer mPackageDexOptimizer;
950    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
951    // is used by other apps).
952    private final DexManager mDexManager;
953
954    private AtomicInteger mNextMoveId = new AtomicInteger();
955    private final MoveCallbacks mMoveCallbacks;
956
957    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
958
959    // Cache of users who need badging.
960    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
961
962    /** Token for keys in mPendingVerification. */
963    private int mPendingVerificationToken = 0;
964
965    volatile boolean mSystemReady;
966    volatile boolean mSafeMode;
967    volatile boolean mHasSystemUidErrors;
968    private volatile boolean mEphemeralAppsDisabled;
969
970    ApplicationInfo mAndroidApplication;
971    final ActivityInfo mResolveActivity = new ActivityInfo();
972    final ResolveInfo mResolveInfo = new ResolveInfo();
973    ComponentName mResolveComponentName;
974    PackageParser.Package mPlatformPackage;
975    ComponentName mCustomResolverComponentName;
976
977    boolean mResolverReplaced = false;
978
979    private final @Nullable ComponentName mIntentFilterVerifierComponent;
980    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
981
982    private int mIntentFilterVerificationToken = 0;
983
984    /** The service connection to the ephemeral resolver */
985    final InstantAppResolverConnection mInstantAppResolverConnection;
986    /** Component used to show resolver settings for Instant Apps */
987    final ComponentName mInstantAppResolverSettingsComponent;
988
989    /** Activity used to install instant applications */
990    ActivityInfo mInstantAppInstallerActivity;
991    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
992
993    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
994            = new SparseArray<IntentFilterVerificationState>();
995
996    // TODO remove this and go through mPermissonManager directly
997    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
998    private final PermissionManagerInternal mPermissionManager;
999
1000    // List of packages names to keep cached, even if they are uninstalled for all users
1001    private List<String> mKeepUninstalledPackages;
1002
1003    private UserManagerInternal mUserManagerInternal;
1004    private ActivityManagerInternal mActivityManagerInternal;
1005
1006    private DeviceIdleController.LocalService mDeviceIdleController;
1007
1008    private File mCacheDir;
1009
1010    private Future<?> mPrepareAppDataFuture;
1011
1012    private static class IFVerificationParams {
1013        PackageParser.Package pkg;
1014        boolean replacing;
1015        int userId;
1016        int verifierUid;
1017
1018        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1019                int _userId, int _verifierUid) {
1020            pkg = _pkg;
1021            replacing = _replacing;
1022            userId = _userId;
1023            replacing = _replacing;
1024            verifierUid = _verifierUid;
1025        }
1026    }
1027
1028    private interface IntentFilterVerifier<T extends IntentFilter> {
1029        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1030                                               T filter, String packageName);
1031        void startVerifications(int userId);
1032        void receiveVerificationResponse(int verificationId);
1033    }
1034
1035    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1036        private Context mContext;
1037        private ComponentName mIntentFilterVerifierComponent;
1038        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1039
1040        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1041            mContext = context;
1042            mIntentFilterVerifierComponent = verifierComponent;
1043        }
1044
1045        private String getDefaultScheme() {
1046            return IntentFilter.SCHEME_HTTPS;
1047        }
1048
1049        @Override
1050        public void startVerifications(int userId) {
1051            // Launch verifications requests
1052            int count = mCurrentIntentFilterVerifications.size();
1053            for (int n=0; n<count; n++) {
1054                int verificationId = mCurrentIntentFilterVerifications.get(n);
1055                final IntentFilterVerificationState ivs =
1056                        mIntentFilterVerificationStates.get(verificationId);
1057
1058                String packageName = ivs.getPackageName();
1059
1060                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1061                final int filterCount = filters.size();
1062                ArraySet<String> domainsSet = new ArraySet<>();
1063                for (int m=0; m<filterCount; m++) {
1064                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1065                    domainsSet.addAll(filter.getHostsList());
1066                }
1067                synchronized (mPackages) {
1068                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1069                            packageName, domainsSet) != null) {
1070                        scheduleWriteSettingsLocked();
1071                    }
1072                }
1073                sendVerificationRequest(verificationId, ivs);
1074            }
1075            mCurrentIntentFilterVerifications.clear();
1076        }
1077
1078        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1079            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1080            verificationIntent.putExtra(
1081                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1082                    verificationId);
1083            verificationIntent.putExtra(
1084                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1085                    getDefaultScheme());
1086            verificationIntent.putExtra(
1087                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1088                    ivs.getHostsString());
1089            verificationIntent.putExtra(
1090                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1091                    ivs.getPackageName());
1092            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1093            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1094
1095            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1096            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1097                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1098                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1099
1100            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1101            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1102                    "Sending IntentFilter verification broadcast");
1103        }
1104
1105        public void receiveVerificationResponse(int verificationId) {
1106            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1107
1108            final boolean verified = ivs.isVerified();
1109
1110            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1111            final int count = filters.size();
1112            if (DEBUG_DOMAIN_VERIFICATION) {
1113                Slog.i(TAG, "Received verification response " + verificationId
1114                        + " for " + count + " filters, verified=" + verified);
1115            }
1116            for (int n=0; n<count; n++) {
1117                PackageParser.ActivityIntentInfo filter = filters.get(n);
1118                filter.setVerified(verified);
1119
1120                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1121                        + " verified with result:" + verified + " and hosts:"
1122                        + ivs.getHostsString());
1123            }
1124
1125            mIntentFilterVerificationStates.remove(verificationId);
1126
1127            final String packageName = ivs.getPackageName();
1128            IntentFilterVerificationInfo ivi = null;
1129
1130            synchronized (mPackages) {
1131                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1132            }
1133            if (ivi == null) {
1134                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1135                        + verificationId + " packageName:" + packageName);
1136                return;
1137            }
1138            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1139                    "Updating IntentFilterVerificationInfo for package " + packageName
1140                            +" verificationId:" + verificationId);
1141
1142            synchronized (mPackages) {
1143                if (verified) {
1144                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1145                } else {
1146                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1147                }
1148                scheduleWriteSettingsLocked();
1149
1150                final int userId = ivs.getUserId();
1151                if (userId != UserHandle.USER_ALL) {
1152                    final int userStatus =
1153                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1154
1155                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1156                    boolean needUpdate = false;
1157
1158                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1159                    // already been set by the User thru the Disambiguation dialog
1160                    switch (userStatus) {
1161                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1162                            if (verified) {
1163                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1164                            } else {
1165                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1166                            }
1167                            needUpdate = true;
1168                            break;
1169
1170                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1171                            if (verified) {
1172                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1173                                needUpdate = true;
1174                            }
1175                            break;
1176
1177                        default:
1178                            // Nothing to do
1179                    }
1180
1181                    if (needUpdate) {
1182                        mSettings.updateIntentFilterVerificationStatusLPw(
1183                                packageName, updatedStatus, userId);
1184                        scheduleWritePackageRestrictionsLocked(userId);
1185                    }
1186                }
1187            }
1188        }
1189
1190        @Override
1191        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1192                    ActivityIntentInfo filter, String packageName) {
1193            if (!hasValidDomains(filter)) {
1194                return false;
1195            }
1196            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1197            if (ivs == null) {
1198                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1199                        packageName);
1200            }
1201            if (DEBUG_DOMAIN_VERIFICATION) {
1202                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1203            }
1204            ivs.addFilter(filter);
1205            return true;
1206        }
1207
1208        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1209                int userId, int verificationId, String packageName) {
1210            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1211                    verifierUid, userId, packageName);
1212            ivs.setPendingState();
1213            synchronized (mPackages) {
1214                mIntentFilterVerificationStates.append(verificationId, ivs);
1215                mCurrentIntentFilterVerifications.add(verificationId);
1216            }
1217            return ivs;
1218        }
1219    }
1220
1221    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1222        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1223                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1224                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1225    }
1226
1227    // Set of pending broadcasts for aggregating enable/disable of components.
1228    static class PendingPackageBroadcasts {
1229        // for each user id, a map of <package name -> components within that package>
1230        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1231
1232        public PendingPackageBroadcasts() {
1233            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1234        }
1235
1236        public ArrayList<String> get(int userId, String packageName) {
1237            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1238            return packages.get(packageName);
1239        }
1240
1241        public void put(int userId, String packageName, ArrayList<String> components) {
1242            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1243            packages.put(packageName, components);
1244        }
1245
1246        public void remove(int userId, String packageName) {
1247            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1248            if (packages != null) {
1249                packages.remove(packageName);
1250            }
1251        }
1252
1253        public void remove(int userId) {
1254            mUidMap.remove(userId);
1255        }
1256
1257        public int userIdCount() {
1258            return mUidMap.size();
1259        }
1260
1261        public int userIdAt(int n) {
1262            return mUidMap.keyAt(n);
1263        }
1264
1265        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1266            return mUidMap.get(userId);
1267        }
1268
1269        public int size() {
1270            // total number of pending broadcast entries across all userIds
1271            int num = 0;
1272            for (int i = 0; i< mUidMap.size(); i++) {
1273                num += mUidMap.valueAt(i).size();
1274            }
1275            return num;
1276        }
1277
1278        public void clear() {
1279            mUidMap.clear();
1280        }
1281
1282        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1283            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1284            if (map == null) {
1285                map = new ArrayMap<String, ArrayList<String>>();
1286                mUidMap.put(userId, map);
1287            }
1288            return map;
1289        }
1290    }
1291    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1292
1293    // Service Connection to remote media container service to copy
1294    // package uri's from external media onto secure containers
1295    // or internal storage.
1296    private IMediaContainerService mContainerService = null;
1297
1298    static final int SEND_PENDING_BROADCAST = 1;
1299    static final int MCS_BOUND = 3;
1300    static final int END_COPY = 4;
1301    static final int INIT_COPY = 5;
1302    static final int MCS_UNBIND = 6;
1303    static final int START_CLEANING_PACKAGE = 7;
1304    static final int FIND_INSTALL_LOC = 8;
1305    static final int POST_INSTALL = 9;
1306    static final int MCS_RECONNECT = 10;
1307    static final int MCS_GIVE_UP = 11;
1308    static final int WRITE_SETTINGS = 13;
1309    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1310    static final int PACKAGE_VERIFIED = 15;
1311    static final int CHECK_PENDING_VERIFICATION = 16;
1312    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1313    static final int INTENT_FILTER_VERIFIED = 18;
1314    static final int WRITE_PACKAGE_LIST = 19;
1315    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1316
1317    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1318
1319    // Delay time in millisecs
1320    static final int BROADCAST_DELAY = 10 * 1000;
1321
1322    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1323            2 * 60 * 60 * 1000L; /* two hours */
1324
1325    static UserManagerService sUserManager;
1326
1327    // Stores a list of users whose package restrictions file needs to be updated
1328    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1329
1330    final private DefaultContainerConnection mDefContainerConn =
1331            new DefaultContainerConnection();
1332    class DefaultContainerConnection implements ServiceConnection {
1333        public void onServiceConnected(ComponentName name, IBinder service) {
1334            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1335            final IMediaContainerService imcs = IMediaContainerService.Stub
1336                    .asInterface(Binder.allowBlocking(service));
1337            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1338        }
1339
1340        public void onServiceDisconnected(ComponentName name) {
1341            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1342        }
1343    }
1344
1345    // Recordkeeping of restore-after-install operations that are currently in flight
1346    // between the Package Manager and the Backup Manager
1347    static class PostInstallData {
1348        public InstallArgs args;
1349        public PackageInstalledInfo res;
1350
1351        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1352            args = _a;
1353            res = _r;
1354        }
1355    }
1356
1357    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1358    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1359
1360    // XML tags for backup/restore of various bits of state
1361    private static final String TAG_PREFERRED_BACKUP = "pa";
1362    private static final String TAG_DEFAULT_APPS = "da";
1363    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1364
1365    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1366    private static final String TAG_ALL_GRANTS = "rt-grants";
1367    private static final String TAG_GRANT = "grant";
1368    private static final String ATTR_PACKAGE_NAME = "pkg";
1369
1370    private static final String TAG_PERMISSION = "perm";
1371    private static final String ATTR_PERMISSION_NAME = "name";
1372    private static final String ATTR_IS_GRANTED = "g";
1373    private static final String ATTR_USER_SET = "set";
1374    private static final String ATTR_USER_FIXED = "fixed";
1375    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1376
1377    // System/policy permission grants are not backed up
1378    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1379            FLAG_PERMISSION_POLICY_FIXED
1380            | FLAG_PERMISSION_SYSTEM_FIXED
1381            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1382
1383    // And we back up these user-adjusted states
1384    private static final int USER_RUNTIME_GRANT_MASK =
1385            FLAG_PERMISSION_USER_SET
1386            | FLAG_PERMISSION_USER_FIXED
1387            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1388
1389    final @Nullable String mRequiredVerifierPackage;
1390    final @NonNull String mRequiredInstallerPackage;
1391    final @NonNull String mRequiredUninstallerPackage;
1392    final @Nullable String mSetupWizardPackage;
1393    final @Nullable String mStorageManagerPackage;
1394    final @NonNull String mServicesSystemSharedLibraryPackageName;
1395    final @NonNull String mSharedSystemSharedLibraryPackageName;
1396
1397    private final PackageUsage mPackageUsage = new PackageUsage();
1398    private final CompilerStats mCompilerStats = new CompilerStats();
1399
1400    class PackageHandler extends Handler {
1401        private boolean mBound = false;
1402        final ArrayList<HandlerParams> mPendingInstalls =
1403            new ArrayList<HandlerParams>();
1404
1405        private boolean connectToService() {
1406            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1407                    " DefaultContainerService");
1408            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1409            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1410            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1411                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1412                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1413                mBound = true;
1414                return true;
1415            }
1416            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1417            return false;
1418        }
1419
1420        private void disconnectService() {
1421            mContainerService = null;
1422            mBound = false;
1423            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1424            mContext.unbindService(mDefContainerConn);
1425            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1426        }
1427
1428        PackageHandler(Looper looper) {
1429            super(looper);
1430        }
1431
1432        public void handleMessage(Message msg) {
1433            try {
1434                doHandleMessage(msg);
1435            } finally {
1436                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1437            }
1438        }
1439
1440        void doHandleMessage(Message msg) {
1441            switch (msg.what) {
1442                case INIT_COPY: {
1443                    HandlerParams params = (HandlerParams) msg.obj;
1444                    int idx = mPendingInstalls.size();
1445                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1446                    // If a bind was already initiated we dont really
1447                    // need to do anything. The pending install
1448                    // will be processed later on.
1449                    if (!mBound) {
1450                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1451                                System.identityHashCode(mHandler));
1452                        // If this is the only one pending we might
1453                        // have to bind to the service again.
1454                        if (!connectToService()) {
1455                            Slog.e(TAG, "Failed to bind to media container service");
1456                            params.serviceError();
1457                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1458                                    System.identityHashCode(mHandler));
1459                            if (params.traceMethod != null) {
1460                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1461                                        params.traceCookie);
1462                            }
1463                            return;
1464                        } else {
1465                            // Once we bind to the service, the first
1466                            // pending request will be processed.
1467                            mPendingInstalls.add(idx, params);
1468                        }
1469                    } else {
1470                        mPendingInstalls.add(idx, params);
1471                        // Already bound to the service. Just make
1472                        // sure we trigger off processing the first request.
1473                        if (idx == 0) {
1474                            mHandler.sendEmptyMessage(MCS_BOUND);
1475                        }
1476                    }
1477                    break;
1478                }
1479                case MCS_BOUND: {
1480                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1481                    if (msg.obj != null) {
1482                        mContainerService = (IMediaContainerService) msg.obj;
1483                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1484                                System.identityHashCode(mHandler));
1485                    }
1486                    if (mContainerService == null) {
1487                        if (!mBound) {
1488                            // Something seriously wrong since we are not bound and we are not
1489                            // waiting for connection. Bail out.
1490                            Slog.e(TAG, "Cannot bind to media container service");
1491                            for (HandlerParams params : mPendingInstalls) {
1492                                // Indicate service bind error
1493                                params.serviceError();
1494                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1495                                        System.identityHashCode(params));
1496                                if (params.traceMethod != null) {
1497                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1498                                            params.traceMethod, params.traceCookie);
1499                                }
1500                                return;
1501                            }
1502                            mPendingInstalls.clear();
1503                        } else {
1504                            Slog.w(TAG, "Waiting to connect to media container service");
1505                        }
1506                    } else if (mPendingInstalls.size() > 0) {
1507                        HandlerParams params = mPendingInstalls.get(0);
1508                        if (params != null) {
1509                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1510                                    System.identityHashCode(params));
1511                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1512                            if (params.startCopy()) {
1513                                // We are done...  look for more work or to
1514                                // go idle.
1515                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1516                                        "Checking for more work or unbind...");
1517                                // Delete pending install
1518                                if (mPendingInstalls.size() > 0) {
1519                                    mPendingInstalls.remove(0);
1520                                }
1521                                if (mPendingInstalls.size() == 0) {
1522                                    if (mBound) {
1523                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1524                                                "Posting delayed MCS_UNBIND");
1525                                        removeMessages(MCS_UNBIND);
1526                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1527                                        // Unbind after a little delay, to avoid
1528                                        // continual thrashing.
1529                                        sendMessageDelayed(ubmsg, 10000);
1530                                    }
1531                                } else {
1532                                    // There are more pending requests in queue.
1533                                    // Just post MCS_BOUND message to trigger processing
1534                                    // of next pending install.
1535                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1536                                            "Posting MCS_BOUND for next work");
1537                                    mHandler.sendEmptyMessage(MCS_BOUND);
1538                                }
1539                            }
1540                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1541                        }
1542                    } else {
1543                        // Should never happen ideally.
1544                        Slog.w(TAG, "Empty queue");
1545                    }
1546                    break;
1547                }
1548                case MCS_RECONNECT: {
1549                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1550                    if (mPendingInstalls.size() > 0) {
1551                        if (mBound) {
1552                            disconnectService();
1553                        }
1554                        if (!connectToService()) {
1555                            Slog.e(TAG, "Failed to bind to media container service");
1556                            for (HandlerParams params : mPendingInstalls) {
1557                                // Indicate service bind error
1558                                params.serviceError();
1559                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1560                                        System.identityHashCode(params));
1561                            }
1562                            mPendingInstalls.clear();
1563                        }
1564                    }
1565                    break;
1566                }
1567                case MCS_UNBIND: {
1568                    // If there is no actual work left, then time to unbind.
1569                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1570
1571                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1572                        if (mBound) {
1573                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1574
1575                            disconnectService();
1576                        }
1577                    } else if (mPendingInstalls.size() > 0) {
1578                        // There are more pending requests in queue.
1579                        // Just post MCS_BOUND message to trigger processing
1580                        // of next pending install.
1581                        mHandler.sendEmptyMessage(MCS_BOUND);
1582                    }
1583
1584                    break;
1585                }
1586                case MCS_GIVE_UP: {
1587                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1588                    HandlerParams params = mPendingInstalls.remove(0);
1589                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1590                            System.identityHashCode(params));
1591                    break;
1592                }
1593                case SEND_PENDING_BROADCAST: {
1594                    String packages[];
1595                    ArrayList<String> components[];
1596                    int size = 0;
1597                    int uids[];
1598                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1599                    synchronized (mPackages) {
1600                        if (mPendingBroadcasts == null) {
1601                            return;
1602                        }
1603                        size = mPendingBroadcasts.size();
1604                        if (size <= 0) {
1605                            // Nothing to be done. Just return
1606                            return;
1607                        }
1608                        packages = new String[size];
1609                        components = new ArrayList[size];
1610                        uids = new int[size];
1611                        int i = 0;  // filling out the above arrays
1612
1613                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1614                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1615                            Iterator<Map.Entry<String, ArrayList<String>>> it
1616                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1617                                            .entrySet().iterator();
1618                            while (it.hasNext() && i < size) {
1619                                Map.Entry<String, ArrayList<String>> ent = it.next();
1620                                packages[i] = ent.getKey();
1621                                components[i] = ent.getValue();
1622                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1623                                uids[i] = (ps != null)
1624                                        ? UserHandle.getUid(packageUserId, ps.appId)
1625                                        : -1;
1626                                i++;
1627                            }
1628                        }
1629                        size = i;
1630                        mPendingBroadcasts.clear();
1631                    }
1632                    // Send broadcasts
1633                    for (int i = 0; i < size; i++) {
1634                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1635                    }
1636                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1637                    break;
1638                }
1639                case START_CLEANING_PACKAGE: {
1640                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1641                    final String packageName = (String)msg.obj;
1642                    final int userId = msg.arg1;
1643                    final boolean andCode = msg.arg2 != 0;
1644                    synchronized (mPackages) {
1645                        if (userId == UserHandle.USER_ALL) {
1646                            int[] users = sUserManager.getUserIds();
1647                            for (int user : users) {
1648                                mSettings.addPackageToCleanLPw(
1649                                        new PackageCleanItem(user, packageName, andCode));
1650                            }
1651                        } else {
1652                            mSettings.addPackageToCleanLPw(
1653                                    new PackageCleanItem(userId, packageName, andCode));
1654                        }
1655                    }
1656                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1657                    startCleaningPackages();
1658                } break;
1659                case POST_INSTALL: {
1660                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1661
1662                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1663                    final boolean didRestore = (msg.arg2 != 0);
1664                    mRunningInstalls.delete(msg.arg1);
1665
1666                    if (data != null) {
1667                        InstallArgs args = data.args;
1668                        PackageInstalledInfo parentRes = data.res;
1669
1670                        final boolean grantPermissions = (args.installFlags
1671                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1672                        final boolean killApp = (args.installFlags
1673                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1674                        final boolean virtualPreload = ((args.installFlags
1675                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1676                        final String[] grantedPermissions = args.installGrantPermissions;
1677
1678                        // Handle the parent package
1679                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1680                                virtualPreload, grantedPermissions, didRestore,
1681                                args.installerPackageName, args.observer);
1682
1683                        // Handle the child packages
1684                        final int childCount = (parentRes.addedChildPackages != null)
1685                                ? parentRes.addedChildPackages.size() : 0;
1686                        for (int i = 0; i < childCount; i++) {
1687                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1688                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1689                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1690                                    args.installerPackageName, args.observer);
1691                        }
1692
1693                        // Log tracing if needed
1694                        if (args.traceMethod != null) {
1695                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1696                                    args.traceCookie);
1697                        }
1698                    } else {
1699                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1700                    }
1701
1702                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1703                } break;
1704                case WRITE_SETTINGS: {
1705                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1706                    synchronized (mPackages) {
1707                        removeMessages(WRITE_SETTINGS);
1708                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1709                        mSettings.writeLPr();
1710                        mDirtyUsers.clear();
1711                    }
1712                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1713                } break;
1714                case WRITE_PACKAGE_RESTRICTIONS: {
1715                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1716                    synchronized (mPackages) {
1717                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1718                        for (int userId : mDirtyUsers) {
1719                            mSettings.writePackageRestrictionsLPr(userId);
1720                        }
1721                        mDirtyUsers.clear();
1722                    }
1723                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1724                } break;
1725                case WRITE_PACKAGE_LIST: {
1726                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1727                    synchronized (mPackages) {
1728                        removeMessages(WRITE_PACKAGE_LIST);
1729                        mSettings.writePackageListLPr(msg.arg1);
1730                    }
1731                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1732                } break;
1733                case CHECK_PENDING_VERIFICATION: {
1734                    final int verificationId = msg.arg1;
1735                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1736
1737                    if ((state != null) && !state.timeoutExtended()) {
1738                        final InstallArgs args = state.getInstallArgs();
1739                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1740
1741                        Slog.i(TAG, "Verification timed out for " + originUri);
1742                        mPendingVerification.remove(verificationId);
1743
1744                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1745
1746                        final UserHandle user = args.getUser();
1747                        if (getDefaultVerificationResponse(user)
1748                                == PackageManager.VERIFICATION_ALLOW) {
1749                            Slog.i(TAG, "Continuing with installation of " + originUri);
1750                            state.setVerifierResponse(Binder.getCallingUid(),
1751                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1752                            broadcastPackageVerified(verificationId, originUri,
1753                                    PackageManager.VERIFICATION_ALLOW, user);
1754                            try {
1755                                ret = args.copyApk(mContainerService, true);
1756                            } catch (RemoteException e) {
1757                                Slog.e(TAG, "Could not contact the ContainerService");
1758                            }
1759                        } else {
1760                            broadcastPackageVerified(verificationId, originUri,
1761                                    PackageManager.VERIFICATION_REJECT, user);
1762                        }
1763
1764                        Trace.asyncTraceEnd(
1765                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1766
1767                        processPendingInstall(args, ret);
1768                        mHandler.sendEmptyMessage(MCS_UNBIND);
1769                    }
1770                    break;
1771                }
1772                case PACKAGE_VERIFIED: {
1773                    final int verificationId = msg.arg1;
1774
1775                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1776                    if (state == null) {
1777                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1778                        break;
1779                    }
1780
1781                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1782
1783                    state.setVerifierResponse(response.callerUid, response.code);
1784
1785                    if (state.isVerificationComplete()) {
1786                        mPendingVerification.remove(verificationId);
1787
1788                        final InstallArgs args = state.getInstallArgs();
1789                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1790
1791                        int ret;
1792                        if (state.isInstallAllowed()) {
1793                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1794                            broadcastPackageVerified(verificationId, originUri,
1795                                    response.code, state.getInstallArgs().getUser());
1796                            try {
1797                                ret = args.copyApk(mContainerService, true);
1798                            } catch (RemoteException e) {
1799                                Slog.e(TAG, "Could not contact the ContainerService");
1800                            }
1801                        } else {
1802                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1803                        }
1804
1805                        Trace.asyncTraceEnd(
1806                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1807
1808                        processPendingInstall(args, ret);
1809                        mHandler.sendEmptyMessage(MCS_UNBIND);
1810                    }
1811
1812                    break;
1813                }
1814                case START_INTENT_FILTER_VERIFICATIONS: {
1815                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1816                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1817                            params.replacing, params.pkg);
1818                    break;
1819                }
1820                case INTENT_FILTER_VERIFIED: {
1821                    final int verificationId = msg.arg1;
1822
1823                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1824                            verificationId);
1825                    if (state == null) {
1826                        Slog.w(TAG, "Invalid IntentFilter verification token "
1827                                + verificationId + " received");
1828                        break;
1829                    }
1830
1831                    final int userId = state.getUserId();
1832
1833                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1834                            "Processing IntentFilter verification with token:"
1835                            + verificationId + " and userId:" + userId);
1836
1837                    final IntentFilterVerificationResponse response =
1838                            (IntentFilterVerificationResponse) msg.obj;
1839
1840                    state.setVerifierResponse(response.callerUid, response.code);
1841
1842                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1843                            "IntentFilter verification with token:" + verificationId
1844                            + " and userId:" + userId
1845                            + " is settings verifier response with response code:"
1846                            + response.code);
1847
1848                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1849                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1850                                + response.getFailedDomainsString());
1851                    }
1852
1853                    if (state.isVerificationComplete()) {
1854                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1855                    } else {
1856                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1857                                "IntentFilter verification with token:" + verificationId
1858                                + " was not said to be complete");
1859                    }
1860
1861                    break;
1862                }
1863                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1864                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1865                            mInstantAppResolverConnection,
1866                            (InstantAppRequest) msg.obj,
1867                            mInstantAppInstallerActivity,
1868                            mHandler);
1869                }
1870            }
1871        }
1872    }
1873
1874    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1875        @Override
1876        public void onGidsChanged(int appId, int userId) {
1877            mHandler.post(new Runnable() {
1878                @Override
1879                public void run() {
1880                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1881                }
1882            });
1883        }
1884        @Override
1885        public void onPermissionGranted(int uid, int userId) {
1886            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1887
1888            // Not critical; if this is lost, the application has to request again.
1889            synchronized (mPackages) {
1890                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1891            }
1892        }
1893        @Override
1894        public void onInstallPermissionGranted() {
1895            synchronized (mPackages) {
1896                scheduleWriteSettingsLocked();
1897            }
1898        }
1899        @Override
1900        public void onPermissionRevoked(int uid, int userId) {
1901            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1902
1903            synchronized (mPackages) {
1904                // Critical; after this call the application should never have the permission
1905                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1906            }
1907
1908            final int appId = UserHandle.getAppId(uid);
1909            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1910        }
1911        @Override
1912        public void onInstallPermissionRevoked() {
1913            synchronized (mPackages) {
1914                scheduleWriteSettingsLocked();
1915            }
1916        }
1917        @Override
1918        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1919            synchronized (mPackages) {
1920                for (int userId : updatedUserIds) {
1921                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1922                }
1923            }
1924        }
1925        @Override
1926        public void onInstallPermissionUpdated() {
1927            synchronized (mPackages) {
1928                scheduleWriteSettingsLocked();
1929            }
1930        }
1931        @Override
1932        public void onPermissionRemoved() {
1933            synchronized (mPackages) {
1934                mSettings.writeLPr();
1935            }
1936        }
1937    };
1938
1939    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1940            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1941            boolean launchedForRestore, String installerPackage,
1942            IPackageInstallObserver2 installObserver) {
1943        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1944            // Send the removed broadcasts
1945            if (res.removedInfo != null) {
1946                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1947            }
1948
1949            // Now that we successfully installed the package, grant runtime
1950            // permissions if requested before broadcasting the install. Also
1951            // for legacy apps in permission review mode we clear the permission
1952            // review flag which is used to emulate runtime permissions for
1953            // legacy apps.
1954            if (grantPermissions) {
1955                final int callingUid = Binder.getCallingUid();
1956                mPermissionManager.grantRequestedRuntimePermissions(
1957                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1958                        mPermissionCallback);
1959            }
1960
1961            final boolean update = res.removedInfo != null
1962                    && res.removedInfo.removedPackage != null;
1963            final String installerPackageName =
1964                    res.installerPackageName != null
1965                            ? res.installerPackageName
1966                            : res.removedInfo != null
1967                                    ? res.removedInfo.installerPackageName
1968                                    : null;
1969
1970            // If this is the first time we have child packages for a disabled privileged
1971            // app that had no children, we grant requested runtime permissions to the new
1972            // children if the parent on the system image had them already granted.
1973            if (res.pkg.parentPackage != null) {
1974                final int callingUid = Binder.getCallingUid();
1975                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1976                        res.pkg, callingUid, mPermissionCallback);
1977            }
1978
1979            synchronized (mPackages) {
1980                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1981            }
1982
1983            final String packageName = res.pkg.applicationInfo.packageName;
1984
1985            // Determine the set of users who are adding this package for
1986            // the first time vs. those who are seeing an update.
1987            int[] firstUserIds = EMPTY_INT_ARRAY;
1988            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
1989            int[] updateUserIds = EMPTY_INT_ARRAY;
1990            int[] instantUserIds = EMPTY_INT_ARRAY;
1991            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1992            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1993            for (int newUser : res.newUsers) {
1994                final boolean isInstantApp = ps.getInstantApp(newUser);
1995                if (allNewUsers) {
1996                    if (isInstantApp) {
1997                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
1998                    } else {
1999                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2000                    }
2001                    continue;
2002                }
2003                boolean isNew = true;
2004                for (int origUser : res.origUsers) {
2005                    if (origUser == newUser) {
2006                        isNew = false;
2007                        break;
2008                    }
2009                }
2010                if (isNew) {
2011                    if (isInstantApp) {
2012                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2013                    } else {
2014                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2015                    }
2016                } else {
2017                    if (isInstantApp) {
2018                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2019                    } else {
2020                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2021                    }
2022                }
2023            }
2024
2025            // Send installed broadcasts if the package is not a static shared lib.
2026            if (res.pkg.staticSharedLibName == null) {
2027                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2028
2029                // Send added for users that see the package for the first time
2030                // sendPackageAddedForNewUsers also deals with system apps
2031                int appId = UserHandle.getAppId(res.uid);
2032                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2033                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2034                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2035
2036                // Send added for users that don't see the package for the first time
2037                Bundle extras = new Bundle(1);
2038                extras.putInt(Intent.EXTRA_UID, res.uid);
2039                if (update) {
2040                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2041                }
2042                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2043                        extras, 0 /*flags*/,
2044                        null /*targetPackage*/, null /*finishedReceiver*/,
2045                        updateUserIds, instantUserIds);
2046                if (installerPackageName != null) {
2047                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2048                            extras, 0 /*flags*/,
2049                            installerPackageName, null /*finishedReceiver*/,
2050                            updateUserIds, instantUserIds);
2051                }
2052
2053                // Send replaced for users that don't see the package for the first time
2054                if (update) {
2055                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2056                            packageName, extras, 0 /*flags*/,
2057                            null /*targetPackage*/, null /*finishedReceiver*/,
2058                            updateUserIds, instantUserIds);
2059                    if (installerPackageName != null) {
2060                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2061                                extras, 0 /*flags*/,
2062                                installerPackageName, null /*finishedReceiver*/,
2063                                updateUserIds, instantUserIds);
2064                    }
2065                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2066                            null /*package*/, null /*extras*/, 0 /*flags*/,
2067                            packageName /*targetPackage*/,
2068                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2069                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2070                    // First-install and we did a restore, so we're responsible for the
2071                    // first-launch broadcast.
2072                    if (DEBUG_BACKUP) {
2073                        Slog.i(TAG, "Post-restore of " + packageName
2074                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2075                    }
2076                    sendFirstLaunchBroadcast(packageName, installerPackage,
2077                            firstUserIds, firstInstantUserIds);
2078                }
2079
2080                // Send broadcast package appeared if forward locked/external for all users
2081                // treat asec-hosted packages like removable media on upgrade
2082                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2083                    if (DEBUG_INSTALL) {
2084                        Slog.i(TAG, "upgrading pkg " + res.pkg
2085                                + " is ASEC-hosted -> AVAILABLE");
2086                    }
2087                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2088                    ArrayList<String> pkgList = new ArrayList<>(1);
2089                    pkgList.add(packageName);
2090                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2091                }
2092            }
2093
2094            // Work that needs to happen on first install within each user
2095            if (firstUserIds != null && firstUserIds.length > 0) {
2096                synchronized (mPackages) {
2097                    for (int userId : firstUserIds) {
2098                        // If this app is a browser and it's newly-installed for some
2099                        // users, clear any default-browser state in those users. The
2100                        // app's nature doesn't depend on the user, so we can just check
2101                        // its browser nature in any user and generalize.
2102                        if (packageIsBrowser(packageName, userId)) {
2103                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2104                        }
2105
2106                        // We may also need to apply pending (restored) runtime
2107                        // permission grants within these users.
2108                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2109                    }
2110                }
2111            }
2112
2113            if (allNewUsers && !update) {
2114                notifyPackageAdded(packageName);
2115            }
2116
2117            // Log current value of "unknown sources" setting
2118            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2119                    getUnknownSourcesSettings());
2120
2121            // Remove the replaced package's older resources safely now
2122            // We delete after a gc for applications  on sdcard.
2123            if (res.removedInfo != null && res.removedInfo.args != null) {
2124                Runtime.getRuntime().gc();
2125                synchronized (mInstallLock) {
2126                    res.removedInfo.args.doPostDeleteLI(true);
2127                }
2128            } else {
2129                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2130                // and not block here.
2131                VMRuntime.getRuntime().requestConcurrentGC();
2132            }
2133
2134            // Notify DexManager that the package was installed for new users.
2135            // The updated users should already be indexed and the package code paths
2136            // should not change.
2137            // Don't notify the manager for ephemeral apps as they are not expected to
2138            // survive long enough to benefit of background optimizations.
2139            for (int userId : firstUserIds) {
2140                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2141                // There's a race currently where some install events may interleave with an uninstall.
2142                // This can lead to package info being null (b/36642664).
2143                if (info != null) {
2144                    mDexManager.notifyPackageInstalled(info, userId);
2145                }
2146            }
2147        }
2148
2149        // If someone is watching installs - notify them
2150        if (installObserver != null) {
2151            try {
2152                Bundle extras = extrasForInstallResult(res);
2153                installObserver.onPackageInstalled(res.name, res.returnCode,
2154                        res.returnMsg, extras);
2155            } catch (RemoteException e) {
2156                Slog.i(TAG, "Observer no longer exists.");
2157            }
2158        }
2159    }
2160
2161    private StorageEventListener mStorageListener = new StorageEventListener() {
2162        @Override
2163        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2164            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2165                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2166                    final String volumeUuid = vol.getFsUuid();
2167
2168                    // Clean up any users or apps that were removed or recreated
2169                    // while this volume was missing
2170                    sUserManager.reconcileUsers(volumeUuid);
2171                    reconcileApps(volumeUuid);
2172
2173                    // Clean up any install sessions that expired or were
2174                    // cancelled while this volume was missing
2175                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2176
2177                    loadPrivatePackages(vol);
2178
2179                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2180                    unloadPrivatePackages(vol);
2181                }
2182            }
2183        }
2184
2185        @Override
2186        public void onVolumeForgotten(String fsUuid) {
2187            if (TextUtils.isEmpty(fsUuid)) {
2188                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2189                return;
2190            }
2191
2192            // Remove any apps installed on the forgotten volume
2193            synchronized (mPackages) {
2194                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2195                for (PackageSetting ps : packages) {
2196                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2197                    deletePackageVersioned(new VersionedPackage(ps.name,
2198                            PackageManager.VERSION_CODE_HIGHEST),
2199                            new LegacyPackageDeleteObserver(null).getBinder(),
2200                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2201                    // Try very hard to release any references to this package
2202                    // so we don't risk the system server being killed due to
2203                    // open FDs
2204                    AttributeCache.instance().removePackage(ps.name);
2205                }
2206
2207                mSettings.onVolumeForgotten(fsUuid);
2208                mSettings.writeLPr();
2209            }
2210        }
2211    };
2212
2213    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2214        Bundle extras = null;
2215        switch (res.returnCode) {
2216            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2217                extras = new Bundle();
2218                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2219                        res.origPermission);
2220                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2221                        res.origPackage);
2222                break;
2223            }
2224            case PackageManager.INSTALL_SUCCEEDED: {
2225                extras = new Bundle();
2226                extras.putBoolean(Intent.EXTRA_REPLACING,
2227                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2228                break;
2229            }
2230        }
2231        return extras;
2232    }
2233
2234    void scheduleWriteSettingsLocked() {
2235        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2236            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2237        }
2238    }
2239
2240    void scheduleWritePackageListLocked(int userId) {
2241        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2242            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2243            msg.arg1 = userId;
2244            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2245        }
2246    }
2247
2248    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2249        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2250        scheduleWritePackageRestrictionsLocked(userId);
2251    }
2252
2253    void scheduleWritePackageRestrictionsLocked(int userId) {
2254        final int[] userIds = (userId == UserHandle.USER_ALL)
2255                ? sUserManager.getUserIds() : new int[]{userId};
2256        for (int nextUserId : userIds) {
2257            if (!sUserManager.exists(nextUserId)) return;
2258            mDirtyUsers.add(nextUserId);
2259            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2260                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2261            }
2262        }
2263    }
2264
2265    public static PackageManagerService main(Context context, Installer installer,
2266            boolean factoryTest, boolean onlyCore) {
2267        // Self-check for initial settings.
2268        PackageManagerServiceCompilerMapping.checkProperties();
2269
2270        PackageManagerService m = new PackageManagerService(context, installer,
2271                factoryTest, onlyCore);
2272        m.enableSystemUserPackages();
2273        ServiceManager.addService("package", m);
2274        final PackageManagerNative pmn = m.new PackageManagerNative();
2275        ServiceManager.addService("package_native", pmn);
2276        return m;
2277    }
2278
2279    private void enableSystemUserPackages() {
2280        if (!UserManager.isSplitSystemUser()) {
2281            return;
2282        }
2283        // For system user, enable apps based on the following conditions:
2284        // - app is whitelisted or belong to one of these groups:
2285        //   -- system app which has no launcher icons
2286        //   -- system app which has INTERACT_ACROSS_USERS permission
2287        //   -- system IME app
2288        // - app is not in the blacklist
2289        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2290        Set<String> enableApps = new ArraySet<>();
2291        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2292                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2293                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2294        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2295        enableApps.addAll(wlApps);
2296        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2297                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2298        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2299        enableApps.removeAll(blApps);
2300        Log.i(TAG, "Applications installed for system user: " + enableApps);
2301        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2302                UserHandle.SYSTEM);
2303        final int allAppsSize = allAps.size();
2304        synchronized (mPackages) {
2305            for (int i = 0; i < allAppsSize; i++) {
2306                String pName = allAps.get(i);
2307                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2308                // Should not happen, but we shouldn't be failing if it does
2309                if (pkgSetting == null) {
2310                    continue;
2311                }
2312                boolean install = enableApps.contains(pName);
2313                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2314                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2315                            + " for system user");
2316                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2317                }
2318            }
2319            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2320        }
2321    }
2322
2323    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2324        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2325                Context.DISPLAY_SERVICE);
2326        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2327    }
2328
2329    /**
2330     * Requests that files preopted on a secondary system partition be copied to the data partition
2331     * if possible.  Note that the actual copying of the files is accomplished by init for security
2332     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2333     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2334     */
2335    private static void requestCopyPreoptedFiles() {
2336        final int WAIT_TIME_MS = 100;
2337        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2338        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2339            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2340            // We will wait for up to 100 seconds.
2341            final long timeStart = SystemClock.uptimeMillis();
2342            final long timeEnd = timeStart + 100 * 1000;
2343            long timeNow = timeStart;
2344            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2345                try {
2346                    Thread.sleep(WAIT_TIME_MS);
2347                } catch (InterruptedException e) {
2348                    // Do nothing
2349                }
2350                timeNow = SystemClock.uptimeMillis();
2351                if (timeNow > timeEnd) {
2352                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2353                    Slog.wtf(TAG, "cppreopt did not finish!");
2354                    break;
2355                }
2356            }
2357
2358            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2359        }
2360    }
2361
2362    public PackageManagerService(Context context, Installer installer,
2363            boolean factoryTest, boolean onlyCore) {
2364        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2365        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2366        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2367                SystemClock.uptimeMillis());
2368
2369        if (mSdkVersion <= 0) {
2370            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2371        }
2372
2373        mContext = context;
2374
2375        mFactoryTest = factoryTest;
2376        mOnlyCore = onlyCore;
2377        mMetrics = new DisplayMetrics();
2378        mInstaller = installer;
2379
2380        // Create sub-components that provide services / data. Order here is important.
2381        synchronized (mInstallLock) {
2382        synchronized (mPackages) {
2383            // Expose private service for system components to use.
2384            LocalServices.addService(
2385                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2386            sUserManager = new UserManagerService(context, this,
2387                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2388            mPermissionManager = PermissionManagerService.create(context,
2389                    new DefaultPermissionGrantedCallback() {
2390                        @Override
2391                        public void onDefaultRuntimePermissionsGranted(int userId) {
2392                            synchronized(mPackages) {
2393                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2394                            }
2395                        }
2396                    }, mPackages /*externalLock*/);
2397            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2398            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2399        }
2400        }
2401        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2402                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2403        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2404                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2405        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2406                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2407        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2408                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2409        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2410                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2411        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2412                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2413        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2414                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2415
2416        String separateProcesses = SystemProperties.get("debug.separate_processes");
2417        if (separateProcesses != null && separateProcesses.length() > 0) {
2418            if ("*".equals(separateProcesses)) {
2419                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2420                mSeparateProcesses = null;
2421                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2422            } else {
2423                mDefParseFlags = 0;
2424                mSeparateProcesses = separateProcesses.split(",");
2425                Slog.w(TAG, "Running with debug.separate_processes: "
2426                        + separateProcesses);
2427            }
2428        } else {
2429            mDefParseFlags = 0;
2430            mSeparateProcesses = null;
2431        }
2432
2433        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2434                "*dexopt*");
2435        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2436                installer, mInstallLock);
2437        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2438                dexManagerListener);
2439        mArtManagerService = new ArtManagerService(this, installer, mInstallLock);
2440        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2441
2442        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2443                FgThread.get().getLooper());
2444
2445        getDefaultDisplayMetrics(context, mMetrics);
2446
2447        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2448        SystemConfig systemConfig = SystemConfig.getInstance();
2449        mAvailableFeatures = systemConfig.getAvailableFeatures();
2450        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2451
2452        mProtectedPackages = new ProtectedPackages(mContext);
2453
2454        synchronized (mInstallLock) {
2455        // writer
2456        synchronized (mPackages) {
2457            mHandlerThread = new ServiceThread(TAG,
2458                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2459            mHandlerThread.start();
2460            mHandler = new PackageHandler(mHandlerThread.getLooper());
2461            mProcessLoggingHandler = new ProcessLoggingHandler();
2462            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2463            mInstantAppRegistry = new InstantAppRegistry(this);
2464
2465            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2466            final int builtInLibCount = libConfig.size();
2467            for (int i = 0; i < builtInLibCount; i++) {
2468                String name = libConfig.keyAt(i);
2469                String path = libConfig.valueAt(i);
2470                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2471                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2472            }
2473
2474            SELinuxMMAC.readInstallPolicy();
2475
2476            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2477            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2478            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2479
2480            // Clean up orphaned packages for which the code path doesn't exist
2481            // and they are an update to a system app - caused by bug/32321269
2482            final int packageSettingCount = mSettings.mPackages.size();
2483            for (int i = packageSettingCount - 1; i >= 0; i--) {
2484                PackageSetting ps = mSettings.mPackages.valueAt(i);
2485                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2486                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2487                    mSettings.mPackages.removeAt(i);
2488                    mSettings.enableSystemPackageLPw(ps.name);
2489                }
2490            }
2491
2492            if (mFirstBoot) {
2493                requestCopyPreoptedFiles();
2494            }
2495
2496            String customResolverActivity = Resources.getSystem().getString(
2497                    R.string.config_customResolverActivity);
2498            if (TextUtils.isEmpty(customResolverActivity)) {
2499                customResolverActivity = null;
2500            } else {
2501                mCustomResolverComponentName = ComponentName.unflattenFromString(
2502                        customResolverActivity);
2503            }
2504
2505            long startTime = SystemClock.uptimeMillis();
2506
2507            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2508                    startTime);
2509
2510            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2511            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2512
2513            if (bootClassPath == null) {
2514                Slog.w(TAG, "No BOOTCLASSPATH found!");
2515            }
2516
2517            if (systemServerClassPath == null) {
2518                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2519            }
2520
2521            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2522
2523            final VersionInfo ver = mSettings.getInternalVersion();
2524            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2525            if (mIsUpgrade) {
2526                logCriticalInfo(Log.INFO,
2527                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2528            }
2529
2530            // when upgrading from pre-M, promote system app permissions from install to runtime
2531            mPromoteSystemApps =
2532                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2533
2534            // When upgrading from pre-N, we need to handle package extraction like first boot,
2535            // as there is no profiling data available.
2536            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2537
2538            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2539
2540            // save off the names of pre-existing system packages prior to scanning; we don't
2541            // want to automatically grant runtime permissions for new system apps
2542            if (mPromoteSystemApps) {
2543                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2544                while (pkgSettingIter.hasNext()) {
2545                    PackageSetting ps = pkgSettingIter.next();
2546                    if (isSystemApp(ps)) {
2547                        mExistingSystemPackages.add(ps.name);
2548                    }
2549                }
2550            }
2551
2552            mCacheDir = preparePackageParserCache(mIsUpgrade);
2553
2554            // Set flag to monitor and not change apk file paths when
2555            // scanning install directories.
2556            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2557
2558            if (mIsUpgrade || mFirstBoot) {
2559                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2560            }
2561
2562            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2563            // For security and version matching reason, only consider
2564            // overlay packages if they reside in the right directory.
2565            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2566                    mDefParseFlags
2567                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2568                    scanFlags
2569                    | SCAN_AS_SYSTEM
2570                    | SCAN_AS_VENDOR,
2571                    0);
2572            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2573                    mDefParseFlags
2574                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2575                    scanFlags
2576                    | SCAN_AS_SYSTEM
2577                    | SCAN_AS_PRODUCT,
2578                    0);
2579
2580            mParallelPackageParserCallback.findStaticOverlayPackages();
2581
2582            // Find base frameworks (resource packages without code).
2583            scanDirTracedLI(frameworkDir,
2584                    mDefParseFlags
2585                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2586                    scanFlags
2587                    | SCAN_NO_DEX
2588                    | SCAN_AS_SYSTEM
2589                    | SCAN_AS_PRIVILEGED,
2590                    0);
2591
2592            // Collected privileged system packages.
2593            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2594            scanDirTracedLI(privilegedAppDir,
2595                    mDefParseFlags
2596                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2597                    scanFlags
2598                    | SCAN_AS_SYSTEM
2599                    | SCAN_AS_PRIVILEGED,
2600                    0);
2601
2602            // Collect ordinary system packages.
2603            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2604            scanDirTracedLI(systemAppDir,
2605                    mDefParseFlags
2606                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2607                    scanFlags
2608                    | SCAN_AS_SYSTEM,
2609                    0);
2610
2611            // Collected privileged vendor packages.
2612            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2613            try {
2614                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2615            } catch (IOException e) {
2616                // failed to look up canonical path, continue with original one
2617            }
2618            scanDirTracedLI(privilegedVendorAppDir,
2619                    mDefParseFlags
2620                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2621                    scanFlags
2622                    | SCAN_AS_SYSTEM
2623                    | SCAN_AS_VENDOR
2624                    | SCAN_AS_PRIVILEGED,
2625                    0);
2626
2627            // Collect ordinary vendor packages.
2628            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2629            try {
2630                vendorAppDir = vendorAppDir.getCanonicalFile();
2631            } catch (IOException e) {
2632                // failed to look up canonical path, continue with original one
2633            }
2634            scanDirTracedLI(vendorAppDir,
2635                    mDefParseFlags
2636                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2637                    scanFlags
2638                    | SCAN_AS_SYSTEM
2639                    | SCAN_AS_VENDOR,
2640                    0);
2641
2642            // Collect all OEM packages.
2643            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2644            scanDirTracedLI(oemAppDir,
2645                    mDefParseFlags
2646                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2647                    scanFlags
2648                    | SCAN_AS_SYSTEM
2649                    | SCAN_AS_OEM,
2650                    0);
2651
2652            // Collected privileged product packages.
2653            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2654            try {
2655                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2656            } catch (IOException e) {
2657                // failed to look up canonical path, continue with original one
2658            }
2659            scanDirTracedLI(privilegedProductAppDir,
2660                    mDefParseFlags
2661                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2662                    scanFlags
2663                    | SCAN_AS_SYSTEM
2664                    | SCAN_AS_PRODUCT
2665                    | SCAN_AS_PRIVILEGED,
2666                    0);
2667
2668            // Collect ordinary product packages.
2669            File productAppDir = new File(Environment.getProductDirectory(), "app");
2670            try {
2671                productAppDir = productAppDir.getCanonicalFile();
2672            } catch (IOException e) {
2673                // failed to look up canonical path, continue with original one
2674            }
2675            scanDirTracedLI(productAppDir,
2676                    mDefParseFlags
2677                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2678                    scanFlags
2679                    | SCAN_AS_SYSTEM
2680                    | SCAN_AS_PRODUCT,
2681                    0);
2682
2683            // Prune any system packages that no longer exist.
2684            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2685            // Stub packages must either be replaced with full versions in the /data
2686            // partition or be disabled.
2687            final List<String> stubSystemApps = new ArrayList<>();
2688            if (!mOnlyCore) {
2689                // do this first before mucking with mPackages for the "expecting better" case
2690                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2691                while (pkgIterator.hasNext()) {
2692                    final PackageParser.Package pkg = pkgIterator.next();
2693                    if (pkg.isStub) {
2694                        stubSystemApps.add(pkg.packageName);
2695                    }
2696                }
2697
2698                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2699                while (psit.hasNext()) {
2700                    PackageSetting ps = psit.next();
2701
2702                    /*
2703                     * If this is not a system app, it can't be a
2704                     * disable system app.
2705                     */
2706                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2707                        continue;
2708                    }
2709
2710                    /*
2711                     * If the package is scanned, it's not erased.
2712                     */
2713                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2714                    if (scannedPkg != null) {
2715                        /*
2716                         * If the system app is both scanned and in the
2717                         * disabled packages list, then it must have been
2718                         * added via OTA. Remove it from the currently
2719                         * scanned package so the previously user-installed
2720                         * application can be scanned.
2721                         */
2722                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2723                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2724                                    + ps.name + "; removing system app.  Last known codePath="
2725                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2726                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2727                                    + scannedPkg.getLongVersionCode());
2728                            removePackageLI(scannedPkg, true);
2729                            mExpectingBetter.put(ps.name, ps.codePath);
2730                        }
2731
2732                        continue;
2733                    }
2734
2735                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2736                        psit.remove();
2737                        logCriticalInfo(Log.WARN, "System package " + ps.name
2738                                + " no longer exists; it's data will be wiped");
2739                        // Actual deletion of code and data will be handled by later
2740                        // reconciliation step
2741                    } else {
2742                        // we still have a disabled system package, but, it still might have
2743                        // been removed. check the code path still exists and check there's
2744                        // still a package. the latter can happen if an OTA keeps the same
2745                        // code path, but, changes the package name.
2746                        final PackageSetting disabledPs =
2747                                mSettings.getDisabledSystemPkgLPr(ps.name);
2748                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2749                                || disabledPs.pkg == null) {
2750                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2751                        }
2752                    }
2753                }
2754            }
2755
2756            //look for any incomplete package installations
2757            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2758            for (int i = 0; i < deletePkgsList.size(); i++) {
2759                // Actual deletion of code and data will be handled by later
2760                // reconciliation step
2761                final String packageName = deletePkgsList.get(i).name;
2762                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2763                synchronized (mPackages) {
2764                    mSettings.removePackageLPw(packageName);
2765                }
2766            }
2767
2768            //delete tmp files
2769            deleteTempPackageFiles();
2770
2771            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2772
2773            // Remove any shared userIDs that have no associated packages
2774            mSettings.pruneSharedUsersLPw();
2775            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2776            final int systemPackagesCount = mPackages.size();
2777            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2778                    + " ms, packageCount: " + systemPackagesCount
2779                    + " , timePerPackage: "
2780                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2781                    + " , cached: " + cachedSystemApps);
2782            if (mIsUpgrade && systemPackagesCount > 0) {
2783                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2784                        ((int) systemScanTime) / systemPackagesCount);
2785            }
2786            if (!mOnlyCore) {
2787                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2788                        SystemClock.uptimeMillis());
2789                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2790
2791                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2792                        | PackageParser.PARSE_FORWARD_LOCK,
2793                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2794
2795                // Remove disable package settings for updated system apps that were
2796                // removed via an OTA. If the update is no longer present, remove the
2797                // app completely. Otherwise, revoke their system privileges.
2798                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2799                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2800                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2801                    final String msg;
2802                    if (deletedPkg == null) {
2803                        // should have found an update, but, we didn't; remove everything
2804                        msg = "Updated system package " + deletedAppName
2805                                + " no longer exists; removing its data";
2806                        // Actual deletion of code and data will be handled by later
2807                        // reconciliation step
2808                    } else {
2809                        // found an update; revoke system privileges
2810                        msg = "Updated system package + " + deletedAppName
2811                                + " no longer exists; revoking system privileges";
2812
2813                        // Don't do anything if a stub is removed from the system image. If
2814                        // we were to remove the uncompressed version from the /data partition,
2815                        // this is where it'd be done.
2816
2817                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2818                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2819                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2820                    }
2821                    logCriticalInfo(Log.WARN, msg);
2822                }
2823
2824                /*
2825                 * Make sure all system apps that we expected to appear on
2826                 * the userdata partition actually showed up. If they never
2827                 * appeared, crawl back and revive the system version.
2828                 */
2829                for (int i = 0; i < mExpectingBetter.size(); i++) {
2830                    final String packageName = mExpectingBetter.keyAt(i);
2831                    if (!mPackages.containsKey(packageName)) {
2832                        final File scanFile = mExpectingBetter.valueAt(i);
2833
2834                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2835                                + " but never showed up; reverting to system");
2836
2837                        final @ParseFlags int reparseFlags;
2838                        final @ScanFlags int rescanFlags;
2839                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2840                            reparseFlags =
2841                                    mDefParseFlags |
2842                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2843                            rescanFlags =
2844                                    scanFlags
2845                                    | SCAN_AS_SYSTEM
2846                                    | SCAN_AS_PRIVILEGED;
2847                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2848                            reparseFlags =
2849                                    mDefParseFlags |
2850                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2851                            rescanFlags =
2852                                    scanFlags
2853                                    | SCAN_AS_SYSTEM;
2854                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)) {
2855                            reparseFlags =
2856                                    mDefParseFlags |
2857                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2858                            rescanFlags =
2859                                    scanFlags
2860                                    | SCAN_AS_SYSTEM
2861                                    | SCAN_AS_VENDOR
2862                                    | SCAN_AS_PRIVILEGED;
2863                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2864                            reparseFlags =
2865                                    mDefParseFlags |
2866                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2867                            rescanFlags =
2868                                    scanFlags
2869                                    | SCAN_AS_SYSTEM
2870                                    | SCAN_AS_VENDOR;
2871                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2872                            reparseFlags =
2873                                    mDefParseFlags |
2874                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2875                            rescanFlags =
2876                                    scanFlags
2877                                    | SCAN_AS_SYSTEM
2878                                    | SCAN_AS_OEM;
2879                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2880                            reparseFlags =
2881                                    mDefParseFlags |
2882                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2883                            rescanFlags =
2884                                    scanFlags
2885                                    | SCAN_AS_SYSTEM
2886                                    | SCAN_AS_PRODUCT
2887                                    | SCAN_AS_PRIVILEGED;
2888                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2889                            reparseFlags =
2890                                    mDefParseFlags |
2891                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2892                            rescanFlags =
2893                                    scanFlags
2894                                    | SCAN_AS_SYSTEM
2895                                    | SCAN_AS_PRODUCT;
2896                        } else {
2897                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2898                            continue;
2899                        }
2900
2901                        mSettings.enableSystemPackageLPw(packageName);
2902
2903                        try {
2904                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2905                        } catch (PackageManagerException e) {
2906                            Slog.e(TAG, "Failed to parse original system package: "
2907                                    + e.getMessage());
2908                        }
2909                    }
2910                }
2911
2912                // Uncompress and install any stubbed system applications.
2913                // This must be done last to ensure all stubs are replaced or disabled.
2914                decompressSystemApplications(stubSystemApps, scanFlags);
2915
2916                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2917                                - cachedSystemApps;
2918
2919                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2920                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2921                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2922                        + " ms, packageCount: " + dataPackagesCount
2923                        + " , timePerPackage: "
2924                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2925                        + " , cached: " + cachedNonSystemApps);
2926                if (mIsUpgrade && dataPackagesCount > 0) {
2927                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2928                            ((int) dataScanTime) / dataPackagesCount);
2929                }
2930            }
2931            mExpectingBetter.clear();
2932
2933            // Resolve the storage manager.
2934            mStorageManagerPackage = getStorageManagerPackageName();
2935
2936            // Resolve protected action filters. Only the setup wizard is allowed to
2937            // have a high priority filter for these actions.
2938            mSetupWizardPackage = getSetupWizardPackageName();
2939            if (mProtectedFilters.size() > 0) {
2940                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2941                    Slog.i(TAG, "No setup wizard;"
2942                        + " All protected intents capped to priority 0");
2943                }
2944                for (ActivityIntentInfo filter : mProtectedFilters) {
2945                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2946                        if (DEBUG_FILTERS) {
2947                            Slog.i(TAG, "Found setup wizard;"
2948                                + " allow priority " + filter.getPriority() + ";"
2949                                + " package: " + filter.activity.info.packageName
2950                                + " activity: " + filter.activity.className
2951                                + " priority: " + filter.getPriority());
2952                        }
2953                        // skip setup wizard; allow it to keep the high priority filter
2954                        continue;
2955                    }
2956                    if (DEBUG_FILTERS) {
2957                        Slog.i(TAG, "Protected action; cap priority to 0;"
2958                                + " package: " + filter.activity.info.packageName
2959                                + " activity: " + filter.activity.className
2960                                + " origPrio: " + filter.getPriority());
2961                    }
2962                    filter.setPriority(0);
2963                }
2964            }
2965            mDeferProtectedFilters = false;
2966            mProtectedFilters.clear();
2967
2968            // Now that we know all of the shared libraries, update all clients to have
2969            // the correct library paths.
2970            updateAllSharedLibrariesLPw(null);
2971
2972            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2973                // NOTE: We ignore potential failures here during a system scan (like
2974                // the rest of the commands above) because there's precious little we
2975                // can do about it. A settings error is reported, though.
2976                final List<String> changedAbiCodePath =
2977                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2978                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
2979                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
2980                        final String codePathString = changedAbiCodePath.get(i);
2981                        try {
2982                            mInstaller.rmdex(codePathString,
2983                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
2984                        } catch (InstallerException ignored) {
2985                        }
2986                    }
2987                }
2988            }
2989
2990            // Now that we know all the packages we are keeping,
2991            // read and update their last usage times.
2992            mPackageUsage.read(mPackages);
2993            mCompilerStats.read();
2994
2995            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2996                    SystemClock.uptimeMillis());
2997            Slog.i(TAG, "Time to scan packages: "
2998                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2999                    + " seconds");
3000
3001            // If the platform SDK has changed since the last time we booted,
3002            // we need to re-grant app permission to catch any new ones that
3003            // appear.  This is really a hack, and means that apps can in some
3004            // cases get permissions that the user didn't initially explicitly
3005            // allow...  it would be nice to have some better way to handle
3006            // this situation.
3007            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3008            if (sdkUpdated) {
3009                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3010                        + mSdkVersion + "; regranting permissions for internal storage");
3011            }
3012            mPermissionManager.updateAllPermissions(
3013                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3014                    mPermissionCallback);
3015            ver.sdkVersion = mSdkVersion;
3016
3017            // If this is the first boot or an update from pre-M, and it is a normal
3018            // boot, then we need to initialize the default preferred apps across
3019            // all defined users.
3020            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3021                for (UserInfo user : sUserManager.getUsers(true)) {
3022                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3023                    applyFactoryDefaultBrowserLPw(user.id);
3024                    primeDomainVerificationsLPw(user.id);
3025                }
3026            }
3027
3028            // Prepare storage for system user really early during boot,
3029            // since core system apps like SettingsProvider and SystemUI
3030            // can't wait for user to start
3031            final int storageFlags;
3032            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3033                storageFlags = StorageManager.FLAG_STORAGE_DE;
3034            } else {
3035                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3036            }
3037            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3038                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3039                    true /* onlyCoreApps */);
3040            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3041                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3042                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3043                traceLog.traceBegin("AppDataFixup");
3044                try {
3045                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3046                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3047                } catch (InstallerException e) {
3048                    Slog.w(TAG, "Trouble fixing GIDs", e);
3049                }
3050                traceLog.traceEnd();
3051
3052                traceLog.traceBegin("AppDataPrepare");
3053                if (deferPackages == null || deferPackages.isEmpty()) {
3054                    return;
3055                }
3056                int count = 0;
3057                for (String pkgName : deferPackages) {
3058                    PackageParser.Package pkg = null;
3059                    synchronized (mPackages) {
3060                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3061                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3062                            pkg = ps.pkg;
3063                        }
3064                    }
3065                    if (pkg != null) {
3066                        synchronized (mInstallLock) {
3067                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3068                                    true /* maybeMigrateAppData */);
3069                        }
3070                        count++;
3071                    }
3072                }
3073                traceLog.traceEnd();
3074                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3075            }, "prepareAppData");
3076
3077            // If this is first boot after an OTA, and a normal boot, then
3078            // we need to clear code cache directories.
3079            // Note that we do *not* clear the application profiles. These remain valid
3080            // across OTAs and are used to drive profile verification (post OTA) and
3081            // profile compilation (without waiting to collect a fresh set of profiles).
3082            if (mIsUpgrade && !onlyCore) {
3083                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3084                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3085                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3086                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3087                        // No apps are running this early, so no need to freeze
3088                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3089                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3090                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3091                    }
3092                }
3093                ver.fingerprint = Build.FINGERPRINT;
3094            }
3095
3096            checkDefaultBrowser();
3097
3098            // clear only after permissions and other defaults have been updated
3099            mExistingSystemPackages.clear();
3100            mPromoteSystemApps = false;
3101
3102            // All the changes are done during package scanning.
3103            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3104
3105            // can downgrade to reader
3106            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3107            mSettings.writeLPr();
3108            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3109            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3110                    SystemClock.uptimeMillis());
3111
3112            if (!mOnlyCore) {
3113                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3114                mRequiredInstallerPackage = getRequiredInstallerLPr();
3115                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3116                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3117                if (mIntentFilterVerifierComponent != null) {
3118                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3119                            mIntentFilterVerifierComponent);
3120                } else {
3121                    mIntentFilterVerifier = null;
3122                }
3123                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3124                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3125                        SharedLibraryInfo.VERSION_UNDEFINED);
3126                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3127                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3128                        SharedLibraryInfo.VERSION_UNDEFINED);
3129            } else {
3130                mRequiredVerifierPackage = null;
3131                mRequiredInstallerPackage = null;
3132                mRequiredUninstallerPackage = null;
3133                mIntentFilterVerifierComponent = null;
3134                mIntentFilterVerifier = null;
3135                mServicesSystemSharedLibraryPackageName = null;
3136                mSharedSystemSharedLibraryPackageName = null;
3137            }
3138
3139            mInstallerService = new PackageInstallerService(context, this);
3140            final Pair<ComponentName, String> instantAppResolverComponent =
3141                    getInstantAppResolverLPr();
3142            if (instantAppResolverComponent != null) {
3143                if (DEBUG_INSTANT) {
3144                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3145                }
3146                mInstantAppResolverConnection = new InstantAppResolverConnection(
3147                        mContext, instantAppResolverComponent.first,
3148                        instantAppResolverComponent.second);
3149                mInstantAppResolverSettingsComponent =
3150                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3151            } else {
3152                mInstantAppResolverConnection = null;
3153                mInstantAppResolverSettingsComponent = null;
3154            }
3155            updateInstantAppInstallerLocked(null);
3156
3157            // Read and update the usage of dex files.
3158            // Do this at the end of PM init so that all the packages have their
3159            // data directory reconciled.
3160            // At this point we know the code paths of the packages, so we can validate
3161            // the disk file and build the internal cache.
3162            // The usage file is expected to be small so loading and verifying it
3163            // should take a fairly small time compare to the other activities (e.g. package
3164            // scanning).
3165            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3166            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3167            for (int userId : currentUserIds) {
3168                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3169            }
3170            mDexManager.load(userPackages);
3171            if (mIsUpgrade) {
3172                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3173                        (int) (SystemClock.uptimeMillis() - startTime));
3174            }
3175        } // synchronized (mPackages)
3176        } // synchronized (mInstallLock)
3177
3178        // Now after opening every single application zip, make sure they
3179        // are all flushed.  Not really needed, but keeps things nice and
3180        // tidy.
3181        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3182        Runtime.getRuntime().gc();
3183        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3184
3185        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3186        FallbackCategoryProvider.loadFallbacks();
3187        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3188
3189        // The initial scanning above does many calls into installd while
3190        // holding the mPackages lock, but we're mostly interested in yelling
3191        // once we have a booted system.
3192        mInstaller.setWarnIfHeld(mPackages);
3193
3194        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3195    }
3196
3197    /**
3198     * Uncompress and install stub applications.
3199     * <p>In order to save space on the system partition, some applications are shipped in a
3200     * compressed form. In addition the compressed bits for the full application, the
3201     * system image contains a tiny stub comprised of only the Android manifest.
3202     * <p>During the first boot, attempt to uncompress and install the full application. If
3203     * the application can't be installed for any reason, disable the stub and prevent
3204     * uncompressing the full application during future boots.
3205     * <p>In order to forcefully attempt an installation of a full application, go to app
3206     * settings and enable the application.
3207     */
3208    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3209        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3210            final String pkgName = stubSystemApps.get(i);
3211            // skip if the system package is already disabled
3212            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3213                stubSystemApps.remove(i);
3214                continue;
3215            }
3216            // skip if the package isn't installed (?!); this should never happen
3217            final PackageParser.Package pkg = mPackages.get(pkgName);
3218            if (pkg == null) {
3219                stubSystemApps.remove(i);
3220                continue;
3221            }
3222            // skip if the package has been disabled by the user
3223            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3224            if (ps != null) {
3225                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3226                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3227                    stubSystemApps.remove(i);
3228                    continue;
3229                }
3230            }
3231
3232            if (DEBUG_COMPRESSION) {
3233                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3234            }
3235
3236            // uncompress the binary to its eventual destination on /data
3237            final File scanFile = decompressPackage(pkg);
3238            if (scanFile == null) {
3239                continue;
3240            }
3241
3242            // install the package to replace the stub on /system
3243            try {
3244                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3245                removePackageLI(pkg, true /*chatty*/);
3246                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3247                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3248                        UserHandle.USER_SYSTEM, "android");
3249                stubSystemApps.remove(i);
3250                continue;
3251            } catch (PackageManagerException e) {
3252                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3253            }
3254
3255            // any failed attempt to install the package will be cleaned up later
3256        }
3257
3258        // disable any stub still left; these failed to install the full application
3259        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3260            final String pkgName = stubSystemApps.get(i);
3261            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3262            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3263                    UserHandle.USER_SYSTEM, "android");
3264            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3265        }
3266    }
3267
3268    /**
3269     * Decompresses the given package on the system image onto
3270     * the /data partition.
3271     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3272     */
3273    private File decompressPackage(PackageParser.Package pkg) {
3274        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3275        if (compressedFiles == null || compressedFiles.length == 0) {
3276            if (DEBUG_COMPRESSION) {
3277                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3278            }
3279            return null;
3280        }
3281        final File dstCodePath =
3282                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3283        int ret = PackageManager.INSTALL_SUCCEEDED;
3284        try {
3285            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3286            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3287            for (File srcFile : compressedFiles) {
3288                final String srcFileName = srcFile.getName();
3289                final String dstFileName = srcFileName.substring(
3290                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3291                final File dstFile = new File(dstCodePath, dstFileName);
3292                ret = decompressFile(srcFile, dstFile);
3293                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3294                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3295                            + "; pkg: " + pkg.packageName
3296                            + ", file: " + dstFileName);
3297                    break;
3298                }
3299            }
3300        } catch (ErrnoException e) {
3301            logCriticalInfo(Log.ERROR, "Failed to decompress"
3302                    + "; pkg: " + pkg.packageName
3303                    + ", err: " + e.errno);
3304        }
3305        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3306            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3307            NativeLibraryHelper.Handle handle = null;
3308            try {
3309                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3310                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3311                        null /*abiOverride*/);
3312            } catch (IOException e) {
3313                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3314                        + "; pkg: " + pkg.packageName);
3315                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3316            } finally {
3317                IoUtils.closeQuietly(handle);
3318            }
3319        }
3320        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3321            if (dstCodePath == null || !dstCodePath.exists()) {
3322                return null;
3323            }
3324            removeCodePathLI(dstCodePath);
3325            return null;
3326        }
3327
3328        return dstCodePath;
3329    }
3330
3331    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3332        // we're only interested in updating the installer appliction when 1) it's not
3333        // already set or 2) the modified package is the installer
3334        if (mInstantAppInstallerActivity != null
3335                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3336                        .equals(modifiedPackage)) {
3337            return;
3338        }
3339        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3340    }
3341
3342    private static File preparePackageParserCache(boolean isUpgrade) {
3343        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3344            return null;
3345        }
3346
3347        // Disable package parsing on eng builds to allow for faster incremental development.
3348        if (Build.IS_ENG) {
3349            return null;
3350        }
3351
3352        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3353            Slog.i(TAG, "Disabling package parser cache due to system property.");
3354            return null;
3355        }
3356
3357        // The base directory for the package parser cache lives under /data/system/.
3358        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3359                "package_cache");
3360        if (cacheBaseDir == null) {
3361            return null;
3362        }
3363
3364        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3365        // This also serves to "GC" unused entries when the package cache version changes (which
3366        // can only happen during upgrades).
3367        if (isUpgrade) {
3368            FileUtils.deleteContents(cacheBaseDir);
3369        }
3370
3371
3372        // Return the versioned package cache directory. This is something like
3373        // "/data/system/package_cache/1"
3374        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3375
3376        // The following is a workaround to aid development on non-numbered userdebug
3377        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3378        // the system partition is newer.
3379        //
3380        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3381        // that starts with "eng." to signify that this is an engineering build and not
3382        // destined for release.
3383        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3384            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3385
3386            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3387            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3388            // in general and should not be used for production changes. In this specific case,
3389            // we know that they will work.
3390            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3391            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3392                FileUtils.deleteContents(cacheBaseDir);
3393                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3394            }
3395        }
3396
3397        return cacheDir;
3398    }
3399
3400    @Override
3401    public boolean isFirstBoot() {
3402        // allow instant applications
3403        return mFirstBoot;
3404    }
3405
3406    @Override
3407    public boolean isOnlyCoreApps() {
3408        // allow instant applications
3409        return mOnlyCore;
3410    }
3411
3412    @Override
3413    public boolean isUpgrade() {
3414        // allow instant applications
3415        // The system property allows testing ota flow when upgraded to the same image.
3416        return mIsUpgrade || SystemProperties.getBoolean(
3417                "persist.pm.mock-upgrade", false /* default */);
3418    }
3419
3420    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3421        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3422
3423        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3424                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3425                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3426        if (matches.size() == 1) {
3427            return matches.get(0).getComponentInfo().packageName;
3428        } else if (matches.size() == 0) {
3429            Log.e(TAG, "There should probably be a verifier, but, none were found");
3430            return null;
3431        }
3432        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3433    }
3434
3435    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3436        synchronized (mPackages) {
3437            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3438            if (libraryEntry == null) {
3439                throw new IllegalStateException("Missing required shared library:" + name);
3440            }
3441            return libraryEntry.apk;
3442        }
3443    }
3444
3445    private @NonNull String getRequiredInstallerLPr() {
3446        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3447        intent.addCategory(Intent.CATEGORY_DEFAULT);
3448        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3449
3450        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3451                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3452                UserHandle.USER_SYSTEM);
3453        if (matches.size() == 1) {
3454            ResolveInfo resolveInfo = matches.get(0);
3455            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3456                throw new RuntimeException("The installer must be a privileged app");
3457            }
3458            return matches.get(0).getComponentInfo().packageName;
3459        } else {
3460            throw new RuntimeException("There must be exactly one installer; found " + matches);
3461        }
3462    }
3463
3464    private @NonNull String getRequiredUninstallerLPr() {
3465        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3466        intent.addCategory(Intent.CATEGORY_DEFAULT);
3467        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3468
3469        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3470                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3471                UserHandle.USER_SYSTEM);
3472        if (resolveInfo == null ||
3473                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3474            throw new RuntimeException("There must be exactly one uninstaller; found "
3475                    + resolveInfo);
3476        }
3477        return resolveInfo.getComponentInfo().packageName;
3478    }
3479
3480    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3481        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3482
3483        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3484                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3485                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3486        ResolveInfo best = null;
3487        final int N = matches.size();
3488        for (int i = 0; i < N; i++) {
3489            final ResolveInfo cur = matches.get(i);
3490            final String packageName = cur.getComponentInfo().packageName;
3491            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3492                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3493                continue;
3494            }
3495
3496            if (best == null || cur.priority > best.priority) {
3497                best = cur;
3498            }
3499        }
3500
3501        if (best != null) {
3502            return best.getComponentInfo().getComponentName();
3503        }
3504        Slog.w(TAG, "Intent filter verifier not found");
3505        return null;
3506    }
3507
3508    @Override
3509    public @Nullable ComponentName getInstantAppResolverComponent() {
3510        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3511            return null;
3512        }
3513        synchronized (mPackages) {
3514            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3515            if (instantAppResolver == null) {
3516                return null;
3517            }
3518            return instantAppResolver.first;
3519        }
3520    }
3521
3522    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3523        final String[] packageArray =
3524                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3525        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3526            if (DEBUG_INSTANT) {
3527                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3528            }
3529            return null;
3530        }
3531
3532        final int callingUid = Binder.getCallingUid();
3533        final int resolveFlags =
3534                MATCH_DIRECT_BOOT_AWARE
3535                | MATCH_DIRECT_BOOT_UNAWARE
3536                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3537        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3538        final Intent resolverIntent = new Intent(actionName);
3539        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3540                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3541        final int N = resolvers.size();
3542        if (N == 0) {
3543            if (DEBUG_INSTANT) {
3544                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3545            }
3546            return null;
3547        }
3548
3549        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3550        for (int i = 0; i < N; i++) {
3551            final ResolveInfo info = resolvers.get(i);
3552
3553            if (info.serviceInfo == null) {
3554                continue;
3555            }
3556
3557            final String packageName = info.serviceInfo.packageName;
3558            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3559                if (DEBUG_INSTANT) {
3560                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3561                            + " pkg: " + packageName + ", info:" + info);
3562                }
3563                continue;
3564            }
3565
3566            if (DEBUG_INSTANT) {
3567                Slog.v(TAG, "Ephemeral resolver found;"
3568                        + " pkg: " + packageName + ", info:" + info);
3569            }
3570            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3571        }
3572        if (DEBUG_INSTANT) {
3573            Slog.v(TAG, "Ephemeral resolver NOT found");
3574        }
3575        return null;
3576    }
3577
3578    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3579        String[] orderedActions = Build.IS_ENG
3580                ? new String[]{
3581                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3582                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3583                : new String[]{
3584                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3585
3586        final int resolveFlags =
3587                MATCH_DIRECT_BOOT_AWARE
3588                        | MATCH_DIRECT_BOOT_UNAWARE
3589                        | Intent.FLAG_IGNORE_EPHEMERAL
3590                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3591        final Intent intent = new Intent();
3592        intent.addCategory(Intent.CATEGORY_DEFAULT);
3593        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3594        List<ResolveInfo> matches = null;
3595        for (String action : orderedActions) {
3596            intent.setAction(action);
3597            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3598                    resolveFlags, UserHandle.USER_SYSTEM);
3599            if (matches.isEmpty()) {
3600                if (DEBUG_INSTANT) {
3601                    Slog.d(TAG, "Instant App installer not found with " + action);
3602                }
3603            } else {
3604                break;
3605            }
3606        }
3607        Iterator<ResolveInfo> iter = matches.iterator();
3608        while (iter.hasNext()) {
3609            final ResolveInfo rInfo = iter.next();
3610            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3611            if (ps != null) {
3612                final PermissionsState permissionsState = ps.getPermissionsState();
3613                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3614                        || Build.IS_ENG) {
3615                    continue;
3616                }
3617            }
3618            iter.remove();
3619        }
3620        if (matches.size() == 0) {
3621            return null;
3622        } else if (matches.size() == 1) {
3623            return (ActivityInfo) matches.get(0).getComponentInfo();
3624        } else {
3625            throw new RuntimeException(
3626                    "There must be at most one ephemeral installer; found " + matches);
3627        }
3628    }
3629
3630    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3631            @NonNull ComponentName resolver) {
3632        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3633                .addCategory(Intent.CATEGORY_DEFAULT)
3634                .setPackage(resolver.getPackageName());
3635        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3636        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3637                UserHandle.USER_SYSTEM);
3638        if (matches.isEmpty()) {
3639            return null;
3640        }
3641        return matches.get(0).getComponentInfo().getComponentName();
3642    }
3643
3644    private void primeDomainVerificationsLPw(int userId) {
3645        if (DEBUG_DOMAIN_VERIFICATION) {
3646            Slog.d(TAG, "Priming domain verifications in user " + userId);
3647        }
3648
3649        SystemConfig systemConfig = SystemConfig.getInstance();
3650        ArraySet<String> packages = systemConfig.getLinkedApps();
3651
3652        for (String packageName : packages) {
3653            PackageParser.Package pkg = mPackages.get(packageName);
3654            if (pkg != null) {
3655                if (!pkg.isSystem()) {
3656                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3657                    continue;
3658                }
3659
3660                ArraySet<String> domains = null;
3661                for (PackageParser.Activity a : pkg.activities) {
3662                    for (ActivityIntentInfo filter : a.intents) {
3663                        if (hasValidDomains(filter)) {
3664                            if (domains == null) {
3665                                domains = new ArraySet<String>();
3666                            }
3667                            domains.addAll(filter.getHostsList());
3668                        }
3669                    }
3670                }
3671
3672                if (domains != null && domains.size() > 0) {
3673                    if (DEBUG_DOMAIN_VERIFICATION) {
3674                        Slog.v(TAG, "      + " + packageName);
3675                    }
3676                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3677                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3678                    // and then 'always' in the per-user state actually used for intent resolution.
3679                    final IntentFilterVerificationInfo ivi;
3680                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3681                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3682                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3683                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3684                } else {
3685                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3686                            + "' does not handle web links");
3687                }
3688            } else {
3689                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3690            }
3691        }
3692
3693        scheduleWritePackageRestrictionsLocked(userId);
3694        scheduleWriteSettingsLocked();
3695    }
3696
3697    private void applyFactoryDefaultBrowserLPw(int userId) {
3698        // The default browser app's package name is stored in a string resource,
3699        // with a product-specific overlay used for vendor customization.
3700        String browserPkg = mContext.getResources().getString(
3701                com.android.internal.R.string.default_browser);
3702        if (!TextUtils.isEmpty(browserPkg)) {
3703            // non-empty string => required to be a known package
3704            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3705            if (ps == null) {
3706                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3707                browserPkg = null;
3708            } else {
3709                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3710            }
3711        }
3712
3713        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3714        // default.  If there's more than one, just leave everything alone.
3715        if (browserPkg == null) {
3716            calculateDefaultBrowserLPw(userId);
3717        }
3718    }
3719
3720    private void calculateDefaultBrowserLPw(int userId) {
3721        List<String> allBrowsers = resolveAllBrowserApps(userId);
3722        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3723        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3724    }
3725
3726    private List<String> resolveAllBrowserApps(int userId) {
3727        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3728        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3729                PackageManager.MATCH_ALL, userId);
3730
3731        final int count = list.size();
3732        List<String> result = new ArrayList<String>(count);
3733        for (int i=0; i<count; i++) {
3734            ResolveInfo info = list.get(i);
3735            if (info.activityInfo == null
3736                    || !info.handleAllWebDataURI
3737                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3738                    || result.contains(info.activityInfo.packageName)) {
3739                continue;
3740            }
3741            result.add(info.activityInfo.packageName);
3742        }
3743
3744        return result;
3745    }
3746
3747    private boolean packageIsBrowser(String packageName, int userId) {
3748        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3749                PackageManager.MATCH_ALL, userId);
3750        final int N = list.size();
3751        for (int i = 0; i < N; i++) {
3752            ResolveInfo info = list.get(i);
3753            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3754                return true;
3755            }
3756        }
3757        return false;
3758    }
3759
3760    private void checkDefaultBrowser() {
3761        final int myUserId = UserHandle.myUserId();
3762        final String packageName = getDefaultBrowserPackageName(myUserId);
3763        if (packageName != null) {
3764            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3765            if (info == null) {
3766                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3767                synchronized (mPackages) {
3768                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3769                }
3770            }
3771        }
3772    }
3773
3774    @Override
3775    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3776            throws RemoteException {
3777        try {
3778            return super.onTransact(code, data, reply, flags);
3779        } catch (RuntimeException e) {
3780            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3781                Slog.wtf(TAG, "Package Manager Crash", e);
3782            }
3783            throw e;
3784        }
3785    }
3786
3787    static int[] appendInts(int[] cur, int[] add) {
3788        if (add == null) return cur;
3789        if (cur == null) return add;
3790        final int N = add.length;
3791        for (int i=0; i<N; i++) {
3792            cur = appendInt(cur, add[i]);
3793        }
3794        return cur;
3795    }
3796
3797    /**
3798     * Returns whether or not a full application can see an instant application.
3799     * <p>
3800     * Currently, there are three cases in which this can occur:
3801     * <ol>
3802     * <li>The calling application is a "special" process. Special processes
3803     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3804     * <li>The calling application has the permission
3805     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3806     * <li>The calling application is the default launcher on the
3807     *     system partition.</li>
3808     * </ol>
3809     */
3810    private boolean canViewInstantApps(int callingUid, int userId) {
3811        if (callingUid < Process.FIRST_APPLICATION_UID) {
3812            return true;
3813        }
3814        if (mContext.checkCallingOrSelfPermission(
3815                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3816            return true;
3817        }
3818        if (mContext.checkCallingOrSelfPermission(
3819                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3820            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3821            if (homeComponent != null
3822                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3823                return true;
3824            }
3825        }
3826        return false;
3827    }
3828
3829    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3830        if (!sUserManager.exists(userId)) return null;
3831        if (ps == null) {
3832            return null;
3833        }
3834        final int callingUid = Binder.getCallingUid();
3835        // Filter out ephemeral app metadata:
3836        //   * The system/shell/root can see metadata for any app
3837        //   * An installed app can see metadata for 1) other installed apps
3838        //     and 2) ephemeral apps that have explicitly interacted with it
3839        //   * Ephemeral apps can only see their own data and exposed installed apps
3840        //   * Holding a signature permission allows seeing instant apps
3841        if (filterAppAccessLPr(ps, callingUid, userId)) {
3842            return null;
3843        }
3844
3845        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3846                && ps.isSystem()) {
3847            flags |= MATCH_ANY_USER;
3848        }
3849
3850        final PackageUserState state = ps.readUserState(userId);
3851        PackageParser.Package p = ps.pkg;
3852        if (p != null) {
3853            final PermissionsState permissionsState = ps.getPermissionsState();
3854
3855            // Compute GIDs only if requested
3856            final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3857                    ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3858            // Compute granted permissions only if package has requested permissions
3859            final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3860                    ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3861
3862            PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3863                    ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3864
3865            if (packageInfo == null) {
3866                return null;
3867            }
3868
3869            packageInfo.packageName = packageInfo.applicationInfo.packageName =
3870                    resolveExternalPackageNameLPr(p);
3871
3872            return packageInfo;
3873        } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
3874            PackageInfo pi = new PackageInfo();
3875            pi.packageName = ps.name;
3876            pi.setLongVersionCode(ps.versionCode);
3877            pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
3878            pi.firstInstallTime = ps.firstInstallTime;
3879            pi.lastUpdateTime = ps.lastUpdateTime;
3880
3881            ApplicationInfo ai = new ApplicationInfo();
3882            ai.packageName = ps.name;
3883            ai.uid = UserHandle.getUid(userId, ps.appId);
3884            ai.primaryCpuAbi = ps.primaryCpuAbiString;
3885            ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
3886            ai.versionCode = ps.versionCode;
3887            ai.flags = ps.pkgFlags;
3888            ai.privateFlags = ps.pkgPrivateFlags;
3889            pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
3890
3891            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
3892                    + ps.name + "]. Provides a minimum info.");
3893            return pi;
3894        } else {
3895            return null;
3896        }
3897    }
3898
3899    @Override
3900    public void checkPackageStartable(String packageName, int userId) {
3901        final int callingUid = Binder.getCallingUid();
3902        if (getInstantAppPackageName(callingUid) != null) {
3903            throw new SecurityException("Instant applications don't have access to this method");
3904        }
3905        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3906        synchronized (mPackages) {
3907            final PackageSetting ps = mSettings.mPackages.get(packageName);
3908            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3909                throw new SecurityException("Package " + packageName + " was not found!");
3910            }
3911
3912            if (!ps.getInstalled(userId)) {
3913                throw new SecurityException(
3914                        "Package " + packageName + " was not installed for user " + userId + "!");
3915            }
3916
3917            if (mSafeMode && !ps.isSystem()) {
3918                throw new SecurityException("Package " + packageName + " not a system app!");
3919            }
3920
3921            if (mFrozenPackages.contains(packageName)) {
3922                throw new SecurityException("Package " + packageName + " is currently frozen!");
3923            }
3924
3925            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3926                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3927            }
3928        }
3929    }
3930
3931    @Override
3932    public boolean isPackageAvailable(String packageName, int userId) {
3933        if (!sUserManager.exists(userId)) return false;
3934        final int callingUid = Binder.getCallingUid();
3935        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3936                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3937        synchronized (mPackages) {
3938            PackageParser.Package p = mPackages.get(packageName);
3939            if (p != null) {
3940                final PackageSetting ps = (PackageSetting) p.mExtras;
3941                if (filterAppAccessLPr(ps, callingUid, userId)) {
3942                    return false;
3943                }
3944                if (ps != null) {
3945                    final PackageUserState state = ps.readUserState(userId);
3946                    if (state != null) {
3947                        return PackageParser.isAvailable(state);
3948                    }
3949                }
3950            }
3951        }
3952        return false;
3953    }
3954
3955    @Override
3956    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3957        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3958                flags, Binder.getCallingUid(), userId);
3959    }
3960
3961    @Override
3962    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3963            int flags, int userId) {
3964        return getPackageInfoInternal(versionedPackage.getPackageName(),
3965                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
3966    }
3967
3968    /**
3969     * Important: The provided filterCallingUid is used exclusively to filter out packages
3970     * that can be seen based on user state. It's typically the original caller uid prior
3971     * to clearing. Because it can only be provided by trusted code, it's value can be
3972     * trusted and will be used as-is; unlike userId which will be validated by this method.
3973     */
3974    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
3975            int flags, int filterCallingUid, int userId) {
3976        if (!sUserManager.exists(userId)) return null;
3977        flags = updateFlagsForPackage(flags, userId, packageName);
3978        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3979                false /* requireFullPermission */, false /* checkShell */, "get package info");
3980
3981        // reader
3982        synchronized (mPackages) {
3983            // Normalize package name to handle renamed packages and static libs
3984            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3985
3986            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3987            if (matchFactoryOnly) {
3988                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3989                if (ps != null) {
3990                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3991                        return null;
3992                    }
3993                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3994                        return null;
3995                    }
3996                    return generatePackageInfo(ps, flags, userId);
3997                }
3998            }
3999
4000            PackageParser.Package p = mPackages.get(packageName);
4001            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
4002                return null;
4003            }
4004            if (DEBUG_PACKAGE_INFO)
4005                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4006            if (p != null) {
4007                final PackageSetting ps = (PackageSetting) p.mExtras;
4008                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4009                    return null;
4010                }
4011                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4012                    return null;
4013                }
4014                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4015            }
4016            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4017                final PackageSetting ps = mSettings.mPackages.get(packageName);
4018                if (ps == null) return null;
4019                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4020                    return null;
4021                }
4022                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4023                    return null;
4024                }
4025                return generatePackageInfo(ps, flags, userId);
4026            }
4027        }
4028        return null;
4029    }
4030
4031    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4032        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4033            return true;
4034        }
4035        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4036            return true;
4037        }
4038        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4039            return true;
4040        }
4041        return false;
4042    }
4043
4044    private boolean isComponentVisibleToInstantApp(
4045            @Nullable ComponentName component, @ComponentType int type) {
4046        if (type == TYPE_ACTIVITY) {
4047            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4048            return activity != null
4049                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4050                    : false;
4051        } else if (type == TYPE_RECEIVER) {
4052            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4053            return activity != null
4054                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4055                    : false;
4056        } else if (type == TYPE_SERVICE) {
4057            final PackageParser.Service service = mServices.mServices.get(component);
4058            return service != null
4059                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4060                    : false;
4061        } else if (type == TYPE_PROVIDER) {
4062            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4063            return provider != null
4064                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4065                    : false;
4066        } else if (type == TYPE_UNKNOWN) {
4067            return isComponentVisibleToInstantApp(component);
4068        }
4069        return false;
4070    }
4071
4072    /**
4073     * Returns whether or not access to the application should be filtered.
4074     * <p>
4075     * Access may be limited based upon whether the calling or target applications
4076     * are instant applications.
4077     *
4078     * @see #canAccessInstantApps(int)
4079     */
4080    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4081            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4082        // if we're in an isolated process, get the real calling UID
4083        if (Process.isIsolated(callingUid)) {
4084            callingUid = mIsolatedOwners.get(callingUid);
4085        }
4086        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4087        final boolean callerIsInstantApp = instantAppPkgName != null;
4088        if (ps == null) {
4089            if (callerIsInstantApp) {
4090                // pretend the application exists, but, needs to be filtered
4091                return true;
4092            }
4093            return false;
4094        }
4095        // if the target and caller are the same application, don't filter
4096        if (isCallerSameApp(ps.name, callingUid)) {
4097            return false;
4098        }
4099        if (callerIsInstantApp) {
4100            // request for a specific component; if it hasn't been explicitly exposed, filter
4101            if (component != null) {
4102                return !isComponentVisibleToInstantApp(component, componentType);
4103            }
4104            // request for application; if no components have been explicitly exposed, filter
4105            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4106        }
4107        if (ps.getInstantApp(userId)) {
4108            // caller can see all components of all instant applications, don't filter
4109            if (canViewInstantApps(callingUid, userId)) {
4110                return false;
4111            }
4112            // request for a specific instant application component, filter
4113            if (component != null) {
4114                return true;
4115            }
4116            // request for an instant application; if the caller hasn't been granted access, filter
4117            return !mInstantAppRegistry.isInstantAccessGranted(
4118                    userId, UserHandle.getAppId(callingUid), ps.appId);
4119        }
4120        return false;
4121    }
4122
4123    /**
4124     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4125     */
4126    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4127        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4128    }
4129
4130    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4131            int flags) {
4132        // Callers can access only the libs they depend on, otherwise they need to explicitly
4133        // ask for the shared libraries given the caller is allowed to access all static libs.
4134        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4135            // System/shell/root get to see all static libs
4136            final int appId = UserHandle.getAppId(uid);
4137            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4138                    || appId == Process.ROOT_UID) {
4139                return false;
4140            }
4141        }
4142
4143        // No package means no static lib as it is always on internal storage
4144        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4145            return false;
4146        }
4147
4148        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4149                ps.pkg.staticSharedLibVersion);
4150        if (libEntry == null) {
4151            return false;
4152        }
4153
4154        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4155        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4156        if (uidPackageNames == null) {
4157            return true;
4158        }
4159
4160        for (String uidPackageName : uidPackageNames) {
4161            if (ps.name.equals(uidPackageName)) {
4162                return false;
4163            }
4164            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4165            if (uidPs != null) {
4166                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4167                        libEntry.info.getName());
4168                if (index < 0) {
4169                    continue;
4170                }
4171                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4172                    return false;
4173                }
4174            }
4175        }
4176        return true;
4177    }
4178
4179    @Override
4180    public String[] currentToCanonicalPackageNames(String[] names) {
4181        final int callingUid = Binder.getCallingUid();
4182        if (getInstantAppPackageName(callingUid) != null) {
4183            return names;
4184        }
4185        final String[] out = new String[names.length];
4186        // reader
4187        synchronized (mPackages) {
4188            final int callingUserId = UserHandle.getUserId(callingUid);
4189            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4190            for (int i=names.length-1; i>=0; i--) {
4191                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4192                boolean translateName = false;
4193                if (ps != null && ps.realName != null) {
4194                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4195                    translateName = !targetIsInstantApp
4196                            || canViewInstantApps
4197                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4198                                    UserHandle.getAppId(callingUid), ps.appId);
4199                }
4200                out[i] = translateName ? ps.realName : names[i];
4201            }
4202        }
4203        return out;
4204    }
4205
4206    @Override
4207    public String[] canonicalToCurrentPackageNames(String[] names) {
4208        final int callingUid = Binder.getCallingUid();
4209        if (getInstantAppPackageName(callingUid) != null) {
4210            return names;
4211        }
4212        final String[] out = new String[names.length];
4213        // reader
4214        synchronized (mPackages) {
4215            final int callingUserId = UserHandle.getUserId(callingUid);
4216            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4217            for (int i=names.length-1; i>=0; i--) {
4218                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4219                boolean translateName = false;
4220                if (cur != null) {
4221                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4222                    final boolean targetIsInstantApp =
4223                            ps != null && ps.getInstantApp(callingUserId);
4224                    translateName = !targetIsInstantApp
4225                            || canViewInstantApps
4226                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4227                                    UserHandle.getAppId(callingUid), ps.appId);
4228                }
4229                out[i] = translateName ? cur : names[i];
4230            }
4231        }
4232        return out;
4233    }
4234
4235    @Override
4236    public int getPackageUid(String packageName, int flags, int userId) {
4237        if (!sUserManager.exists(userId)) return -1;
4238        final int callingUid = Binder.getCallingUid();
4239        flags = updateFlagsForPackage(flags, userId, packageName);
4240        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4241                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4242
4243        // reader
4244        synchronized (mPackages) {
4245            final PackageParser.Package p = mPackages.get(packageName);
4246            if (p != null && p.isMatch(flags)) {
4247                PackageSetting ps = (PackageSetting) p.mExtras;
4248                if (filterAppAccessLPr(ps, callingUid, userId)) {
4249                    return -1;
4250                }
4251                return UserHandle.getUid(userId, p.applicationInfo.uid);
4252            }
4253            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4254                final PackageSetting ps = mSettings.mPackages.get(packageName);
4255                if (ps != null && ps.isMatch(flags)
4256                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4257                    return UserHandle.getUid(userId, ps.appId);
4258                }
4259            }
4260        }
4261
4262        return -1;
4263    }
4264
4265    @Override
4266    public int[] getPackageGids(String packageName, int flags, int userId) {
4267        if (!sUserManager.exists(userId)) return null;
4268        final int callingUid = Binder.getCallingUid();
4269        flags = updateFlagsForPackage(flags, userId, packageName);
4270        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4271                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4272
4273        // reader
4274        synchronized (mPackages) {
4275            final PackageParser.Package p = mPackages.get(packageName);
4276            if (p != null && p.isMatch(flags)) {
4277                PackageSetting ps = (PackageSetting) p.mExtras;
4278                if (filterAppAccessLPr(ps, callingUid, userId)) {
4279                    return null;
4280                }
4281                // TODO: Shouldn't this be checking for package installed state for userId and
4282                // return null?
4283                return ps.getPermissionsState().computeGids(userId);
4284            }
4285            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4286                final PackageSetting ps = mSettings.mPackages.get(packageName);
4287                if (ps != null && ps.isMatch(flags)
4288                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4289                    return ps.getPermissionsState().computeGids(userId);
4290                }
4291            }
4292        }
4293
4294        return null;
4295    }
4296
4297    @Override
4298    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4299        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4300    }
4301
4302    @Override
4303    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4304            int flags) {
4305        final List<PermissionInfo> permissionList =
4306                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4307        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4308    }
4309
4310    @Override
4311    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4312        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4313    }
4314
4315    @Override
4316    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4317        final List<PermissionGroupInfo> permissionList =
4318                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4319        return (permissionList == null)
4320                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4321    }
4322
4323    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4324            int filterCallingUid, int userId) {
4325        if (!sUserManager.exists(userId)) return null;
4326        PackageSetting ps = mSettings.mPackages.get(packageName);
4327        if (ps != null) {
4328            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4329                return null;
4330            }
4331            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4332                return null;
4333            }
4334            if (ps.pkg == null) {
4335                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4336                if (pInfo != null) {
4337                    return pInfo.applicationInfo;
4338                }
4339                return null;
4340            }
4341            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4342                    ps.readUserState(userId), userId);
4343            if (ai != null) {
4344                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4345            }
4346            return ai;
4347        }
4348        return null;
4349    }
4350
4351    @Override
4352    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4353        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4354    }
4355
4356    /**
4357     * Important: The provided filterCallingUid is used exclusively to filter out applications
4358     * that can be seen based on user state. It's typically the original caller uid prior
4359     * to clearing. Because it can only be provided by trusted code, it's value can be
4360     * trusted and will be used as-is; unlike userId which will be validated by this method.
4361     */
4362    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4363            int filterCallingUid, int userId) {
4364        if (!sUserManager.exists(userId)) return null;
4365        flags = updateFlagsForApplication(flags, userId, packageName);
4366        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4367                false /* requireFullPermission */, false /* checkShell */, "get application info");
4368
4369        // writer
4370        synchronized (mPackages) {
4371            // Normalize package name to handle renamed packages and static libs
4372            packageName = resolveInternalPackageNameLPr(packageName,
4373                    PackageManager.VERSION_CODE_HIGHEST);
4374
4375            PackageParser.Package p = mPackages.get(packageName);
4376            if (DEBUG_PACKAGE_INFO) Log.v(
4377                    TAG, "getApplicationInfo " + packageName
4378                    + ": " + p);
4379            if (p != null) {
4380                PackageSetting ps = mSettings.mPackages.get(packageName);
4381                if (ps == null) return null;
4382                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4383                    return null;
4384                }
4385                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4386                    return null;
4387                }
4388                // Note: isEnabledLP() does not apply here - always return info
4389                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4390                        p, flags, ps.readUserState(userId), userId);
4391                if (ai != null) {
4392                    ai.packageName = resolveExternalPackageNameLPr(p);
4393                }
4394                return ai;
4395            }
4396            if ("android".equals(packageName)||"system".equals(packageName)) {
4397                return mAndroidApplication;
4398            }
4399            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4400                // Already generates the external package name
4401                return generateApplicationInfoFromSettingsLPw(packageName,
4402                        flags, filterCallingUid, userId);
4403            }
4404        }
4405        return null;
4406    }
4407
4408    private String normalizePackageNameLPr(String packageName) {
4409        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4410        return normalizedPackageName != null ? normalizedPackageName : packageName;
4411    }
4412
4413    @Override
4414    public void deletePreloadsFileCache() {
4415        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4416            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4417        }
4418        File dir = Environment.getDataPreloadsFileCacheDirectory();
4419        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4420        FileUtils.deleteContents(dir);
4421    }
4422
4423    @Override
4424    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4425            final int storageFlags, final IPackageDataObserver observer) {
4426        mContext.enforceCallingOrSelfPermission(
4427                android.Manifest.permission.CLEAR_APP_CACHE, null);
4428        mHandler.post(() -> {
4429            boolean success = false;
4430            try {
4431                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4432                success = true;
4433            } catch (IOException e) {
4434                Slog.w(TAG, e);
4435            }
4436            if (observer != null) {
4437                try {
4438                    observer.onRemoveCompleted(null, success);
4439                } catch (RemoteException e) {
4440                    Slog.w(TAG, e);
4441                }
4442            }
4443        });
4444    }
4445
4446    @Override
4447    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4448            final int storageFlags, final IntentSender pi) {
4449        mContext.enforceCallingOrSelfPermission(
4450                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4451        mHandler.post(() -> {
4452            boolean success = false;
4453            try {
4454                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4455                success = true;
4456            } catch (IOException e) {
4457                Slog.w(TAG, e);
4458            }
4459            if (pi != null) {
4460                try {
4461                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4462                } catch (SendIntentException e) {
4463                    Slog.w(TAG, e);
4464                }
4465            }
4466        });
4467    }
4468
4469    /**
4470     * Blocking call to clear various types of cached data across the system
4471     * until the requested bytes are available.
4472     */
4473    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4474        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4475        final File file = storage.findPathForUuid(volumeUuid);
4476        if (file.getUsableSpace() >= bytes) return;
4477
4478        if (ENABLE_FREE_CACHE_V2) {
4479            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4480                    volumeUuid);
4481            final boolean aggressive = (storageFlags
4482                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4483            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4484
4485            // 1. Pre-flight to determine if we have any chance to succeed
4486            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4487            if (internalVolume && (aggressive || SystemProperties
4488                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4489                deletePreloadsFileCache();
4490                if (file.getUsableSpace() >= bytes) return;
4491            }
4492
4493            // 3. Consider parsed APK data (aggressive only)
4494            if (internalVolume && aggressive) {
4495                FileUtils.deleteContents(mCacheDir);
4496                if (file.getUsableSpace() >= bytes) return;
4497            }
4498
4499            // 4. Consider cached app data (above quotas)
4500            try {
4501                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4502                        Installer.FLAG_FREE_CACHE_V2);
4503            } catch (InstallerException ignored) {
4504            }
4505            if (file.getUsableSpace() >= bytes) return;
4506
4507            // 5. Consider shared libraries with refcount=0 and age>min cache period
4508            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4509                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4510                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4511                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4512                return;
4513            }
4514
4515            // 6. Consider dexopt output (aggressive only)
4516            // TODO: Implement
4517
4518            // 7. Consider installed instant apps unused longer than min cache period
4519            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4520                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4521                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4522                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4523                return;
4524            }
4525
4526            // 8. Consider cached app data (below quotas)
4527            try {
4528                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4529                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4530            } catch (InstallerException ignored) {
4531            }
4532            if (file.getUsableSpace() >= bytes) return;
4533
4534            // 9. Consider DropBox entries
4535            // TODO: Implement
4536
4537            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4538            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4539                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4540                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4541                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4542                return;
4543            }
4544        } else {
4545            try {
4546                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4547            } catch (InstallerException ignored) {
4548            }
4549            if (file.getUsableSpace() >= bytes) return;
4550        }
4551
4552        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4553    }
4554
4555    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4556            throws IOException {
4557        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4558        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4559
4560        List<VersionedPackage> packagesToDelete = null;
4561        final long now = System.currentTimeMillis();
4562
4563        synchronized (mPackages) {
4564            final int[] allUsers = sUserManager.getUserIds();
4565            final int libCount = mSharedLibraries.size();
4566            for (int i = 0; i < libCount; i++) {
4567                final LongSparseArray<SharedLibraryEntry> versionedLib
4568                        = mSharedLibraries.valueAt(i);
4569                if (versionedLib == null) {
4570                    continue;
4571                }
4572                final int versionCount = versionedLib.size();
4573                for (int j = 0; j < versionCount; j++) {
4574                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4575                    // Skip packages that are not static shared libs.
4576                    if (!libInfo.isStatic()) {
4577                        break;
4578                    }
4579                    // Important: We skip static shared libs used for some user since
4580                    // in such a case we need to keep the APK on the device. The check for
4581                    // a lib being used for any user is performed by the uninstall call.
4582                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4583                    // Resolve the package name - we use synthetic package names internally
4584                    final String internalPackageName = resolveInternalPackageNameLPr(
4585                            declaringPackage.getPackageName(),
4586                            declaringPackage.getLongVersionCode());
4587                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4588                    // Skip unused static shared libs cached less than the min period
4589                    // to prevent pruning a lib needed by a subsequently installed package.
4590                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4591                        continue;
4592                    }
4593                    if (packagesToDelete == null) {
4594                        packagesToDelete = new ArrayList<>();
4595                    }
4596                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4597                            declaringPackage.getLongVersionCode()));
4598                }
4599            }
4600        }
4601
4602        if (packagesToDelete != null) {
4603            final int packageCount = packagesToDelete.size();
4604            for (int i = 0; i < packageCount; i++) {
4605                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4606                // Delete the package synchronously (will fail of the lib used for any user).
4607                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4608                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4609                                == PackageManager.DELETE_SUCCEEDED) {
4610                    if (volume.getUsableSpace() >= neededSpace) {
4611                        return true;
4612                    }
4613                }
4614            }
4615        }
4616
4617        return false;
4618    }
4619
4620    /**
4621     * Update given flags based on encryption status of current user.
4622     */
4623    private int updateFlags(int flags, int userId) {
4624        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4625                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4626            // Caller expressed an explicit opinion about what encryption
4627            // aware/unaware components they want to see, so fall through and
4628            // give them what they want
4629        } else {
4630            // Caller expressed no opinion, so match based on user state
4631            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4632                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4633            } else {
4634                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4635            }
4636        }
4637        return flags;
4638    }
4639
4640    private UserManagerInternal getUserManagerInternal() {
4641        if (mUserManagerInternal == null) {
4642            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4643        }
4644        return mUserManagerInternal;
4645    }
4646
4647    private ActivityManagerInternal getActivityManagerInternal() {
4648        if (mActivityManagerInternal == null) {
4649            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4650        }
4651        return mActivityManagerInternal;
4652    }
4653
4654
4655    private DeviceIdleController.LocalService getDeviceIdleController() {
4656        if (mDeviceIdleController == null) {
4657            mDeviceIdleController =
4658                    LocalServices.getService(DeviceIdleController.LocalService.class);
4659        }
4660        return mDeviceIdleController;
4661    }
4662
4663    /**
4664     * Update given flags when being used to request {@link PackageInfo}.
4665     */
4666    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4667        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4668        boolean triaged = true;
4669        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4670                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4671            // Caller is asking for component details, so they'd better be
4672            // asking for specific encryption matching behavior, or be triaged
4673            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4674                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4675                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4676                triaged = false;
4677            }
4678        }
4679        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4680                | PackageManager.MATCH_SYSTEM_ONLY
4681                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4682            triaged = false;
4683        }
4684        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4685            mPermissionManager.enforceCrossUserPermission(
4686                    Binder.getCallingUid(), userId, false, false,
4687                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4688                    + Debug.getCallers(5));
4689        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4690                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4691            // If the caller wants all packages and has a restricted profile associated with it,
4692            // then match all users. This is to make sure that launchers that need to access work
4693            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4694            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4695            flags |= PackageManager.MATCH_ANY_USER;
4696        }
4697        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4698            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4699                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4700        }
4701        return updateFlags(flags, userId);
4702    }
4703
4704    /**
4705     * Update given flags when being used to request {@link ApplicationInfo}.
4706     */
4707    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4708        return updateFlagsForPackage(flags, userId, cookie);
4709    }
4710
4711    /**
4712     * Update given flags when being used to request {@link ComponentInfo}.
4713     */
4714    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4715        if (cookie instanceof Intent) {
4716            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4717                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4718            }
4719        }
4720
4721        boolean triaged = true;
4722        // Caller is asking for component details, so they'd better be
4723        // asking for specific encryption matching behavior, or be triaged
4724        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4725                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4726                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4727            triaged = false;
4728        }
4729        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4730            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4731                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4732        }
4733
4734        return updateFlags(flags, userId);
4735    }
4736
4737    /**
4738     * Update given intent when being used to request {@link ResolveInfo}.
4739     */
4740    private Intent updateIntentForResolve(Intent intent) {
4741        if (intent.getSelector() != null) {
4742            intent = intent.getSelector();
4743        }
4744        if (DEBUG_PREFERRED) {
4745            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4746        }
4747        return intent;
4748    }
4749
4750    /**
4751     * Update given flags when being used to request {@link ResolveInfo}.
4752     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4753     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4754     * flag set. However, this flag is only honoured in three circumstances:
4755     * <ul>
4756     * <li>when called from a system process</li>
4757     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4758     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4759     * action and a {@code android.intent.category.BROWSABLE} category</li>
4760     * </ul>
4761     */
4762    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4763        return updateFlagsForResolve(flags, userId, intent, callingUid,
4764                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4765    }
4766    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4767            boolean wantInstantApps) {
4768        return updateFlagsForResolve(flags, userId, intent, callingUid,
4769                wantInstantApps, false /*onlyExposedExplicitly*/);
4770    }
4771    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4772            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4773        // Safe mode means we shouldn't match any third-party components
4774        if (mSafeMode) {
4775            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4776        }
4777        if (getInstantAppPackageName(callingUid) != null) {
4778            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4779            if (onlyExposedExplicitly) {
4780                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4781            }
4782            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4783            flags |= PackageManager.MATCH_INSTANT;
4784        } else {
4785            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4786            final boolean allowMatchInstant = wantInstantApps
4787                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4788            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4789                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4790            if (!allowMatchInstant) {
4791                flags &= ~PackageManager.MATCH_INSTANT;
4792            }
4793        }
4794        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4795    }
4796
4797    @Override
4798    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4799        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4800    }
4801
4802    /**
4803     * Important: The provided filterCallingUid is used exclusively to filter out activities
4804     * that can be seen based on user state. It's typically the original caller uid prior
4805     * to clearing. Because it can only be provided by trusted code, it's value can be
4806     * trusted and will be used as-is; unlike userId which will be validated by this method.
4807     */
4808    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4809            int filterCallingUid, int userId) {
4810        if (!sUserManager.exists(userId)) return null;
4811        flags = updateFlagsForComponent(flags, userId, component);
4812
4813        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4814            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4815                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4816        }
4817
4818        synchronized (mPackages) {
4819            PackageParser.Activity a = mActivities.mActivities.get(component);
4820
4821            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4822            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4823                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4824                if (ps == null) return null;
4825                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4826                    return null;
4827                }
4828                return PackageParser.generateActivityInfo(
4829                        a, flags, ps.readUserState(userId), userId);
4830            }
4831            if (mResolveComponentName.equals(component)) {
4832                return PackageParser.generateActivityInfo(
4833                        mResolveActivity, flags, new PackageUserState(), userId);
4834            }
4835        }
4836        return null;
4837    }
4838
4839    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4840        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4841            return false;
4842        }
4843        final long token = Binder.clearCallingIdentity();
4844        try {
4845            final int callingUserId = UserHandle.getUserId(callingUid);
4846            if (ActivityManager.getCurrentUser() != callingUserId) {
4847                return false;
4848            }
4849            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4850        } finally {
4851            Binder.restoreCallingIdentity(token);
4852        }
4853    }
4854
4855    @Override
4856    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4857            String resolvedType) {
4858        synchronized (mPackages) {
4859            if (component.equals(mResolveComponentName)) {
4860                // The resolver supports EVERYTHING!
4861                return true;
4862            }
4863            final int callingUid = Binder.getCallingUid();
4864            final int callingUserId = UserHandle.getUserId(callingUid);
4865            PackageParser.Activity a = mActivities.mActivities.get(component);
4866            if (a == null) {
4867                return false;
4868            }
4869            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4870            if (ps == null) {
4871                return false;
4872            }
4873            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4874                return false;
4875            }
4876            for (int i=0; i<a.intents.size(); i++) {
4877                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4878                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4879                    return true;
4880                }
4881            }
4882            return false;
4883        }
4884    }
4885
4886    @Override
4887    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4888        if (!sUserManager.exists(userId)) return null;
4889        final int callingUid = Binder.getCallingUid();
4890        flags = updateFlagsForComponent(flags, userId, component);
4891        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4892                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4893        synchronized (mPackages) {
4894            PackageParser.Activity a = mReceivers.mActivities.get(component);
4895            if (DEBUG_PACKAGE_INFO) Log.v(
4896                TAG, "getReceiverInfo " + component + ": " + a);
4897            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4898                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4899                if (ps == null) return null;
4900                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4901                    return null;
4902                }
4903                return PackageParser.generateActivityInfo(
4904                        a, flags, ps.readUserState(userId), userId);
4905            }
4906        }
4907        return null;
4908    }
4909
4910    @Override
4911    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4912            int flags, int userId) {
4913        if (!sUserManager.exists(userId)) return null;
4914        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4915        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4916            return null;
4917        }
4918
4919        flags = updateFlagsForPackage(flags, userId, null);
4920
4921        final boolean canSeeStaticLibraries =
4922                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4923                        == PERMISSION_GRANTED
4924                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4925                        == PERMISSION_GRANTED
4926                || canRequestPackageInstallsInternal(packageName,
4927                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4928                        false  /* throwIfPermNotDeclared*/)
4929                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4930                        == PERMISSION_GRANTED;
4931
4932        synchronized (mPackages) {
4933            List<SharedLibraryInfo> result = null;
4934
4935            final int libCount = mSharedLibraries.size();
4936            for (int i = 0; i < libCount; i++) {
4937                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4938                if (versionedLib == null) {
4939                    continue;
4940                }
4941
4942                final int versionCount = versionedLib.size();
4943                for (int j = 0; j < versionCount; j++) {
4944                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4945                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4946                        break;
4947                    }
4948                    final long identity = Binder.clearCallingIdentity();
4949                    try {
4950                        PackageInfo packageInfo = getPackageInfoVersioned(
4951                                libInfo.getDeclaringPackage(), flags
4952                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4953                        if (packageInfo == null) {
4954                            continue;
4955                        }
4956                    } finally {
4957                        Binder.restoreCallingIdentity(identity);
4958                    }
4959
4960                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4961                            libInfo.getLongVersion(), libInfo.getType(),
4962                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4963                            flags, userId));
4964
4965                    if (result == null) {
4966                        result = new ArrayList<>();
4967                    }
4968                    result.add(resLibInfo);
4969                }
4970            }
4971
4972            return result != null ? new ParceledListSlice<>(result) : null;
4973        }
4974    }
4975
4976    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4977            SharedLibraryInfo libInfo, int flags, int userId) {
4978        List<VersionedPackage> versionedPackages = null;
4979        final int packageCount = mSettings.mPackages.size();
4980        for (int i = 0; i < packageCount; i++) {
4981            PackageSetting ps = mSettings.mPackages.valueAt(i);
4982
4983            if (ps == null) {
4984                continue;
4985            }
4986
4987            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4988                continue;
4989            }
4990
4991            final String libName = libInfo.getName();
4992            if (libInfo.isStatic()) {
4993                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4994                if (libIdx < 0) {
4995                    continue;
4996                }
4997                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
4998                    continue;
4999                }
5000                if (versionedPackages == null) {
5001                    versionedPackages = new ArrayList<>();
5002                }
5003                // If the dependent is a static shared lib, use the public package name
5004                String dependentPackageName = ps.name;
5005                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5006                    dependentPackageName = ps.pkg.manifestPackageName;
5007                }
5008                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5009            } else if (ps.pkg != null) {
5010                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5011                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5012                    if (versionedPackages == null) {
5013                        versionedPackages = new ArrayList<>();
5014                    }
5015                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5016                }
5017            }
5018        }
5019
5020        return versionedPackages;
5021    }
5022
5023    @Override
5024    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5025        if (!sUserManager.exists(userId)) return null;
5026        final int callingUid = Binder.getCallingUid();
5027        flags = updateFlagsForComponent(flags, userId, component);
5028        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5029                false /* requireFullPermission */, false /* checkShell */, "get service info");
5030        synchronized (mPackages) {
5031            PackageParser.Service s = mServices.mServices.get(component);
5032            if (DEBUG_PACKAGE_INFO) Log.v(
5033                TAG, "getServiceInfo " + component + ": " + s);
5034            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5035                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5036                if (ps == null) return null;
5037                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5038                    return null;
5039                }
5040                return PackageParser.generateServiceInfo(
5041                        s, flags, ps.readUserState(userId), userId);
5042            }
5043        }
5044        return null;
5045    }
5046
5047    @Override
5048    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5049        if (!sUserManager.exists(userId)) return null;
5050        final int callingUid = Binder.getCallingUid();
5051        flags = updateFlagsForComponent(flags, userId, component);
5052        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5053                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5054        synchronized (mPackages) {
5055            PackageParser.Provider p = mProviders.mProviders.get(component);
5056            if (DEBUG_PACKAGE_INFO) Log.v(
5057                TAG, "getProviderInfo " + component + ": " + p);
5058            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5059                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5060                if (ps == null) return null;
5061                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5062                    return null;
5063                }
5064                return PackageParser.generateProviderInfo(
5065                        p, flags, ps.readUserState(userId), userId);
5066            }
5067        }
5068        return null;
5069    }
5070
5071    @Override
5072    public String[] getSystemSharedLibraryNames() {
5073        // allow instant applications
5074        synchronized (mPackages) {
5075            Set<String> libs = null;
5076            final int libCount = mSharedLibraries.size();
5077            for (int i = 0; i < libCount; i++) {
5078                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5079                if (versionedLib == null) {
5080                    continue;
5081                }
5082                final int versionCount = versionedLib.size();
5083                for (int j = 0; j < versionCount; j++) {
5084                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5085                    if (!libEntry.info.isStatic()) {
5086                        if (libs == null) {
5087                            libs = new ArraySet<>();
5088                        }
5089                        libs.add(libEntry.info.getName());
5090                        break;
5091                    }
5092                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5093                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5094                            UserHandle.getUserId(Binder.getCallingUid()),
5095                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5096                        if (libs == null) {
5097                            libs = new ArraySet<>();
5098                        }
5099                        libs.add(libEntry.info.getName());
5100                        break;
5101                    }
5102                }
5103            }
5104
5105            if (libs != null) {
5106                String[] libsArray = new String[libs.size()];
5107                libs.toArray(libsArray);
5108                return libsArray;
5109            }
5110
5111            return null;
5112        }
5113    }
5114
5115    @Override
5116    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5117        // allow instant applications
5118        synchronized (mPackages) {
5119            return mServicesSystemSharedLibraryPackageName;
5120        }
5121    }
5122
5123    @Override
5124    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5125        // allow instant applications
5126        synchronized (mPackages) {
5127            return mSharedSystemSharedLibraryPackageName;
5128        }
5129    }
5130
5131    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5132        for (int i = userList.length - 1; i >= 0; --i) {
5133            final int userId = userList[i];
5134            // don't add instant app to the list of updates
5135            if (pkgSetting.getInstantApp(userId)) {
5136                continue;
5137            }
5138            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5139            if (changedPackages == null) {
5140                changedPackages = new SparseArray<>();
5141                mChangedPackages.put(userId, changedPackages);
5142            }
5143            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5144            if (sequenceNumbers == null) {
5145                sequenceNumbers = new HashMap<>();
5146                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5147            }
5148            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5149            if (sequenceNumber != null) {
5150                changedPackages.remove(sequenceNumber);
5151            }
5152            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5153            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5154        }
5155        mChangedPackagesSequenceNumber++;
5156    }
5157
5158    @Override
5159    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5160        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5161            return null;
5162        }
5163        synchronized (mPackages) {
5164            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5165                return null;
5166            }
5167            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5168            if (changedPackages == null) {
5169                return null;
5170            }
5171            final List<String> packageNames =
5172                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5173            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5174                final String packageName = changedPackages.get(i);
5175                if (packageName != null) {
5176                    packageNames.add(packageName);
5177                }
5178            }
5179            return packageNames.isEmpty()
5180                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5181        }
5182    }
5183
5184    @Override
5185    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5186        // allow instant applications
5187        ArrayList<FeatureInfo> res;
5188        synchronized (mAvailableFeatures) {
5189            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5190            res.addAll(mAvailableFeatures.values());
5191        }
5192        final FeatureInfo fi = new FeatureInfo();
5193        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5194                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5195        res.add(fi);
5196
5197        return new ParceledListSlice<>(res);
5198    }
5199
5200    @Override
5201    public boolean hasSystemFeature(String name, int version) {
5202        // allow instant applications
5203        synchronized (mAvailableFeatures) {
5204            final FeatureInfo feat = mAvailableFeatures.get(name);
5205            if (feat == null) {
5206                return false;
5207            } else {
5208                return feat.version >= version;
5209            }
5210        }
5211    }
5212
5213    @Override
5214    public int checkPermission(String permName, String pkgName, int userId) {
5215        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5216    }
5217
5218    @Override
5219    public int checkUidPermission(String permName, int uid) {
5220        return mPermissionManager.checkUidPermission(permName, uid, getCallingUid());
5221    }
5222
5223    @Override
5224    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5225        if (UserHandle.getCallingUserId() != userId) {
5226            mContext.enforceCallingPermission(
5227                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5228                    "isPermissionRevokedByPolicy for user " + userId);
5229        }
5230
5231        if (checkPermission(permission, packageName, userId)
5232                == PackageManager.PERMISSION_GRANTED) {
5233            return false;
5234        }
5235
5236        final int callingUid = Binder.getCallingUid();
5237        if (getInstantAppPackageName(callingUid) != null) {
5238            if (!isCallerSameApp(packageName, callingUid)) {
5239                return false;
5240            }
5241        } else {
5242            if (isInstantApp(packageName, userId)) {
5243                return false;
5244            }
5245        }
5246
5247        final long identity = Binder.clearCallingIdentity();
5248        try {
5249            final int flags = getPermissionFlags(permission, packageName, userId);
5250            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5251        } finally {
5252            Binder.restoreCallingIdentity(identity);
5253        }
5254    }
5255
5256    @Override
5257    public String getPermissionControllerPackageName() {
5258        synchronized (mPackages) {
5259            return mRequiredInstallerPackage;
5260        }
5261    }
5262
5263    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5264        return mPermissionManager.addDynamicPermission(
5265                info, async, getCallingUid(), new PermissionCallback() {
5266                    @Override
5267                    public void onPermissionChanged() {
5268                        if (!async) {
5269                            mSettings.writeLPr();
5270                        } else {
5271                            scheduleWriteSettingsLocked();
5272                        }
5273                    }
5274                });
5275    }
5276
5277    @Override
5278    public boolean addPermission(PermissionInfo info) {
5279        synchronized (mPackages) {
5280            return addDynamicPermission(info, false);
5281        }
5282    }
5283
5284    @Override
5285    public boolean addPermissionAsync(PermissionInfo info) {
5286        synchronized (mPackages) {
5287            return addDynamicPermission(info, true);
5288        }
5289    }
5290
5291    @Override
5292    public void removePermission(String permName) {
5293        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5294    }
5295
5296    @Override
5297    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5298        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5299                getCallingUid(), userId, mPermissionCallback);
5300    }
5301
5302    @Override
5303    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5304        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5305                getCallingUid(), userId, mPermissionCallback);
5306    }
5307
5308    @Override
5309    public void resetRuntimePermissions() {
5310        mContext.enforceCallingOrSelfPermission(
5311                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5312                "revokeRuntimePermission");
5313
5314        int callingUid = Binder.getCallingUid();
5315        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5316            mContext.enforceCallingOrSelfPermission(
5317                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5318                    "resetRuntimePermissions");
5319        }
5320
5321        synchronized (mPackages) {
5322            mPermissionManager.updateAllPermissions(
5323                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5324                    mPermissionCallback);
5325            for (int userId : UserManagerService.getInstance().getUserIds()) {
5326                final int packageCount = mPackages.size();
5327                for (int i = 0; i < packageCount; i++) {
5328                    PackageParser.Package pkg = mPackages.valueAt(i);
5329                    if (!(pkg.mExtras instanceof PackageSetting)) {
5330                        continue;
5331                    }
5332                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5333                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5334                }
5335            }
5336        }
5337    }
5338
5339    @Override
5340    public int getPermissionFlags(String permName, String packageName, int userId) {
5341        return mPermissionManager.getPermissionFlags(
5342                permName, packageName, getCallingUid(), userId);
5343    }
5344
5345    @Override
5346    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5347            int flagValues, int userId) {
5348        mPermissionManager.updatePermissionFlags(
5349                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5350                mPermissionCallback);
5351    }
5352
5353    /**
5354     * Update the permission flags for all packages and runtime permissions of a user in order
5355     * to allow device or profile owner to remove POLICY_FIXED.
5356     */
5357    @Override
5358    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5359        synchronized (mPackages) {
5360            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5361                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5362                    mPermissionCallback);
5363            if (changed) {
5364                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5365            }
5366        }
5367    }
5368
5369    @Override
5370    public boolean shouldShowRequestPermissionRationale(String permissionName,
5371            String packageName, int userId) {
5372        if (UserHandle.getCallingUserId() != userId) {
5373            mContext.enforceCallingPermission(
5374                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5375                    "canShowRequestPermissionRationale for user " + userId);
5376        }
5377
5378        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5379        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5380            return false;
5381        }
5382
5383        if (checkPermission(permissionName, packageName, userId)
5384                == PackageManager.PERMISSION_GRANTED) {
5385            return false;
5386        }
5387
5388        final int flags;
5389
5390        final long identity = Binder.clearCallingIdentity();
5391        try {
5392            flags = getPermissionFlags(permissionName,
5393                    packageName, userId);
5394        } finally {
5395            Binder.restoreCallingIdentity(identity);
5396        }
5397
5398        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5399                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5400                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5401
5402        if ((flags & fixedFlags) != 0) {
5403            return false;
5404        }
5405
5406        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5407    }
5408
5409    @Override
5410    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5411        mContext.enforceCallingOrSelfPermission(
5412                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5413                "addOnPermissionsChangeListener");
5414
5415        synchronized (mPackages) {
5416            mOnPermissionChangeListeners.addListenerLocked(listener);
5417        }
5418    }
5419
5420    @Override
5421    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5422        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5423            throw new SecurityException("Instant applications don't have access to this method");
5424        }
5425        synchronized (mPackages) {
5426            mOnPermissionChangeListeners.removeListenerLocked(listener);
5427        }
5428    }
5429
5430    @Override
5431    public boolean isProtectedBroadcast(String actionName) {
5432        // allow instant applications
5433        synchronized (mProtectedBroadcasts) {
5434            if (mProtectedBroadcasts.contains(actionName)) {
5435                return true;
5436            } else if (actionName != null) {
5437                // TODO: remove these terrible hacks
5438                if (actionName.startsWith("android.net.netmon.lingerExpired")
5439                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5440                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5441                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5442                    return true;
5443                }
5444            }
5445        }
5446        return false;
5447    }
5448
5449    @Override
5450    public int checkSignatures(String pkg1, String pkg2) {
5451        synchronized (mPackages) {
5452            final PackageParser.Package p1 = mPackages.get(pkg1);
5453            final PackageParser.Package p2 = mPackages.get(pkg2);
5454            if (p1 == null || p1.mExtras == null
5455                    || p2 == null || p2.mExtras == null) {
5456                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5457            }
5458            final int callingUid = Binder.getCallingUid();
5459            final int callingUserId = UserHandle.getUserId(callingUid);
5460            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5461            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5462            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5463                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5464                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5465            }
5466            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5467        }
5468    }
5469
5470    @Override
5471    public int checkUidSignatures(int uid1, int uid2) {
5472        final int callingUid = Binder.getCallingUid();
5473        final int callingUserId = UserHandle.getUserId(callingUid);
5474        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5475        // Map to base uids.
5476        uid1 = UserHandle.getAppId(uid1);
5477        uid2 = UserHandle.getAppId(uid2);
5478        // reader
5479        synchronized (mPackages) {
5480            Signature[] s1;
5481            Signature[] s2;
5482            Object obj = mSettings.getUserIdLPr(uid1);
5483            if (obj != null) {
5484                if (obj instanceof SharedUserSetting) {
5485                    if (isCallerInstantApp) {
5486                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5487                    }
5488                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5489                } else if (obj instanceof PackageSetting) {
5490                    final PackageSetting ps = (PackageSetting) obj;
5491                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5492                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5493                    }
5494                    s1 = ps.signatures.mSigningDetails.signatures;
5495                } else {
5496                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5497                }
5498            } else {
5499                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5500            }
5501            obj = mSettings.getUserIdLPr(uid2);
5502            if (obj != null) {
5503                if (obj instanceof SharedUserSetting) {
5504                    if (isCallerInstantApp) {
5505                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5506                    }
5507                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5508                } else if (obj instanceof PackageSetting) {
5509                    final PackageSetting ps = (PackageSetting) obj;
5510                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5511                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5512                    }
5513                    s2 = ps.signatures.mSigningDetails.signatures;
5514                } else {
5515                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5516                }
5517            } else {
5518                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5519            }
5520            return compareSignatures(s1, s2);
5521        }
5522    }
5523
5524    @Override
5525    public boolean hasSigningCertificate(
5526            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5527
5528        synchronized (mPackages) {
5529            final PackageParser.Package p = mPackages.get(packageName);
5530            if (p == null || p.mExtras == null) {
5531                return false;
5532            }
5533            final int callingUid = Binder.getCallingUid();
5534            final int callingUserId = UserHandle.getUserId(callingUid);
5535            final PackageSetting ps = (PackageSetting) p.mExtras;
5536            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5537                return false;
5538            }
5539            switch (type) {
5540                case CERT_INPUT_RAW_X509:
5541                    return p.mSigningDetails.hasCertificate(certificate);
5542                case CERT_INPUT_SHA256:
5543                    return p.mSigningDetails.hasSha256Certificate(certificate);
5544                default:
5545                    return false;
5546            }
5547        }
5548    }
5549
5550    @Override
5551    public boolean hasUidSigningCertificate(
5552            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5553        final int callingUid = Binder.getCallingUid();
5554        final int callingUserId = UserHandle.getUserId(callingUid);
5555        // Map to base uids.
5556        uid = UserHandle.getAppId(uid);
5557        // reader
5558        synchronized (mPackages) {
5559            final PackageParser.SigningDetails signingDetails;
5560            final Object obj = mSettings.getUserIdLPr(uid);
5561            if (obj != null) {
5562                if (obj instanceof SharedUserSetting) {
5563                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5564                    if (isCallerInstantApp) {
5565                        return false;
5566                    }
5567                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5568                } else if (obj instanceof PackageSetting) {
5569                    final PackageSetting ps = (PackageSetting) obj;
5570                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5571                        return false;
5572                    }
5573                    signingDetails = ps.signatures.mSigningDetails;
5574                } else {
5575                    return false;
5576                }
5577            } else {
5578                return false;
5579            }
5580            switch (type) {
5581                case CERT_INPUT_RAW_X509:
5582                    return signingDetails.hasCertificate(certificate);
5583                case CERT_INPUT_SHA256:
5584                    return signingDetails.hasSha256Certificate(certificate);
5585                default:
5586                    return false;
5587            }
5588        }
5589    }
5590
5591    /**
5592     * This method should typically only be used when granting or revoking
5593     * permissions, since the app may immediately restart after this call.
5594     * <p>
5595     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5596     * guard your work against the app being relaunched.
5597     */
5598    private void killUid(int appId, int userId, String reason) {
5599        final long identity = Binder.clearCallingIdentity();
5600        try {
5601            IActivityManager am = ActivityManager.getService();
5602            if (am != null) {
5603                try {
5604                    am.killUid(appId, userId, reason);
5605                } catch (RemoteException e) {
5606                    /* ignore - same process */
5607                }
5608            }
5609        } finally {
5610            Binder.restoreCallingIdentity(identity);
5611        }
5612    }
5613
5614    /**
5615     * If the database version for this type of package (internal storage or
5616     * external storage) is less than the version where package signatures
5617     * were updated, return true.
5618     */
5619    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5620        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5621        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5622    }
5623
5624    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5625        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5626        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5627    }
5628
5629    @Override
5630    public List<String> getAllPackages() {
5631        final int callingUid = Binder.getCallingUid();
5632        final int callingUserId = UserHandle.getUserId(callingUid);
5633        synchronized (mPackages) {
5634            if (canViewInstantApps(callingUid, callingUserId)) {
5635                return new ArrayList<String>(mPackages.keySet());
5636            }
5637            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5638            final List<String> result = new ArrayList<>();
5639            if (instantAppPkgName != null) {
5640                // caller is an instant application; filter unexposed applications
5641                for (PackageParser.Package pkg : mPackages.values()) {
5642                    if (!pkg.visibleToInstantApps) {
5643                        continue;
5644                    }
5645                    result.add(pkg.packageName);
5646                }
5647            } else {
5648                // caller is a normal application; filter instant applications
5649                for (PackageParser.Package pkg : mPackages.values()) {
5650                    final PackageSetting ps =
5651                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5652                    if (ps != null
5653                            && ps.getInstantApp(callingUserId)
5654                            && !mInstantAppRegistry.isInstantAccessGranted(
5655                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5656                        continue;
5657                    }
5658                    result.add(pkg.packageName);
5659                }
5660            }
5661            return result;
5662        }
5663    }
5664
5665    @Override
5666    public String[] getPackagesForUid(int uid) {
5667        final int callingUid = Binder.getCallingUid();
5668        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5669        final int userId = UserHandle.getUserId(uid);
5670        uid = UserHandle.getAppId(uid);
5671        // reader
5672        synchronized (mPackages) {
5673            Object obj = mSettings.getUserIdLPr(uid);
5674            if (obj instanceof SharedUserSetting) {
5675                if (isCallerInstantApp) {
5676                    return null;
5677                }
5678                final SharedUserSetting sus = (SharedUserSetting) obj;
5679                final int N = sus.packages.size();
5680                String[] res = new String[N];
5681                final Iterator<PackageSetting> it = sus.packages.iterator();
5682                int i = 0;
5683                while (it.hasNext()) {
5684                    PackageSetting ps = it.next();
5685                    if (ps.getInstalled(userId)) {
5686                        res[i++] = ps.name;
5687                    } else {
5688                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5689                    }
5690                }
5691                return res;
5692            } else if (obj instanceof PackageSetting) {
5693                final PackageSetting ps = (PackageSetting) obj;
5694                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5695                    return new String[]{ps.name};
5696                }
5697            }
5698        }
5699        return null;
5700    }
5701
5702    @Override
5703    public String getNameForUid(int uid) {
5704        final int callingUid = Binder.getCallingUid();
5705        if (getInstantAppPackageName(callingUid) != null) {
5706            return null;
5707        }
5708        synchronized (mPackages) {
5709            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5710            if (obj instanceof SharedUserSetting) {
5711                final SharedUserSetting sus = (SharedUserSetting) obj;
5712                return sus.name + ":" + sus.userId;
5713            } else if (obj instanceof PackageSetting) {
5714                final PackageSetting ps = (PackageSetting) obj;
5715                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5716                    return null;
5717                }
5718                return ps.name;
5719            }
5720            return null;
5721        }
5722    }
5723
5724    @Override
5725    public String[] getNamesForUids(int[] uids) {
5726        if (uids == null || uids.length == 0) {
5727            return null;
5728        }
5729        final int callingUid = Binder.getCallingUid();
5730        if (getInstantAppPackageName(callingUid) != null) {
5731            return null;
5732        }
5733        final String[] names = new String[uids.length];
5734        synchronized (mPackages) {
5735            for (int i = uids.length - 1; i >= 0; i--) {
5736                final int uid = uids[i];
5737                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5738                if (obj instanceof SharedUserSetting) {
5739                    final SharedUserSetting sus = (SharedUserSetting) obj;
5740                    names[i] = "shared:" + sus.name;
5741                } else if (obj instanceof PackageSetting) {
5742                    final PackageSetting ps = (PackageSetting) obj;
5743                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5744                        names[i] = null;
5745                    } else {
5746                        names[i] = ps.name;
5747                    }
5748                } else {
5749                    names[i] = null;
5750                }
5751            }
5752        }
5753        return names;
5754    }
5755
5756    @Override
5757    public int getUidForSharedUser(String sharedUserName) {
5758        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5759            return -1;
5760        }
5761        if (sharedUserName == null) {
5762            return -1;
5763        }
5764        // reader
5765        synchronized (mPackages) {
5766            SharedUserSetting suid;
5767            try {
5768                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5769                if (suid != null) {
5770                    return suid.userId;
5771                }
5772            } catch (PackageManagerException ignore) {
5773                // can't happen, but, still need to catch it
5774            }
5775            return -1;
5776        }
5777    }
5778
5779    @Override
5780    public int getFlagsForUid(int uid) {
5781        final int callingUid = Binder.getCallingUid();
5782        if (getInstantAppPackageName(callingUid) != null) {
5783            return 0;
5784        }
5785        synchronized (mPackages) {
5786            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5787            if (obj instanceof SharedUserSetting) {
5788                final SharedUserSetting sus = (SharedUserSetting) obj;
5789                return sus.pkgFlags;
5790            } else if (obj instanceof PackageSetting) {
5791                final PackageSetting ps = (PackageSetting) obj;
5792                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5793                    return 0;
5794                }
5795                return ps.pkgFlags;
5796            }
5797        }
5798        return 0;
5799    }
5800
5801    @Override
5802    public int getPrivateFlagsForUid(int uid) {
5803        final int callingUid = Binder.getCallingUid();
5804        if (getInstantAppPackageName(callingUid) != null) {
5805            return 0;
5806        }
5807        synchronized (mPackages) {
5808            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5809            if (obj instanceof SharedUserSetting) {
5810                final SharedUserSetting sus = (SharedUserSetting) obj;
5811                return sus.pkgPrivateFlags;
5812            } else if (obj instanceof PackageSetting) {
5813                final PackageSetting ps = (PackageSetting) obj;
5814                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5815                    return 0;
5816                }
5817                return ps.pkgPrivateFlags;
5818            }
5819        }
5820        return 0;
5821    }
5822
5823    @Override
5824    public boolean isUidPrivileged(int uid) {
5825        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5826            return false;
5827        }
5828        uid = UserHandle.getAppId(uid);
5829        // reader
5830        synchronized (mPackages) {
5831            Object obj = mSettings.getUserIdLPr(uid);
5832            if (obj instanceof SharedUserSetting) {
5833                final SharedUserSetting sus = (SharedUserSetting) obj;
5834                final Iterator<PackageSetting> it = sus.packages.iterator();
5835                while (it.hasNext()) {
5836                    if (it.next().isPrivileged()) {
5837                        return true;
5838                    }
5839                }
5840            } else if (obj instanceof PackageSetting) {
5841                final PackageSetting ps = (PackageSetting) obj;
5842                return ps.isPrivileged();
5843            }
5844        }
5845        return false;
5846    }
5847
5848    @Override
5849    public String[] getAppOpPermissionPackages(String permName) {
5850        return mPermissionManager.getAppOpPermissionPackages(permName);
5851    }
5852
5853    @Override
5854    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5855            int flags, int userId) {
5856        return resolveIntentInternal(
5857                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5858    }
5859
5860    /**
5861     * Normally instant apps can only be resolved when they're visible to the caller.
5862     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5863     * since we need to allow the system to start any installed application.
5864     */
5865    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5866            int flags, int userId, boolean resolveForStart) {
5867        try {
5868            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5869
5870            if (!sUserManager.exists(userId)) return null;
5871            final int callingUid = Binder.getCallingUid();
5872            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5873            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5874                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5875
5876            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5877            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5878                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5879            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5880
5881            final ResolveInfo bestChoice =
5882                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5883            return bestChoice;
5884        } finally {
5885            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5886        }
5887    }
5888
5889    @Override
5890    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5891        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5892            throw new SecurityException(
5893                    "findPersistentPreferredActivity can only be run by the system");
5894        }
5895        if (!sUserManager.exists(userId)) {
5896            return null;
5897        }
5898        final int callingUid = Binder.getCallingUid();
5899        intent = updateIntentForResolve(intent);
5900        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5901        final int flags = updateFlagsForResolve(
5902                0, userId, intent, callingUid, false /*includeInstantApps*/);
5903        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5904                userId);
5905        synchronized (mPackages) {
5906            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5907                    userId);
5908        }
5909    }
5910
5911    @Override
5912    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5913            IntentFilter filter, int match, ComponentName activity) {
5914        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5915            return;
5916        }
5917        final int userId = UserHandle.getCallingUserId();
5918        if (DEBUG_PREFERRED) {
5919            Log.v(TAG, "setLastChosenActivity intent=" + intent
5920                + " resolvedType=" + resolvedType
5921                + " flags=" + flags
5922                + " filter=" + filter
5923                + " match=" + match
5924                + " activity=" + activity);
5925            filter.dump(new PrintStreamPrinter(System.out), "    ");
5926        }
5927        intent.setComponent(null);
5928        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5929                userId);
5930        // Find any earlier preferred or last chosen entries and nuke them
5931        findPreferredActivity(intent, resolvedType,
5932                flags, query, 0, false, true, false, userId);
5933        // Add the new activity as the last chosen for this filter
5934        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5935                "Setting last chosen");
5936    }
5937
5938    @Override
5939    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5940        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5941            return null;
5942        }
5943        final int userId = UserHandle.getCallingUserId();
5944        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5945        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5946                userId);
5947        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5948                false, false, false, userId);
5949    }
5950
5951    /**
5952     * Returns whether or not instant apps have been disabled remotely.
5953     */
5954    private boolean isEphemeralDisabled() {
5955        return mEphemeralAppsDisabled;
5956    }
5957
5958    private boolean isInstantAppAllowed(
5959            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5960            boolean skipPackageCheck) {
5961        if (mInstantAppResolverConnection == null) {
5962            return false;
5963        }
5964        if (mInstantAppInstallerActivity == null) {
5965            return false;
5966        }
5967        if (intent.getComponent() != null) {
5968            return false;
5969        }
5970        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5971            return false;
5972        }
5973        if (!skipPackageCheck && intent.getPackage() != null) {
5974            return false;
5975        }
5976        if (!intent.isWebIntent()) {
5977            // for non web intents, we should not resolve externally if an app already exists to
5978            // handle it or if the caller didn't explicitly request it.
5979            if ((resolvedActivities != null && resolvedActivities.size() != 0)
5980                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
5981                return false;
5982            }
5983        } else if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
5984            return false;
5985        }
5986        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5987        // Or if there's already an ephemeral app installed that handles the action
5988        synchronized (mPackages) {
5989            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5990            for (int n = 0; n < count; n++) {
5991                final ResolveInfo info = resolvedActivities.get(n);
5992                final String packageName = info.activityInfo.packageName;
5993                final PackageSetting ps = mSettings.mPackages.get(packageName);
5994                if (ps != null) {
5995                    // only check domain verification status if the app is not a browser
5996                    if (!info.handleAllWebDataURI) {
5997                        // Try to get the status from User settings first
5998                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5999                        final int status = (int) (packedStatus >> 32);
6000                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6001                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6002                            if (DEBUG_INSTANT) {
6003                                Slog.v(TAG, "DENY instant app;"
6004                                    + " pkg: " + packageName + ", status: " + status);
6005                            }
6006                            return false;
6007                        }
6008                    }
6009                    if (ps.getInstantApp(userId)) {
6010                        if (DEBUG_INSTANT) {
6011                            Slog.v(TAG, "DENY instant app installed;"
6012                                    + " pkg: " + packageName);
6013                        }
6014                        return false;
6015                    }
6016                }
6017            }
6018        }
6019        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6020        return true;
6021    }
6022
6023    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6024            Intent origIntent, String resolvedType, String callingPackage,
6025            Bundle verificationBundle, int userId) {
6026        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6027                new InstantAppRequest(responseObj, origIntent, resolvedType,
6028                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6029        mHandler.sendMessage(msg);
6030    }
6031
6032    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6033            int flags, List<ResolveInfo> query, int userId) {
6034        if (query != null) {
6035            final int N = query.size();
6036            if (N == 1) {
6037                return query.get(0);
6038            } else if (N > 1) {
6039                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6040                // If there is more than one activity with the same priority,
6041                // then let the user decide between them.
6042                ResolveInfo r0 = query.get(0);
6043                ResolveInfo r1 = query.get(1);
6044                if (DEBUG_INTENT_MATCHING || debug) {
6045                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6046                            + r1.activityInfo.name + "=" + r1.priority);
6047                }
6048                // If the first activity has a higher priority, or a different
6049                // default, then it is always desirable to pick it.
6050                if (r0.priority != r1.priority
6051                        || r0.preferredOrder != r1.preferredOrder
6052                        || r0.isDefault != r1.isDefault) {
6053                    return query.get(0);
6054                }
6055                // If we have saved a preference for a preferred activity for
6056                // this Intent, use that.
6057                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6058                        flags, query, r0.priority, true, false, debug, userId);
6059                if (ri != null) {
6060                    return ri;
6061                }
6062                // If we have an ephemeral app, use it
6063                for (int i = 0; i < N; i++) {
6064                    ri = query.get(i);
6065                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6066                        final String packageName = ri.activityInfo.packageName;
6067                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6068                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6069                        final int status = (int)(packedStatus >> 32);
6070                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6071                            return ri;
6072                        }
6073                    }
6074                }
6075                ri = new ResolveInfo(mResolveInfo);
6076                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6077                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6078                // If all of the options come from the same package, show the application's
6079                // label and icon instead of the generic resolver's.
6080                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6081                // and then throw away the ResolveInfo itself, meaning that the caller loses
6082                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6083                // a fallback for this case; we only set the target package's resources on
6084                // the ResolveInfo, not the ActivityInfo.
6085                final String intentPackage = intent.getPackage();
6086                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6087                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6088                    ri.resolvePackageName = intentPackage;
6089                    if (userNeedsBadging(userId)) {
6090                        ri.noResourceId = true;
6091                    } else {
6092                        ri.icon = appi.icon;
6093                    }
6094                    ri.iconResourceId = appi.icon;
6095                    ri.labelRes = appi.labelRes;
6096                }
6097                ri.activityInfo.applicationInfo = new ApplicationInfo(
6098                        ri.activityInfo.applicationInfo);
6099                if (userId != 0) {
6100                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6101                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6102                }
6103                // Make sure that the resolver is displayable in car mode
6104                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6105                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6106                return ri;
6107            }
6108        }
6109        return null;
6110    }
6111
6112    /**
6113     * Return true if the given list is not empty and all of its contents have
6114     * an activityInfo with the given package name.
6115     */
6116    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6117        if (ArrayUtils.isEmpty(list)) {
6118            return false;
6119        }
6120        for (int i = 0, N = list.size(); i < N; i++) {
6121            final ResolveInfo ri = list.get(i);
6122            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6123            if (ai == null || !packageName.equals(ai.packageName)) {
6124                return false;
6125            }
6126        }
6127        return true;
6128    }
6129
6130    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6131            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6132        final int N = query.size();
6133        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6134                .get(userId);
6135        // Get the list of persistent preferred activities that handle the intent
6136        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6137        List<PersistentPreferredActivity> pprefs = ppir != null
6138                ? ppir.queryIntent(intent, resolvedType,
6139                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6140                        userId)
6141                : null;
6142        if (pprefs != null && pprefs.size() > 0) {
6143            final int M = pprefs.size();
6144            for (int i=0; i<M; i++) {
6145                final PersistentPreferredActivity ppa = pprefs.get(i);
6146                if (DEBUG_PREFERRED || debug) {
6147                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6148                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6149                            + "\n  component=" + ppa.mComponent);
6150                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6151                }
6152                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6153                        flags | MATCH_DISABLED_COMPONENTS, userId);
6154                if (DEBUG_PREFERRED || debug) {
6155                    Slog.v(TAG, "Found persistent preferred activity:");
6156                    if (ai != null) {
6157                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6158                    } else {
6159                        Slog.v(TAG, "  null");
6160                    }
6161                }
6162                if (ai == null) {
6163                    // This previously registered persistent preferred activity
6164                    // component is no longer known. Ignore it and do NOT remove it.
6165                    continue;
6166                }
6167                for (int j=0; j<N; j++) {
6168                    final ResolveInfo ri = query.get(j);
6169                    if (!ri.activityInfo.applicationInfo.packageName
6170                            .equals(ai.applicationInfo.packageName)) {
6171                        continue;
6172                    }
6173                    if (!ri.activityInfo.name.equals(ai.name)) {
6174                        continue;
6175                    }
6176                    //  Found a persistent preference that can handle the intent.
6177                    if (DEBUG_PREFERRED || debug) {
6178                        Slog.v(TAG, "Returning persistent preferred activity: " +
6179                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6180                    }
6181                    return ri;
6182                }
6183            }
6184        }
6185        return null;
6186    }
6187
6188    // TODO: handle preferred activities missing while user has amnesia
6189    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6190            List<ResolveInfo> query, int priority, boolean always,
6191            boolean removeMatches, boolean debug, int userId) {
6192        if (!sUserManager.exists(userId)) return null;
6193        final int callingUid = Binder.getCallingUid();
6194        flags = updateFlagsForResolve(
6195                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6196        intent = updateIntentForResolve(intent);
6197        // writer
6198        synchronized (mPackages) {
6199            // Try to find a matching persistent preferred activity.
6200            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6201                    debug, userId);
6202
6203            // If a persistent preferred activity matched, use it.
6204            if (pri != null) {
6205                return pri;
6206            }
6207
6208            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6209            // Get the list of preferred activities that handle the intent
6210            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6211            List<PreferredActivity> prefs = pir != null
6212                    ? pir.queryIntent(intent, resolvedType,
6213                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6214                            userId)
6215                    : null;
6216            if (prefs != null && prefs.size() > 0) {
6217                boolean changed = false;
6218                try {
6219                    // First figure out how good the original match set is.
6220                    // We will only allow preferred activities that came
6221                    // from the same match quality.
6222                    int match = 0;
6223
6224                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6225
6226                    final int N = query.size();
6227                    for (int j=0; j<N; j++) {
6228                        final ResolveInfo ri = query.get(j);
6229                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6230                                + ": 0x" + Integer.toHexString(match));
6231                        if (ri.match > match) {
6232                            match = ri.match;
6233                        }
6234                    }
6235
6236                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6237                            + Integer.toHexString(match));
6238
6239                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6240                    final int M = prefs.size();
6241                    for (int i=0; i<M; i++) {
6242                        final PreferredActivity pa = prefs.get(i);
6243                        if (DEBUG_PREFERRED || debug) {
6244                            Slog.v(TAG, "Checking PreferredActivity ds="
6245                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6246                                    + "\n  component=" + pa.mPref.mComponent);
6247                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6248                        }
6249                        if (pa.mPref.mMatch != match) {
6250                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6251                                    + Integer.toHexString(pa.mPref.mMatch));
6252                            continue;
6253                        }
6254                        // If it's not an "always" type preferred activity and that's what we're
6255                        // looking for, skip it.
6256                        if (always && !pa.mPref.mAlways) {
6257                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6258                            continue;
6259                        }
6260                        final ActivityInfo ai = getActivityInfo(
6261                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6262                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6263                                userId);
6264                        if (DEBUG_PREFERRED || debug) {
6265                            Slog.v(TAG, "Found preferred activity:");
6266                            if (ai != null) {
6267                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6268                            } else {
6269                                Slog.v(TAG, "  null");
6270                            }
6271                        }
6272                        if (ai == null) {
6273                            // This previously registered preferred activity
6274                            // component is no longer known.  Most likely an update
6275                            // to the app was installed and in the new version this
6276                            // component no longer exists.  Clean it up by removing
6277                            // it from the preferred activities list, and skip it.
6278                            Slog.w(TAG, "Removing dangling preferred activity: "
6279                                    + pa.mPref.mComponent);
6280                            pir.removeFilter(pa);
6281                            changed = true;
6282                            continue;
6283                        }
6284                        for (int j=0; j<N; j++) {
6285                            final ResolveInfo ri = query.get(j);
6286                            if (!ri.activityInfo.applicationInfo.packageName
6287                                    .equals(ai.applicationInfo.packageName)) {
6288                                continue;
6289                            }
6290                            if (!ri.activityInfo.name.equals(ai.name)) {
6291                                continue;
6292                            }
6293
6294                            if (removeMatches) {
6295                                pir.removeFilter(pa);
6296                                changed = true;
6297                                if (DEBUG_PREFERRED) {
6298                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6299                                }
6300                                break;
6301                            }
6302
6303                            // Okay we found a previously set preferred or last chosen app.
6304                            // If the result set is different from when this
6305                            // was created, and is not a subset of the preferred set, we need to
6306                            // clear it and re-ask the user their preference, if we're looking for
6307                            // an "always" type entry.
6308                            if (always && !pa.mPref.sameSet(query)) {
6309                                if (pa.mPref.isSuperset(query)) {
6310                                    // some components of the set are no longer present in
6311                                    // the query, but the preferred activity can still be reused
6312                                    if (DEBUG_PREFERRED) {
6313                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6314                                                + " still valid as only non-preferred components"
6315                                                + " were removed for " + intent + " type "
6316                                                + resolvedType);
6317                                    }
6318                                    // remove obsolete components and re-add the up-to-date filter
6319                                    PreferredActivity freshPa = new PreferredActivity(pa,
6320                                            pa.mPref.mMatch,
6321                                            pa.mPref.discardObsoleteComponents(query),
6322                                            pa.mPref.mComponent,
6323                                            pa.mPref.mAlways);
6324                                    pir.removeFilter(pa);
6325                                    pir.addFilter(freshPa);
6326                                    changed = true;
6327                                } else {
6328                                    Slog.i(TAG,
6329                                            "Result set changed, dropping preferred activity for "
6330                                                    + intent + " type " + resolvedType);
6331                                    if (DEBUG_PREFERRED) {
6332                                        Slog.v(TAG, "Removing preferred activity since set changed "
6333                                                + pa.mPref.mComponent);
6334                                    }
6335                                    pir.removeFilter(pa);
6336                                    // Re-add the filter as a "last chosen" entry (!always)
6337                                    PreferredActivity lastChosen = new PreferredActivity(
6338                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6339                                    pir.addFilter(lastChosen);
6340                                    changed = true;
6341                                    return null;
6342                                }
6343                            }
6344
6345                            // Yay! Either the set matched or we're looking for the last chosen
6346                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6347                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6348                            return ri;
6349                        }
6350                    }
6351                } finally {
6352                    if (changed) {
6353                        if (DEBUG_PREFERRED) {
6354                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6355                        }
6356                        scheduleWritePackageRestrictionsLocked(userId);
6357                    }
6358                }
6359            }
6360        }
6361        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6362        return null;
6363    }
6364
6365    /*
6366     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6367     */
6368    @Override
6369    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6370            int targetUserId) {
6371        mContext.enforceCallingOrSelfPermission(
6372                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6373        List<CrossProfileIntentFilter> matches =
6374                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6375        if (matches != null) {
6376            int size = matches.size();
6377            for (int i = 0; i < size; i++) {
6378                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6379            }
6380        }
6381        if (intent.hasWebURI()) {
6382            // cross-profile app linking works only towards the parent.
6383            final int callingUid = Binder.getCallingUid();
6384            final UserInfo parent = getProfileParent(sourceUserId);
6385            synchronized(mPackages) {
6386                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6387                        false /*includeInstantApps*/);
6388                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6389                        intent, resolvedType, flags, sourceUserId, parent.id);
6390                return xpDomainInfo != null;
6391            }
6392        }
6393        return false;
6394    }
6395
6396    private UserInfo getProfileParent(int userId) {
6397        final long identity = Binder.clearCallingIdentity();
6398        try {
6399            return sUserManager.getProfileParent(userId);
6400        } finally {
6401            Binder.restoreCallingIdentity(identity);
6402        }
6403    }
6404
6405    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6406            String resolvedType, int userId) {
6407        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6408        if (resolver != null) {
6409            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6410        }
6411        return null;
6412    }
6413
6414    @Override
6415    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6416            String resolvedType, int flags, int userId) {
6417        try {
6418            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6419
6420            return new ParceledListSlice<>(
6421                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6422        } finally {
6423            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6424        }
6425    }
6426
6427    /**
6428     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6429     * instant, returns {@code null}.
6430     */
6431    private String getInstantAppPackageName(int callingUid) {
6432        synchronized (mPackages) {
6433            // If the caller is an isolated app use the owner's uid for the lookup.
6434            if (Process.isIsolated(callingUid)) {
6435                callingUid = mIsolatedOwners.get(callingUid);
6436            }
6437            final int appId = UserHandle.getAppId(callingUid);
6438            final Object obj = mSettings.getUserIdLPr(appId);
6439            if (obj instanceof PackageSetting) {
6440                final PackageSetting ps = (PackageSetting) obj;
6441                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6442                return isInstantApp ? ps.pkg.packageName : null;
6443            }
6444        }
6445        return null;
6446    }
6447
6448    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6449            String resolvedType, int flags, int userId) {
6450        return queryIntentActivitiesInternal(
6451                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6452                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6453    }
6454
6455    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6456            String resolvedType, int flags, int filterCallingUid, int userId,
6457            boolean resolveForStart, boolean allowDynamicSplits) {
6458        if (!sUserManager.exists(userId)) return Collections.emptyList();
6459        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6460        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6461                false /* requireFullPermission */, false /* checkShell */,
6462                "query intent activities");
6463        final String pkgName = intent.getPackage();
6464        ComponentName comp = intent.getComponent();
6465        if (comp == null) {
6466            if (intent.getSelector() != null) {
6467                intent = intent.getSelector();
6468                comp = intent.getComponent();
6469            }
6470        }
6471
6472        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6473                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6474        if (comp != null) {
6475            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6476            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6477            if (ai != null) {
6478                // When specifying an explicit component, we prevent the activity from being
6479                // used when either 1) the calling package is normal and the activity is within
6480                // an ephemeral application or 2) the calling package is ephemeral and the
6481                // activity is not visible to ephemeral applications.
6482                final boolean matchInstantApp =
6483                        (flags & PackageManager.MATCH_INSTANT) != 0;
6484                final boolean matchVisibleToInstantAppOnly =
6485                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6486                final boolean matchExplicitlyVisibleOnly =
6487                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6488                final boolean isCallerInstantApp =
6489                        instantAppPkgName != null;
6490                final boolean isTargetSameInstantApp =
6491                        comp.getPackageName().equals(instantAppPkgName);
6492                final boolean isTargetInstantApp =
6493                        (ai.applicationInfo.privateFlags
6494                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6495                final boolean isTargetVisibleToInstantApp =
6496                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6497                final boolean isTargetExplicitlyVisibleToInstantApp =
6498                        isTargetVisibleToInstantApp
6499                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6500                final boolean isTargetHiddenFromInstantApp =
6501                        !isTargetVisibleToInstantApp
6502                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6503                final boolean blockResolution =
6504                        !isTargetSameInstantApp
6505                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6506                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6507                                        && isTargetHiddenFromInstantApp));
6508                if (!blockResolution) {
6509                    final ResolveInfo ri = new ResolveInfo();
6510                    ri.activityInfo = ai;
6511                    list.add(ri);
6512                }
6513            }
6514            return applyPostResolutionFilter(
6515                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6516        }
6517
6518        // reader
6519        boolean sortResult = false;
6520        boolean addEphemeral = false;
6521        List<ResolveInfo> result;
6522        final boolean ephemeralDisabled = isEphemeralDisabled();
6523        synchronized (mPackages) {
6524            if (pkgName == null) {
6525                List<CrossProfileIntentFilter> matchingFilters =
6526                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6527                // Check for results that need to skip the current profile.
6528                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6529                        resolvedType, flags, userId);
6530                if (xpResolveInfo != null) {
6531                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6532                    xpResult.add(xpResolveInfo);
6533                    return applyPostResolutionFilter(
6534                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6535                            allowDynamicSplits, filterCallingUid, userId);
6536                }
6537
6538                // Check for results in the current profile.
6539                result = filterIfNotSystemUser(mActivities.queryIntent(
6540                        intent, resolvedType, flags, userId), userId);
6541                addEphemeral = !ephemeralDisabled
6542                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6543                // Check for cross profile results.
6544                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6545                xpResolveInfo = queryCrossProfileIntents(
6546                        matchingFilters, intent, resolvedType, flags, userId,
6547                        hasNonNegativePriorityResult);
6548                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6549                    boolean isVisibleToUser = filterIfNotSystemUser(
6550                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6551                    if (isVisibleToUser) {
6552                        result.add(xpResolveInfo);
6553                        sortResult = true;
6554                    }
6555                }
6556                if (intent.hasWebURI()) {
6557                    CrossProfileDomainInfo xpDomainInfo = null;
6558                    final UserInfo parent = getProfileParent(userId);
6559                    if (parent != null) {
6560                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6561                                flags, userId, parent.id);
6562                    }
6563                    if (xpDomainInfo != null) {
6564                        if (xpResolveInfo != null) {
6565                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6566                            // in the result.
6567                            result.remove(xpResolveInfo);
6568                        }
6569                        if (result.size() == 0 && !addEphemeral) {
6570                            // No result in current profile, but found candidate in parent user.
6571                            // And we are not going to add emphemeral app, so we can return the
6572                            // result straight away.
6573                            result.add(xpDomainInfo.resolveInfo);
6574                            return applyPostResolutionFilter(result, instantAppPkgName,
6575                                    allowDynamicSplits, filterCallingUid, userId);
6576                        }
6577                    } else if (result.size() <= 1 && !addEphemeral) {
6578                        // No result in parent user and <= 1 result in current profile, and we
6579                        // are not going to add emphemeral app, so we can return the result without
6580                        // further processing.
6581                        return applyPostResolutionFilter(result, instantAppPkgName,
6582                                allowDynamicSplits, filterCallingUid, userId);
6583                    }
6584                    // We have more than one candidate (combining results from current and parent
6585                    // profile), so we need filtering and sorting.
6586                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6587                            intent, flags, result, xpDomainInfo, userId);
6588                    sortResult = true;
6589                }
6590            } else {
6591                final PackageParser.Package pkg = mPackages.get(pkgName);
6592                result = null;
6593                if (pkg != null) {
6594                    result = filterIfNotSystemUser(
6595                            mActivities.queryIntentForPackage(
6596                                    intent, resolvedType, flags, pkg.activities, userId),
6597                            userId);
6598                }
6599                if (result == null || result.size() == 0) {
6600                    // the caller wants to resolve for a particular package; however, there
6601                    // were no installed results, so, try to find an ephemeral result
6602                    addEphemeral = !ephemeralDisabled
6603                            && isInstantAppAllowed(
6604                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6605                    if (result == null) {
6606                        result = new ArrayList<>();
6607                    }
6608                }
6609            }
6610        }
6611        if (addEphemeral) {
6612            result = maybeAddInstantAppInstaller(
6613                    result, intent, resolvedType, flags, userId, resolveForStart);
6614        }
6615        if (sortResult) {
6616            Collections.sort(result, mResolvePrioritySorter);
6617        }
6618        return applyPostResolutionFilter(
6619                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6620    }
6621
6622    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6623            String resolvedType, int flags, int userId, boolean resolveForStart) {
6624        // first, check to see if we've got an instant app already installed
6625        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6626        ResolveInfo localInstantApp = null;
6627        boolean blockResolution = false;
6628        if (!alreadyResolvedLocally) {
6629            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6630                    flags
6631                        | PackageManager.GET_RESOLVED_FILTER
6632                        | PackageManager.MATCH_INSTANT
6633                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6634                    userId);
6635            for (int i = instantApps.size() - 1; i >= 0; --i) {
6636                final ResolveInfo info = instantApps.get(i);
6637                final String packageName = info.activityInfo.packageName;
6638                final PackageSetting ps = mSettings.mPackages.get(packageName);
6639                if (ps.getInstantApp(userId)) {
6640                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6641                    final int status = (int)(packedStatus >> 32);
6642                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6643                        // there's a local instant application installed, but, the user has
6644                        // chosen to never use it; skip resolution and don't acknowledge
6645                        // an instant application is even available
6646                        if (DEBUG_INSTANT) {
6647                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6648                        }
6649                        blockResolution = true;
6650                        break;
6651                    } else {
6652                        // we have a locally installed instant application; skip resolution
6653                        // but acknowledge there's an instant application available
6654                        if (DEBUG_INSTANT) {
6655                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6656                        }
6657                        localInstantApp = info;
6658                        break;
6659                    }
6660                }
6661            }
6662        }
6663        // no app installed, let's see if one's available
6664        AuxiliaryResolveInfo auxiliaryResponse = null;
6665        if (!blockResolution) {
6666            if (localInstantApp == null) {
6667                // we don't have an instant app locally, resolve externally
6668                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6669                final InstantAppRequest requestObject = new InstantAppRequest(
6670                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6671                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6672                        resolveForStart);
6673                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6674                        mInstantAppResolverConnection, requestObject);
6675                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6676            } else {
6677                // we have an instant application locally, but, we can't admit that since
6678                // callers shouldn't be able to determine prior browsing. create a dummy
6679                // auxiliary response so the downstream code behaves as if there's an
6680                // instant application available externally. when it comes time to start
6681                // the instant application, we'll do the right thing.
6682                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6683                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6684                                        ai.packageName, ai.versionCode, null /* splitName */);
6685            }
6686        }
6687        if (intent.isWebIntent() && auxiliaryResponse == null) {
6688            return result;
6689        }
6690        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6691        if (ps == null) {
6692            return result;
6693        }
6694        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6695        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6696                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6697        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6698                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6699        // add a non-generic filter
6700        ephemeralInstaller.filter = new IntentFilter();
6701        if (intent.getAction() != null) {
6702            ephemeralInstaller.filter.addAction(intent.getAction());
6703        }
6704        if (intent.getData() != null && intent.getData().getPath() != null) {
6705            ephemeralInstaller.filter.addDataPath(
6706                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6707        }
6708        ephemeralInstaller.isInstantAppAvailable = true;
6709        // make sure this resolver is the default
6710        ephemeralInstaller.isDefault = true;
6711        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6712        if (DEBUG_INSTANT) {
6713            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6714        }
6715
6716        result.add(ephemeralInstaller);
6717        return result;
6718    }
6719
6720    private static class CrossProfileDomainInfo {
6721        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6722        ResolveInfo resolveInfo;
6723        /* Best domain verification status of the activities found in the other profile */
6724        int bestDomainVerificationStatus;
6725    }
6726
6727    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6728            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6729        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6730                sourceUserId)) {
6731            return null;
6732        }
6733        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6734                resolvedType, flags, parentUserId);
6735
6736        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6737            return null;
6738        }
6739        CrossProfileDomainInfo result = null;
6740        int size = resultTargetUser.size();
6741        for (int i = 0; i < size; i++) {
6742            ResolveInfo riTargetUser = resultTargetUser.get(i);
6743            // Intent filter verification is only for filters that specify a host. So don't return
6744            // those that handle all web uris.
6745            if (riTargetUser.handleAllWebDataURI) {
6746                continue;
6747            }
6748            String packageName = riTargetUser.activityInfo.packageName;
6749            PackageSetting ps = mSettings.mPackages.get(packageName);
6750            if (ps == null) {
6751                continue;
6752            }
6753            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6754            int status = (int)(verificationState >> 32);
6755            if (result == null) {
6756                result = new CrossProfileDomainInfo();
6757                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6758                        sourceUserId, parentUserId);
6759                result.bestDomainVerificationStatus = status;
6760            } else {
6761                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6762                        result.bestDomainVerificationStatus);
6763            }
6764        }
6765        // Don't consider matches with status NEVER across profiles.
6766        if (result != null && result.bestDomainVerificationStatus
6767                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6768            return null;
6769        }
6770        return result;
6771    }
6772
6773    /**
6774     * Verification statuses are ordered from the worse to the best, except for
6775     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6776     */
6777    private int bestDomainVerificationStatus(int status1, int status2) {
6778        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6779            return status2;
6780        }
6781        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6782            return status1;
6783        }
6784        return (int) MathUtils.max(status1, status2);
6785    }
6786
6787    private boolean isUserEnabled(int userId) {
6788        long callingId = Binder.clearCallingIdentity();
6789        try {
6790            UserInfo userInfo = sUserManager.getUserInfo(userId);
6791            return userInfo != null && userInfo.isEnabled();
6792        } finally {
6793            Binder.restoreCallingIdentity(callingId);
6794        }
6795    }
6796
6797    /**
6798     * Filter out activities with systemUserOnly flag set, when current user is not System.
6799     *
6800     * @return filtered list
6801     */
6802    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6803        if (userId == UserHandle.USER_SYSTEM) {
6804            return resolveInfos;
6805        }
6806        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6807            ResolveInfo info = resolveInfos.get(i);
6808            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6809                resolveInfos.remove(i);
6810            }
6811        }
6812        return resolveInfos;
6813    }
6814
6815    /**
6816     * Filters out ephemeral activities.
6817     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6818     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6819     *
6820     * @param resolveInfos The pre-filtered list of resolved activities
6821     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6822     *          is performed.
6823     * @return A filtered list of resolved activities.
6824     */
6825    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6826            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
6827        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6828            final ResolveInfo info = resolveInfos.get(i);
6829            // allow activities that are defined in the provided package
6830            if (allowDynamicSplits
6831                    && info.activityInfo != null
6832                    && info.activityInfo.splitName != null
6833                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6834                            info.activityInfo.splitName)) {
6835                if (mInstantAppInstallerActivity == null) {
6836                    if (DEBUG_INSTALL) {
6837                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6838                    }
6839                    resolveInfos.remove(i);
6840                    continue;
6841                }
6842                // requested activity is defined in a split that hasn't been installed yet.
6843                // add the installer to the resolve list
6844                if (DEBUG_INSTALL) {
6845                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6846                }
6847                final ResolveInfo installerInfo = new ResolveInfo(
6848                        mInstantAppInstallerInfo);
6849                final ComponentName installFailureActivity = findInstallFailureActivity(
6850                        info.activityInfo.packageName,  filterCallingUid, userId);
6851                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6852                        installFailureActivity,
6853                        info.activityInfo.packageName,
6854                        info.activityInfo.applicationInfo.versionCode,
6855                        info.activityInfo.splitName);
6856                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6857                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6858                // add a non-generic filter
6859                installerInfo.filter = new IntentFilter();
6860
6861                // This resolve info may appear in the chooser UI, so let us make it
6862                // look as the one it replaces as far as the user is concerned which
6863                // requires loading the correct label and icon for the resolve info.
6864                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6865                installerInfo.labelRes = info.resolveLabelResId();
6866                installerInfo.icon = info.resolveIconResId();
6867
6868                // propagate priority/preferred order/default
6869                installerInfo.priority = info.priority;
6870                installerInfo.preferredOrder = info.preferredOrder;
6871                installerInfo.isDefault = info.isDefault;
6872                installerInfo.isInstantAppAvailable = true;
6873                resolveInfos.set(i, installerInfo);
6874                continue;
6875            }
6876            // caller is a full app, don't need to apply any other filtering
6877            if (ephemeralPkgName == null) {
6878                continue;
6879            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6880                // caller is same app; don't need to apply any other filtering
6881                continue;
6882            }
6883            // allow activities that have been explicitly exposed to ephemeral apps
6884            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6885            if (!isEphemeralApp
6886                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6887                continue;
6888            }
6889            resolveInfos.remove(i);
6890        }
6891        return resolveInfos;
6892    }
6893
6894    /**
6895     * Returns the activity component that can handle install failures.
6896     * <p>By default, the instant application installer handles failures. However, an
6897     * application may want to handle failures on its own. Applications do this by
6898     * creating an activity with an intent filter that handles the action
6899     * {@link Intent#ACTION_INSTALL_FAILURE}.
6900     */
6901    private @Nullable ComponentName findInstallFailureActivity(
6902            String packageName, int filterCallingUid, int userId) {
6903        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6904        failureActivityIntent.setPackage(packageName);
6905        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6906        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6907                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6908                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6909        final int NR = result.size();
6910        if (NR > 0) {
6911            for (int i = 0; i < NR; i++) {
6912                final ResolveInfo info = result.get(i);
6913                if (info.activityInfo.splitName != null) {
6914                    continue;
6915                }
6916                return new ComponentName(packageName, info.activityInfo.name);
6917            }
6918        }
6919        return null;
6920    }
6921
6922    /**
6923     * @param resolveInfos list of resolve infos in descending priority order
6924     * @return if the list contains a resolve info with non-negative priority
6925     */
6926    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6927        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6928    }
6929
6930    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6931            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6932            int userId) {
6933        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6934
6935        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6936            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6937                    candidates.size());
6938        }
6939
6940        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6941        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6942        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6943        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6944        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6945        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6946
6947        synchronized (mPackages) {
6948            final int count = candidates.size();
6949            // First, try to use linked apps. Partition the candidates into four lists:
6950            // one for the final results, one for the "do not use ever", one for "undefined status"
6951            // and finally one for "browser app type".
6952            for (int n=0; n<count; n++) {
6953                ResolveInfo info = candidates.get(n);
6954                String packageName = info.activityInfo.packageName;
6955                PackageSetting ps = mSettings.mPackages.get(packageName);
6956                if (ps != null) {
6957                    // Add to the special match all list (Browser use case)
6958                    if (info.handleAllWebDataURI) {
6959                        matchAllList.add(info);
6960                        continue;
6961                    }
6962                    // Try to get the status from User settings first
6963                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6964                    int status = (int)(packedStatus >> 32);
6965                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6966                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6967                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6968                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6969                                    + " : linkgen=" + linkGeneration);
6970                        }
6971                        // Use link-enabled generation as preferredOrder, i.e.
6972                        // prefer newly-enabled over earlier-enabled.
6973                        info.preferredOrder = linkGeneration;
6974                        alwaysList.add(info);
6975                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6976                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6977                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6978                        }
6979                        neverList.add(info);
6980                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6981                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6982                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6983                        }
6984                        alwaysAskList.add(info);
6985                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6986                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6987                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6988                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6989                        }
6990                        undefinedList.add(info);
6991                    }
6992                }
6993            }
6994
6995            // We'll want to include browser possibilities in a few cases
6996            boolean includeBrowser = false;
6997
6998            // First try to add the "always" resolution(s) for the current user, if any
6999            if (alwaysList.size() > 0) {
7000                result.addAll(alwaysList);
7001            } else {
7002                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7003                result.addAll(undefinedList);
7004                // Maybe add one for the other profile.
7005                if (xpDomainInfo != null && (
7006                        xpDomainInfo.bestDomainVerificationStatus
7007                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7008                    result.add(xpDomainInfo.resolveInfo);
7009                }
7010                includeBrowser = true;
7011            }
7012
7013            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7014            // If there were 'always' entries their preferred order has been set, so we also
7015            // back that off to make the alternatives equivalent
7016            if (alwaysAskList.size() > 0) {
7017                for (ResolveInfo i : result) {
7018                    i.preferredOrder = 0;
7019                }
7020                result.addAll(alwaysAskList);
7021                includeBrowser = true;
7022            }
7023
7024            if (includeBrowser) {
7025                // Also add browsers (all of them or only the default one)
7026                if (DEBUG_DOMAIN_VERIFICATION) {
7027                    Slog.v(TAG, "   ...including browsers in candidate set");
7028                }
7029                if ((matchFlags & MATCH_ALL) != 0) {
7030                    result.addAll(matchAllList);
7031                } else {
7032                    // Browser/generic handling case.  If there's a default browser, go straight
7033                    // to that (but only if there is no other higher-priority match).
7034                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7035                    int maxMatchPrio = 0;
7036                    ResolveInfo defaultBrowserMatch = null;
7037                    final int numCandidates = matchAllList.size();
7038                    for (int n = 0; n < numCandidates; n++) {
7039                        ResolveInfo info = matchAllList.get(n);
7040                        // track the highest overall match priority...
7041                        if (info.priority > maxMatchPrio) {
7042                            maxMatchPrio = info.priority;
7043                        }
7044                        // ...and the highest-priority default browser match
7045                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7046                            if (defaultBrowserMatch == null
7047                                    || (defaultBrowserMatch.priority < info.priority)) {
7048                                if (debug) {
7049                                    Slog.v(TAG, "Considering default browser match " + info);
7050                                }
7051                                defaultBrowserMatch = info;
7052                            }
7053                        }
7054                    }
7055                    if (defaultBrowserMatch != null
7056                            && defaultBrowserMatch.priority >= maxMatchPrio
7057                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7058                    {
7059                        if (debug) {
7060                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7061                        }
7062                        result.add(defaultBrowserMatch);
7063                    } else {
7064                        result.addAll(matchAllList);
7065                    }
7066                }
7067
7068                // If there is nothing selected, add all candidates and remove the ones that the user
7069                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7070                if (result.size() == 0) {
7071                    result.addAll(candidates);
7072                    result.removeAll(neverList);
7073                }
7074            }
7075        }
7076        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7077            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7078                    result.size());
7079            for (ResolveInfo info : result) {
7080                Slog.v(TAG, "  + " + info.activityInfo);
7081            }
7082        }
7083        return result;
7084    }
7085
7086    // Returns a packed value as a long:
7087    //
7088    // high 'int'-sized word: link status: undefined/ask/never/always.
7089    // low 'int'-sized word: relative priority among 'always' results.
7090    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7091        long result = ps.getDomainVerificationStatusForUser(userId);
7092        // if none available, get the master status
7093        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7094            if (ps.getIntentFilterVerificationInfo() != null) {
7095                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7096            }
7097        }
7098        return result;
7099    }
7100
7101    private ResolveInfo querySkipCurrentProfileIntents(
7102            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7103            int flags, int sourceUserId) {
7104        if (matchingFilters != null) {
7105            int size = matchingFilters.size();
7106            for (int i = 0; i < size; i ++) {
7107                CrossProfileIntentFilter filter = matchingFilters.get(i);
7108                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7109                    // Checking if there are activities in the target user that can handle the
7110                    // intent.
7111                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7112                            resolvedType, flags, sourceUserId);
7113                    if (resolveInfo != null) {
7114                        return resolveInfo;
7115                    }
7116                }
7117            }
7118        }
7119        return null;
7120    }
7121
7122    // Return matching ResolveInfo in target user if any.
7123    private ResolveInfo queryCrossProfileIntents(
7124            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7125            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7126        if (matchingFilters != null) {
7127            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7128            // match the same intent. For performance reasons, it is better not to
7129            // run queryIntent twice for the same userId
7130            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7131            int size = matchingFilters.size();
7132            for (int i = 0; i < size; i++) {
7133                CrossProfileIntentFilter filter = matchingFilters.get(i);
7134                int targetUserId = filter.getTargetUserId();
7135                boolean skipCurrentProfile =
7136                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7137                boolean skipCurrentProfileIfNoMatchFound =
7138                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7139                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7140                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7141                    // Checking if there are activities in the target user that can handle the
7142                    // intent.
7143                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7144                            resolvedType, flags, sourceUserId);
7145                    if (resolveInfo != null) return resolveInfo;
7146                    alreadyTriedUserIds.put(targetUserId, true);
7147                }
7148            }
7149        }
7150        return null;
7151    }
7152
7153    /**
7154     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7155     * will forward the intent to the filter's target user.
7156     * Otherwise, returns null.
7157     */
7158    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7159            String resolvedType, int flags, int sourceUserId) {
7160        int targetUserId = filter.getTargetUserId();
7161        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7162                resolvedType, flags, targetUserId);
7163        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7164            // If all the matches in the target profile are suspended, return null.
7165            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7166                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7167                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7168                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7169                            targetUserId);
7170                }
7171            }
7172        }
7173        return null;
7174    }
7175
7176    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7177            int sourceUserId, int targetUserId) {
7178        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7179        long ident = Binder.clearCallingIdentity();
7180        boolean targetIsProfile;
7181        try {
7182            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7183        } finally {
7184            Binder.restoreCallingIdentity(ident);
7185        }
7186        String className;
7187        if (targetIsProfile) {
7188            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7189        } else {
7190            className = FORWARD_INTENT_TO_PARENT;
7191        }
7192        ComponentName forwardingActivityComponentName = new ComponentName(
7193                mAndroidApplication.packageName, className);
7194        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7195                sourceUserId);
7196        if (!targetIsProfile) {
7197            forwardingActivityInfo.showUserIcon = targetUserId;
7198            forwardingResolveInfo.noResourceId = true;
7199        }
7200        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7201        forwardingResolveInfo.priority = 0;
7202        forwardingResolveInfo.preferredOrder = 0;
7203        forwardingResolveInfo.match = 0;
7204        forwardingResolveInfo.isDefault = true;
7205        forwardingResolveInfo.filter = filter;
7206        forwardingResolveInfo.targetUserId = targetUserId;
7207        return forwardingResolveInfo;
7208    }
7209
7210    @Override
7211    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7212            Intent[] specifics, String[] specificTypes, Intent intent,
7213            String resolvedType, int flags, int userId) {
7214        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7215                specificTypes, intent, resolvedType, flags, userId));
7216    }
7217
7218    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7219            Intent[] specifics, String[] specificTypes, Intent intent,
7220            String resolvedType, int flags, int userId) {
7221        if (!sUserManager.exists(userId)) return Collections.emptyList();
7222        final int callingUid = Binder.getCallingUid();
7223        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7224                false /*includeInstantApps*/);
7225        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7226                false /*requireFullPermission*/, false /*checkShell*/,
7227                "query intent activity options");
7228        final String resultsAction = intent.getAction();
7229
7230        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7231                | PackageManager.GET_RESOLVED_FILTER, userId);
7232
7233        if (DEBUG_INTENT_MATCHING) {
7234            Log.v(TAG, "Query " + intent + ": " + results);
7235        }
7236
7237        int specificsPos = 0;
7238        int N;
7239
7240        // todo: note that the algorithm used here is O(N^2).  This
7241        // isn't a problem in our current environment, but if we start running
7242        // into situations where we have more than 5 or 10 matches then this
7243        // should probably be changed to something smarter...
7244
7245        // First we go through and resolve each of the specific items
7246        // that were supplied, taking care of removing any corresponding
7247        // duplicate items in the generic resolve list.
7248        if (specifics != null) {
7249            for (int i=0; i<specifics.length; i++) {
7250                final Intent sintent = specifics[i];
7251                if (sintent == null) {
7252                    continue;
7253                }
7254
7255                if (DEBUG_INTENT_MATCHING) {
7256                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7257                }
7258
7259                String action = sintent.getAction();
7260                if (resultsAction != null && resultsAction.equals(action)) {
7261                    // If this action was explicitly requested, then don't
7262                    // remove things that have it.
7263                    action = null;
7264                }
7265
7266                ResolveInfo ri = null;
7267                ActivityInfo ai = null;
7268
7269                ComponentName comp = sintent.getComponent();
7270                if (comp == null) {
7271                    ri = resolveIntent(
7272                        sintent,
7273                        specificTypes != null ? specificTypes[i] : null,
7274                            flags, userId);
7275                    if (ri == null) {
7276                        continue;
7277                    }
7278                    if (ri == mResolveInfo) {
7279                        // ACK!  Must do something better with this.
7280                    }
7281                    ai = ri.activityInfo;
7282                    comp = new ComponentName(ai.applicationInfo.packageName,
7283                            ai.name);
7284                } else {
7285                    ai = getActivityInfo(comp, flags, userId);
7286                    if (ai == null) {
7287                        continue;
7288                    }
7289                }
7290
7291                // Look for any generic query activities that are duplicates
7292                // of this specific one, and remove them from the results.
7293                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7294                N = results.size();
7295                int j;
7296                for (j=specificsPos; j<N; j++) {
7297                    ResolveInfo sri = results.get(j);
7298                    if ((sri.activityInfo.name.equals(comp.getClassName())
7299                            && sri.activityInfo.applicationInfo.packageName.equals(
7300                                    comp.getPackageName()))
7301                        || (action != null && sri.filter.matchAction(action))) {
7302                        results.remove(j);
7303                        if (DEBUG_INTENT_MATCHING) Log.v(
7304                            TAG, "Removing duplicate item from " + j
7305                            + " due to specific " + specificsPos);
7306                        if (ri == null) {
7307                            ri = sri;
7308                        }
7309                        j--;
7310                        N--;
7311                    }
7312                }
7313
7314                // Add this specific item to its proper place.
7315                if (ri == null) {
7316                    ri = new ResolveInfo();
7317                    ri.activityInfo = ai;
7318                }
7319                results.add(specificsPos, ri);
7320                ri.specificIndex = i;
7321                specificsPos++;
7322            }
7323        }
7324
7325        // Now we go through the remaining generic results and remove any
7326        // duplicate actions that are found here.
7327        N = results.size();
7328        for (int i=specificsPos; i<N-1; i++) {
7329            final ResolveInfo rii = results.get(i);
7330            if (rii.filter == null) {
7331                continue;
7332            }
7333
7334            // Iterate over all of the actions of this result's intent
7335            // filter...  typically this should be just one.
7336            final Iterator<String> it = rii.filter.actionsIterator();
7337            if (it == null) {
7338                continue;
7339            }
7340            while (it.hasNext()) {
7341                final String action = it.next();
7342                if (resultsAction != null && resultsAction.equals(action)) {
7343                    // If this action was explicitly requested, then don't
7344                    // remove things that have it.
7345                    continue;
7346                }
7347                for (int j=i+1; j<N; j++) {
7348                    final ResolveInfo rij = results.get(j);
7349                    if (rij.filter != null && rij.filter.hasAction(action)) {
7350                        results.remove(j);
7351                        if (DEBUG_INTENT_MATCHING) Log.v(
7352                            TAG, "Removing duplicate item from " + j
7353                            + " due to action " + action + " at " + i);
7354                        j--;
7355                        N--;
7356                    }
7357                }
7358            }
7359
7360            // If the caller didn't request filter information, drop it now
7361            // so we don't have to marshall/unmarshall it.
7362            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7363                rii.filter = null;
7364            }
7365        }
7366
7367        // Filter out the caller activity if so requested.
7368        if (caller != null) {
7369            N = results.size();
7370            for (int i=0; i<N; i++) {
7371                ActivityInfo ainfo = results.get(i).activityInfo;
7372                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7373                        && caller.getClassName().equals(ainfo.name)) {
7374                    results.remove(i);
7375                    break;
7376                }
7377            }
7378        }
7379
7380        // If the caller didn't request filter information,
7381        // drop them now so we don't have to
7382        // marshall/unmarshall it.
7383        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7384            N = results.size();
7385            for (int i=0; i<N; i++) {
7386                results.get(i).filter = null;
7387            }
7388        }
7389
7390        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7391        return results;
7392    }
7393
7394    @Override
7395    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7396            String resolvedType, int flags, int userId) {
7397        return new ParceledListSlice<>(
7398                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7399                        false /*allowDynamicSplits*/));
7400    }
7401
7402    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7403            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7404        if (!sUserManager.exists(userId)) return Collections.emptyList();
7405        final int callingUid = Binder.getCallingUid();
7406        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7407                false /*requireFullPermission*/, false /*checkShell*/,
7408                "query intent receivers");
7409        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7410        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7411                false /*includeInstantApps*/);
7412        ComponentName comp = intent.getComponent();
7413        if (comp == null) {
7414            if (intent.getSelector() != null) {
7415                intent = intent.getSelector();
7416                comp = intent.getComponent();
7417            }
7418        }
7419        if (comp != null) {
7420            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7421            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7422            if (ai != null) {
7423                // When specifying an explicit component, we prevent the activity from being
7424                // used when either 1) the calling package is normal and the activity is within
7425                // an instant application or 2) the calling package is ephemeral and the
7426                // activity is not visible to instant applications.
7427                final boolean matchInstantApp =
7428                        (flags & PackageManager.MATCH_INSTANT) != 0;
7429                final boolean matchVisibleToInstantAppOnly =
7430                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7431                final boolean matchExplicitlyVisibleOnly =
7432                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7433                final boolean isCallerInstantApp =
7434                        instantAppPkgName != null;
7435                final boolean isTargetSameInstantApp =
7436                        comp.getPackageName().equals(instantAppPkgName);
7437                final boolean isTargetInstantApp =
7438                        (ai.applicationInfo.privateFlags
7439                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7440                final boolean isTargetVisibleToInstantApp =
7441                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7442                final boolean isTargetExplicitlyVisibleToInstantApp =
7443                        isTargetVisibleToInstantApp
7444                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7445                final boolean isTargetHiddenFromInstantApp =
7446                        !isTargetVisibleToInstantApp
7447                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7448                final boolean blockResolution =
7449                        !isTargetSameInstantApp
7450                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7451                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7452                                        && isTargetHiddenFromInstantApp));
7453                if (!blockResolution) {
7454                    ResolveInfo ri = new ResolveInfo();
7455                    ri.activityInfo = ai;
7456                    list.add(ri);
7457                }
7458            }
7459            return applyPostResolutionFilter(
7460                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7461        }
7462
7463        // reader
7464        synchronized (mPackages) {
7465            String pkgName = intent.getPackage();
7466            if (pkgName == null) {
7467                final List<ResolveInfo> result =
7468                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7469                return applyPostResolutionFilter(
7470                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7471            }
7472            final PackageParser.Package pkg = mPackages.get(pkgName);
7473            if (pkg != null) {
7474                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7475                        intent, resolvedType, flags, pkg.receivers, userId);
7476                return applyPostResolutionFilter(
7477                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7478            }
7479            return Collections.emptyList();
7480        }
7481    }
7482
7483    @Override
7484    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7485        final int callingUid = Binder.getCallingUid();
7486        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7487    }
7488
7489    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7490            int userId, int callingUid) {
7491        if (!sUserManager.exists(userId)) return null;
7492        flags = updateFlagsForResolve(
7493                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7494        List<ResolveInfo> query = queryIntentServicesInternal(
7495                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7496        if (query != null) {
7497            if (query.size() >= 1) {
7498                // If there is more than one service with the same priority,
7499                // just arbitrarily pick the first one.
7500                return query.get(0);
7501            }
7502        }
7503        return null;
7504    }
7505
7506    @Override
7507    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7508            String resolvedType, int flags, int userId) {
7509        final int callingUid = Binder.getCallingUid();
7510        return new ParceledListSlice<>(queryIntentServicesInternal(
7511                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7512    }
7513
7514    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7515            String resolvedType, int flags, int userId, int callingUid,
7516            boolean includeInstantApps) {
7517        if (!sUserManager.exists(userId)) return Collections.emptyList();
7518        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7519                false /*requireFullPermission*/, false /*checkShell*/,
7520                "query intent receivers");
7521        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7522        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7523        ComponentName comp = intent.getComponent();
7524        if (comp == null) {
7525            if (intent.getSelector() != null) {
7526                intent = intent.getSelector();
7527                comp = intent.getComponent();
7528            }
7529        }
7530        if (comp != null) {
7531            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7532            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7533            if (si != null) {
7534                // When specifying an explicit component, we prevent the service from being
7535                // used when either 1) the service is in an instant application and the
7536                // caller is not the same instant application or 2) the calling package is
7537                // ephemeral and the activity is not visible to ephemeral applications.
7538                final boolean matchInstantApp =
7539                        (flags & PackageManager.MATCH_INSTANT) != 0;
7540                final boolean matchVisibleToInstantAppOnly =
7541                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7542                final boolean isCallerInstantApp =
7543                        instantAppPkgName != null;
7544                final boolean isTargetSameInstantApp =
7545                        comp.getPackageName().equals(instantAppPkgName);
7546                final boolean isTargetInstantApp =
7547                        (si.applicationInfo.privateFlags
7548                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7549                final boolean isTargetHiddenFromInstantApp =
7550                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7551                final boolean blockResolution =
7552                        !isTargetSameInstantApp
7553                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7554                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7555                                        && isTargetHiddenFromInstantApp));
7556                if (!blockResolution) {
7557                    final ResolveInfo ri = new ResolveInfo();
7558                    ri.serviceInfo = si;
7559                    list.add(ri);
7560                }
7561            }
7562            return list;
7563        }
7564
7565        // reader
7566        synchronized (mPackages) {
7567            String pkgName = intent.getPackage();
7568            if (pkgName == null) {
7569                return applyPostServiceResolutionFilter(
7570                        mServices.queryIntent(intent, resolvedType, flags, userId),
7571                        instantAppPkgName);
7572            }
7573            final PackageParser.Package pkg = mPackages.get(pkgName);
7574            if (pkg != null) {
7575                return applyPostServiceResolutionFilter(
7576                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7577                                userId),
7578                        instantAppPkgName);
7579            }
7580            return Collections.emptyList();
7581        }
7582    }
7583
7584    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7585            String instantAppPkgName) {
7586        if (instantAppPkgName == null) {
7587            return resolveInfos;
7588        }
7589        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7590            final ResolveInfo info = resolveInfos.get(i);
7591            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7592            // allow services that are defined in the provided package
7593            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7594                if (info.serviceInfo.splitName != null
7595                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7596                                info.serviceInfo.splitName)) {
7597                    // requested service is defined in a split that hasn't been installed yet.
7598                    // add the installer to the resolve list
7599                    if (DEBUG_INSTANT) {
7600                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7601                    }
7602                    final ResolveInfo installerInfo = new ResolveInfo(
7603                            mInstantAppInstallerInfo);
7604                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7605                            null /* installFailureActivity */,
7606                            info.serviceInfo.packageName,
7607                            info.serviceInfo.applicationInfo.versionCode,
7608                            info.serviceInfo.splitName);
7609                    // make sure this resolver is the default
7610                    installerInfo.isDefault = true;
7611                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7612                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7613                    // add a non-generic filter
7614                    installerInfo.filter = new IntentFilter();
7615                    // load resources from the correct package
7616                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7617                    resolveInfos.set(i, installerInfo);
7618                }
7619                continue;
7620            }
7621            // allow services that have been explicitly exposed to ephemeral apps
7622            if (!isEphemeralApp
7623                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7624                continue;
7625            }
7626            resolveInfos.remove(i);
7627        }
7628        return resolveInfos;
7629    }
7630
7631    @Override
7632    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7633            String resolvedType, int flags, int userId) {
7634        return new ParceledListSlice<>(
7635                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7636    }
7637
7638    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7639            Intent intent, String resolvedType, int flags, int userId) {
7640        if (!sUserManager.exists(userId)) return Collections.emptyList();
7641        final int callingUid = Binder.getCallingUid();
7642        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7643        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7644                false /*includeInstantApps*/);
7645        ComponentName comp = intent.getComponent();
7646        if (comp == null) {
7647            if (intent.getSelector() != null) {
7648                intent = intent.getSelector();
7649                comp = intent.getComponent();
7650            }
7651        }
7652        if (comp != null) {
7653            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7654            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7655            if (pi != null) {
7656                // When specifying an explicit component, we prevent the provider from being
7657                // used when either 1) the provider is in an instant application and the
7658                // caller is not the same instant application or 2) the calling package is an
7659                // instant application and the provider is not visible to instant applications.
7660                final boolean matchInstantApp =
7661                        (flags & PackageManager.MATCH_INSTANT) != 0;
7662                final boolean matchVisibleToInstantAppOnly =
7663                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7664                final boolean isCallerInstantApp =
7665                        instantAppPkgName != null;
7666                final boolean isTargetSameInstantApp =
7667                        comp.getPackageName().equals(instantAppPkgName);
7668                final boolean isTargetInstantApp =
7669                        (pi.applicationInfo.privateFlags
7670                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7671                final boolean isTargetHiddenFromInstantApp =
7672                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7673                final boolean blockResolution =
7674                        !isTargetSameInstantApp
7675                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7676                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7677                                        && isTargetHiddenFromInstantApp));
7678                if (!blockResolution) {
7679                    final ResolveInfo ri = new ResolveInfo();
7680                    ri.providerInfo = pi;
7681                    list.add(ri);
7682                }
7683            }
7684            return list;
7685        }
7686
7687        // reader
7688        synchronized (mPackages) {
7689            String pkgName = intent.getPackage();
7690            if (pkgName == null) {
7691                return applyPostContentProviderResolutionFilter(
7692                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7693                        instantAppPkgName);
7694            }
7695            final PackageParser.Package pkg = mPackages.get(pkgName);
7696            if (pkg != null) {
7697                return applyPostContentProviderResolutionFilter(
7698                        mProviders.queryIntentForPackage(
7699                        intent, resolvedType, flags, pkg.providers, userId),
7700                        instantAppPkgName);
7701            }
7702            return Collections.emptyList();
7703        }
7704    }
7705
7706    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7707            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7708        if (instantAppPkgName == null) {
7709            return resolveInfos;
7710        }
7711        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7712            final ResolveInfo info = resolveInfos.get(i);
7713            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7714            // allow providers that are defined in the provided package
7715            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7716                if (info.providerInfo.splitName != null
7717                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7718                                info.providerInfo.splitName)) {
7719                    // requested provider is defined in a split that hasn't been installed yet.
7720                    // add the installer to the resolve list
7721                    if (DEBUG_INSTANT) {
7722                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7723                    }
7724                    final ResolveInfo installerInfo = new ResolveInfo(
7725                            mInstantAppInstallerInfo);
7726                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7727                            null /*failureActivity*/,
7728                            info.providerInfo.packageName,
7729                            info.providerInfo.applicationInfo.versionCode,
7730                            info.providerInfo.splitName);
7731                    // make sure this resolver is the default
7732                    installerInfo.isDefault = true;
7733                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7734                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7735                    // add a non-generic filter
7736                    installerInfo.filter = new IntentFilter();
7737                    // load resources from the correct package
7738                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7739                    resolveInfos.set(i, installerInfo);
7740                }
7741                continue;
7742            }
7743            // allow providers that have been explicitly exposed to instant applications
7744            if (!isEphemeralApp
7745                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7746                continue;
7747            }
7748            resolveInfos.remove(i);
7749        }
7750        return resolveInfos;
7751    }
7752
7753    @Override
7754    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7755        final int callingUid = Binder.getCallingUid();
7756        if (getInstantAppPackageName(callingUid) != null) {
7757            return ParceledListSlice.emptyList();
7758        }
7759        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7760        flags = updateFlagsForPackage(flags, userId, null);
7761        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7762        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7763                true /* requireFullPermission */, false /* checkShell */,
7764                "get installed packages");
7765
7766        // writer
7767        synchronized (mPackages) {
7768            ArrayList<PackageInfo> list;
7769            if (listUninstalled) {
7770                list = new ArrayList<>(mSettings.mPackages.size());
7771                for (PackageSetting ps : mSettings.mPackages.values()) {
7772                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7773                        continue;
7774                    }
7775                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7776                        continue;
7777                    }
7778                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7779                    if (pi != null) {
7780                        list.add(pi);
7781                    }
7782                }
7783            } else {
7784                list = new ArrayList<>(mPackages.size());
7785                for (PackageParser.Package p : mPackages.values()) {
7786                    final PackageSetting ps = (PackageSetting) p.mExtras;
7787                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7788                        continue;
7789                    }
7790                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7791                        continue;
7792                    }
7793                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7794                            p.mExtras, flags, userId);
7795                    if (pi != null) {
7796                        list.add(pi);
7797                    }
7798                }
7799            }
7800
7801            return new ParceledListSlice<>(list);
7802        }
7803    }
7804
7805    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7806            String[] permissions, boolean[] tmp, int flags, int userId) {
7807        int numMatch = 0;
7808        final PermissionsState permissionsState = ps.getPermissionsState();
7809        for (int i=0; i<permissions.length; i++) {
7810            final String permission = permissions[i];
7811            if (permissionsState.hasPermission(permission, userId)) {
7812                tmp[i] = true;
7813                numMatch++;
7814            } else {
7815                tmp[i] = false;
7816            }
7817        }
7818        if (numMatch == 0) {
7819            return;
7820        }
7821        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7822
7823        // The above might return null in cases of uninstalled apps or install-state
7824        // skew across users/profiles.
7825        if (pi != null) {
7826            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7827                if (numMatch == permissions.length) {
7828                    pi.requestedPermissions = permissions;
7829                } else {
7830                    pi.requestedPermissions = new String[numMatch];
7831                    numMatch = 0;
7832                    for (int i=0; i<permissions.length; i++) {
7833                        if (tmp[i]) {
7834                            pi.requestedPermissions[numMatch] = permissions[i];
7835                            numMatch++;
7836                        }
7837                    }
7838                }
7839            }
7840            list.add(pi);
7841        }
7842    }
7843
7844    @Override
7845    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7846            String[] permissions, int flags, int userId) {
7847        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7848        flags = updateFlagsForPackage(flags, userId, permissions);
7849        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7850                true /* requireFullPermission */, false /* checkShell */,
7851                "get packages holding permissions");
7852        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7853
7854        // writer
7855        synchronized (mPackages) {
7856            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7857            boolean[] tmpBools = new boolean[permissions.length];
7858            if (listUninstalled) {
7859                for (PackageSetting ps : mSettings.mPackages.values()) {
7860                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7861                            userId);
7862                }
7863            } else {
7864                for (PackageParser.Package pkg : mPackages.values()) {
7865                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7866                    if (ps != null) {
7867                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7868                                userId);
7869                    }
7870                }
7871            }
7872
7873            return new ParceledListSlice<PackageInfo>(list);
7874        }
7875    }
7876
7877    @Override
7878    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7879        final int callingUid = Binder.getCallingUid();
7880        if (getInstantAppPackageName(callingUid) != null) {
7881            return ParceledListSlice.emptyList();
7882        }
7883        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7884        flags = updateFlagsForApplication(flags, userId, null);
7885        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7886
7887        // writer
7888        synchronized (mPackages) {
7889            ArrayList<ApplicationInfo> list;
7890            if (listUninstalled) {
7891                list = new ArrayList<>(mSettings.mPackages.size());
7892                for (PackageSetting ps : mSettings.mPackages.values()) {
7893                    ApplicationInfo ai;
7894                    int effectiveFlags = flags;
7895                    if (ps.isSystem()) {
7896                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7897                    }
7898                    if (ps.pkg != null) {
7899                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7900                            continue;
7901                        }
7902                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7903                            continue;
7904                        }
7905                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7906                                ps.readUserState(userId), userId);
7907                        if (ai != null) {
7908                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7909                        }
7910                    } else {
7911                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7912                        // and already converts to externally visible package name
7913                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7914                                callingUid, effectiveFlags, userId);
7915                    }
7916                    if (ai != null) {
7917                        list.add(ai);
7918                    }
7919                }
7920            } else {
7921                list = new ArrayList<>(mPackages.size());
7922                for (PackageParser.Package p : mPackages.values()) {
7923                    if (p.mExtras != null) {
7924                        PackageSetting ps = (PackageSetting) p.mExtras;
7925                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7926                            continue;
7927                        }
7928                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7929                            continue;
7930                        }
7931                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7932                                ps.readUserState(userId), userId);
7933                        if (ai != null) {
7934                            ai.packageName = resolveExternalPackageNameLPr(p);
7935                            list.add(ai);
7936                        }
7937                    }
7938                }
7939            }
7940
7941            return new ParceledListSlice<>(list);
7942        }
7943    }
7944
7945    @Override
7946    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7947        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7948            return null;
7949        }
7950        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7951            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7952                    "getEphemeralApplications");
7953        }
7954        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7955                true /* requireFullPermission */, false /* checkShell */,
7956                "getEphemeralApplications");
7957        synchronized (mPackages) {
7958            List<InstantAppInfo> instantApps = mInstantAppRegistry
7959                    .getInstantAppsLPr(userId);
7960            if (instantApps != null) {
7961                return new ParceledListSlice<>(instantApps);
7962            }
7963        }
7964        return null;
7965    }
7966
7967    @Override
7968    public boolean isInstantApp(String packageName, int userId) {
7969        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7970                true /* requireFullPermission */, false /* checkShell */,
7971                "isInstantApp");
7972        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7973            return false;
7974        }
7975
7976        synchronized (mPackages) {
7977            int callingUid = Binder.getCallingUid();
7978            if (Process.isIsolated(callingUid)) {
7979                callingUid = mIsolatedOwners.get(callingUid);
7980            }
7981            final PackageSetting ps = mSettings.mPackages.get(packageName);
7982            PackageParser.Package pkg = mPackages.get(packageName);
7983            final boolean returnAllowed =
7984                    ps != null
7985                    && (isCallerSameApp(packageName, callingUid)
7986                            || canViewInstantApps(callingUid, userId)
7987                            || mInstantAppRegistry.isInstantAccessGranted(
7988                                    userId, UserHandle.getAppId(callingUid), ps.appId));
7989            if (returnAllowed) {
7990                return ps.getInstantApp(userId);
7991            }
7992        }
7993        return false;
7994    }
7995
7996    @Override
7997    public byte[] getInstantAppCookie(String packageName, int userId) {
7998        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7999            return null;
8000        }
8001
8002        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8003                true /* requireFullPermission */, false /* checkShell */,
8004                "getInstantAppCookie");
8005        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8006            return null;
8007        }
8008        synchronized (mPackages) {
8009            return mInstantAppRegistry.getInstantAppCookieLPw(
8010                    packageName, userId);
8011        }
8012    }
8013
8014    @Override
8015    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8016        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8017            return true;
8018        }
8019
8020        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8021                true /* requireFullPermission */, true /* checkShell */,
8022                "setInstantAppCookie");
8023        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8024            return false;
8025        }
8026        synchronized (mPackages) {
8027            return mInstantAppRegistry.setInstantAppCookieLPw(
8028                    packageName, cookie, userId);
8029        }
8030    }
8031
8032    @Override
8033    public Bitmap getInstantAppIcon(String packageName, int userId) {
8034        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8035            return null;
8036        }
8037
8038        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8039            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8040                    "getInstantAppIcon");
8041        }
8042        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8043                true /* requireFullPermission */, false /* checkShell */,
8044                "getInstantAppIcon");
8045
8046        synchronized (mPackages) {
8047            return mInstantAppRegistry.getInstantAppIconLPw(
8048                    packageName, userId);
8049        }
8050    }
8051
8052    private boolean isCallerSameApp(String packageName, int uid) {
8053        PackageParser.Package pkg = mPackages.get(packageName);
8054        return pkg != null
8055                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8056    }
8057
8058    @Override
8059    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8060        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8061            return ParceledListSlice.emptyList();
8062        }
8063        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8064    }
8065
8066    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8067        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8068
8069        // reader
8070        synchronized (mPackages) {
8071            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8072            final int userId = UserHandle.getCallingUserId();
8073            while (i.hasNext()) {
8074                final PackageParser.Package p = i.next();
8075                if (p.applicationInfo == null) continue;
8076
8077                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8078                        && !p.applicationInfo.isDirectBootAware();
8079                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8080                        && p.applicationInfo.isDirectBootAware();
8081
8082                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8083                        && (!mSafeMode || isSystemApp(p))
8084                        && (matchesUnaware || matchesAware)) {
8085                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8086                    if (ps != null) {
8087                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8088                                ps.readUserState(userId), userId);
8089                        if (ai != null) {
8090                            finalList.add(ai);
8091                        }
8092                    }
8093                }
8094            }
8095        }
8096
8097        return finalList;
8098    }
8099
8100    @Override
8101    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8102        return resolveContentProviderInternal(name, flags, userId);
8103    }
8104
8105    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8106        if (!sUserManager.exists(userId)) return null;
8107        flags = updateFlagsForComponent(flags, userId, name);
8108        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8109        // reader
8110        synchronized (mPackages) {
8111            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8112            PackageSetting ps = provider != null
8113                    ? mSettings.mPackages.get(provider.owner.packageName)
8114                    : null;
8115            if (ps != null) {
8116                final boolean isInstantApp = ps.getInstantApp(userId);
8117                // normal application; filter out instant application provider
8118                if (instantAppPkgName == null && isInstantApp) {
8119                    return null;
8120                }
8121                // instant application; filter out other instant applications
8122                if (instantAppPkgName != null
8123                        && isInstantApp
8124                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8125                    return null;
8126                }
8127                // instant application; filter out non-exposed provider
8128                if (instantAppPkgName != null
8129                        && !isInstantApp
8130                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8131                    return null;
8132                }
8133                // provider not enabled
8134                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8135                    return null;
8136                }
8137                return PackageParser.generateProviderInfo(
8138                        provider, flags, ps.readUserState(userId), userId);
8139            }
8140            return null;
8141        }
8142    }
8143
8144    /**
8145     * @deprecated
8146     */
8147    @Deprecated
8148    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8149        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8150            return;
8151        }
8152        // reader
8153        synchronized (mPackages) {
8154            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8155                    .entrySet().iterator();
8156            final int userId = UserHandle.getCallingUserId();
8157            while (i.hasNext()) {
8158                Map.Entry<String, PackageParser.Provider> entry = i.next();
8159                PackageParser.Provider p = entry.getValue();
8160                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8161
8162                if (ps != null && p.syncable
8163                        && (!mSafeMode || (p.info.applicationInfo.flags
8164                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8165                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8166                            ps.readUserState(userId), userId);
8167                    if (info != null) {
8168                        outNames.add(entry.getKey());
8169                        outInfo.add(info);
8170                    }
8171                }
8172            }
8173        }
8174    }
8175
8176    @Override
8177    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8178            int uid, int flags, String metaDataKey) {
8179        final int callingUid = Binder.getCallingUid();
8180        final int userId = processName != null ? UserHandle.getUserId(uid)
8181                : UserHandle.getCallingUserId();
8182        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8183        flags = updateFlagsForComponent(flags, userId, processName);
8184        ArrayList<ProviderInfo> finalList = null;
8185        // reader
8186        synchronized (mPackages) {
8187            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8188            while (i.hasNext()) {
8189                final PackageParser.Provider p = i.next();
8190                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8191                if (ps != null && p.info.authority != null
8192                        && (processName == null
8193                                || (p.info.processName.equals(processName)
8194                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8195                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8196
8197                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8198                    // parameter.
8199                    if (metaDataKey != null
8200                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8201                        continue;
8202                    }
8203                    final ComponentName component =
8204                            new ComponentName(p.info.packageName, p.info.name);
8205                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8206                        continue;
8207                    }
8208                    if (finalList == null) {
8209                        finalList = new ArrayList<ProviderInfo>(3);
8210                    }
8211                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8212                            ps.readUserState(userId), userId);
8213                    if (info != null) {
8214                        finalList.add(info);
8215                    }
8216                }
8217            }
8218        }
8219
8220        if (finalList != null) {
8221            Collections.sort(finalList, mProviderInitOrderSorter);
8222            return new ParceledListSlice<ProviderInfo>(finalList);
8223        }
8224
8225        return ParceledListSlice.emptyList();
8226    }
8227
8228    @Override
8229    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8230        // reader
8231        synchronized (mPackages) {
8232            final int callingUid = Binder.getCallingUid();
8233            final int callingUserId = UserHandle.getUserId(callingUid);
8234            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8235            if (ps == null) return null;
8236            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8237                return null;
8238            }
8239            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8240            return PackageParser.generateInstrumentationInfo(i, flags);
8241        }
8242    }
8243
8244    @Override
8245    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8246            String targetPackage, int flags) {
8247        final int callingUid = Binder.getCallingUid();
8248        final int callingUserId = UserHandle.getUserId(callingUid);
8249        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8250        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8251            return ParceledListSlice.emptyList();
8252        }
8253        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8254    }
8255
8256    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8257            int flags) {
8258        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8259
8260        // reader
8261        synchronized (mPackages) {
8262            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8263            while (i.hasNext()) {
8264                final PackageParser.Instrumentation p = i.next();
8265                if (targetPackage == null
8266                        || targetPackage.equals(p.info.targetPackage)) {
8267                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8268                            flags);
8269                    if (ii != null) {
8270                        finalList.add(ii);
8271                    }
8272                }
8273            }
8274        }
8275
8276        return finalList;
8277    }
8278
8279    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8280        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8281        try {
8282            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8283        } finally {
8284            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8285        }
8286    }
8287
8288    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8289        final File[] files = scanDir.listFiles();
8290        if (ArrayUtils.isEmpty(files)) {
8291            Log.d(TAG, "No files in app dir " + scanDir);
8292            return;
8293        }
8294
8295        if (DEBUG_PACKAGE_SCANNING) {
8296            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8297                    + " flags=0x" + Integer.toHexString(parseFlags));
8298        }
8299        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8300                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8301                mParallelPackageParserCallback)) {
8302            // Submit files for parsing in parallel
8303            int fileCount = 0;
8304            for (File file : files) {
8305                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8306                        && !PackageInstallerService.isStageName(file.getName());
8307                if (!isPackage) {
8308                    // Ignore entries which are not packages
8309                    continue;
8310                }
8311                parallelPackageParser.submit(file, parseFlags);
8312                fileCount++;
8313            }
8314
8315            // Process results one by one
8316            for (; fileCount > 0; fileCount--) {
8317                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8318                Throwable throwable = parseResult.throwable;
8319                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8320
8321                if (throwable == null) {
8322                    // TODO(toddke): move lower in the scan chain
8323                    // Static shared libraries have synthetic package names
8324                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8325                        renameStaticSharedLibraryPackage(parseResult.pkg);
8326                    }
8327                    try {
8328                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8329                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8330                                    currentTime, null);
8331                        }
8332                    } catch (PackageManagerException e) {
8333                        errorCode = e.error;
8334                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8335                    }
8336                } else if (throwable instanceof PackageParser.PackageParserException) {
8337                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8338                            throwable;
8339                    errorCode = e.error;
8340                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8341                } else {
8342                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8343                            + parseResult.scanFile, throwable);
8344                }
8345
8346                // Delete invalid userdata apps
8347                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8348                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8349                    logCriticalInfo(Log.WARN,
8350                            "Deleting invalid package at " + parseResult.scanFile);
8351                    removeCodePathLI(parseResult.scanFile);
8352                }
8353            }
8354        }
8355    }
8356
8357    public static void reportSettingsProblem(int priority, String msg) {
8358        logCriticalInfo(priority, msg);
8359    }
8360
8361    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8362            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8363        // When upgrading from pre-N MR1, verify the package time stamp using the package
8364        // directory and not the APK file.
8365        final long lastModifiedTime = mIsPreNMR1Upgrade
8366                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8367        if (ps != null && !forceCollect
8368                && ps.codePathString.equals(pkg.codePath)
8369                && ps.timeStamp == lastModifiedTime
8370                && !isCompatSignatureUpdateNeeded(pkg)
8371                && !isRecoverSignatureUpdateNeeded(pkg)) {
8372            if (ps.signatures.mSigningDetails.signatures != null
8373                    && ps.signatures.mSigningDetails.signatures.length != 0
8374                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8375                            != SignatureSchemeVersion.UNKNOWN) {
8376                // Optimization: reuse the existing cached signing data
8377                // if the package appears to be unchanged.
8378                pkg.mSigningDetails =
8379                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8380                return;
8381            }
8382
8383            Slog.w(TAG, "PackageSetting for " + ps.name
8384                    + " is missing signatures.  Collecting certs again to recover them.");
8385        } else {
8386            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8387                    (forceCollect ? " (forced)" : ""));
8388        }
8389
8390        try {
8391            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8392            PackageParser.collectCertificates(pkg, skipVerify);
8393        } catch (PackageParserException e) {
8394            throw PackageManagerException.from(e);
8395        } finally {
8396            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8397        }
8398    }
8399
8400    /**
8401     *  Traces a package scan.
8402     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8403     */
8404    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8405            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8406        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8407        try {
8408            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8409        } finally {
8410            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8411        }
8412    }
8413
8414    /**
8415     *  Scans a package and returns the newly parsed package.
8416     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8417     */
8418    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8419            long currentTime, UserHandle user) throws PackageManagerException {
8420        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8421        PackageParser pp = new PackageParser();
8422        pp.setSeparateProcesses(mSeparateProcesses);
8423        pp.setOnlyCoreApps(mOnlyCore);
8424        pp.setDisplayMetrics(mMetrics);
8425        pp.setCallback(mPackageParserCallback);
8426
8427        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8428        final PackageParser.Package pkg;
8429        try {
8430            pkg = pp.parsePackage(scanFile, parseFlags);
8431        } catch (PackageParserException e) {
8432            throw PackageManagerException.from(e);
8433        } finally {
8434            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8435        }
8436
8437        // Static shared libraries have synthetic package names
8438        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8439            renameStaticSharedLibraryPackage(pkg);
8440        }
8441
8442        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8443    }
8444
8445    /**
8446     *  Scans a package and returns the newly parsed package.
8447     *  @throws PackageManagerException on a parse error.
8448     */
8449    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8450            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8451            @Nullable UserHandle user)
8452                    throws PackageManagerException {
8453        // If the package has children and this is the first dive in the function
8454        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8455        // packages (parent and children) would be successfully scanned before the
8456        // actual scan since scanning mutates internal state and we want to atomically
8457        // install the package and its children.
8458        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8459            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8460                scanFlags |= SCAN_CHECK_ONLY;
8461            }
8462        } else {
8463            scanFlags &= ~SCAN_CHECK_ONLY;
8464        }
8465
8466        // Scan the parent
8467        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8468                scanFlags, currentTime, user);
8469
8470        // Scan the children
8471        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8472        for (int i = 0; i < childCount; i++) {
8473            PackageParser.Package childPackage = pkg.childPackages.get(i);
8474            addForInitLI(childPackage, parseFlags, scanFlags,
8475                    currentTime, user);
8476        }
8477
8478
8479        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8480            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8481        }
8482
8483        return scannedPkg;
8484    }
8485
8486    /**
8487     * Returns if full apk verification can be skipped for the whole package, including the splits.
8488     */
8489    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8490        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8491            return false;
8492        }
8493        // TODO: Allow base and splits to be verified individually.
8494        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8495            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8496                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8497                    return false;
8498                }
8499            }
8500        }
8501        return true;
8502    }
8503
8504    /**
8505     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8506     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8507     * match one in a trusted source, and should be done separately.
8508     */
8509    private boolean canSkipFullApkVerification(String apkPath) {
8510        byte[] rootHashObserved = null;
8511        try {
8512            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8513            if (rootHashObserved == null) {
8514                return false;  // APK does not contain Merkle tree root hash.
8515            }
8516            synchronized (mInstallLock) {
8517                // Returns whether the observed root hash matches what kernel has.
8518                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8519                return true;
8520            }
8521        } catch (InstallerException | IOException | DigestException |
8522                NoSuchAlgorithmException e) {
8523            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8524        }
8525        return false;
8526    }
8527
8528    /**
8529     * Adds a new package to the internal data structures during platform initialization.
8530     * <p>After adding, the package is known to the system and available for querying.
8531     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8532     * etc...], additional checks are performed. Basic verification [such as ensuring
8533     * matching signatures, checking version codes, etc...] occurs if the package is
8534     * identical to a previously known package. If the package fails a signature check,
8535     * the version installed on /data will be removed. If the version of the new package
8536     * is less than or equal than the version on /data, it will be ignored.
8537     * <p>Regardless of the package location, the results are applied to the internal
8538     * structures and the package is made available to the rest of the system.
8539     * <p>NOTE: The return value should be removed. It's the passed in package object.
8540     */
8541    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8542            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8543            @Nullable UserHandle user)
8544                    throws PackageManagerException {
8545        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8546        final String renamedPkgName;
8547        final PackageSetting disabledPkgSetting;
8548        final boolean isSystemPkgUpdated;
8549        final boolean pkgAlreadyExists;
8550        PackageSetting pkgSetting;
8551
8552        // NOTE: installPackageLI() has the same code to setup the package's
8553        // application info. This probably should be done lower in the call
8554        // stack [such as scanPackageOnly()]. However, we verify the application
8555        // info prior to that [in scanPackageNew()] and thus have to setup
8556        // the application info early.
8557        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8558        pkg.setApplicationInfoCodePath(pkg.codePath);
8559        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8560        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8561        pkg.setApplicationInfoResourcePath(pkg.codePath);
8562        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8563        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8564
8565        synchronized (mPackages) {
8566            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8567            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8568            if (realPkgName != null) {
8569                ensurePackageRenamed(pkg, renamedPkgName);
8570            }
8571            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8572            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8573            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8574            pkgAlreadyExists = pkgSetting != null;
8575            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8576            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8577            isSystemPkgUpdated = disabledPkgSetting != null;
8578
8579            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8580                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8581            }
8582
8583            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8584                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8585                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8586                    : null;
8587            if (DEBUG_PACKAGE_SCANNING
8588                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8589                    && sharedUserSetting != null) {
8590                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8591                        + " (uid=" + sharedUserSetting.userId + "):"
8592                        + " packages=" + sharedUserSetting.packages);
8593            }
8594
8595            if (scanSystemPartition) {
8596                // Potentially prune child packages. If the application on the /system
8597                // partition has been updated via OTA, but, is still disabled by a
8598                // version on /data, cycle through all of its children packages and
8599                // remove children that are no longer defined.
8600                if (isSystemPkgUpdated) {
8601                    final int scannedChildCount = (pkg.childPackages != null)
8602                            ? pkg.childPackages.size() : 0;
8603                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8604                            ? disabledPkgSetting.childPackageNames.size() : 0;
8605                    for (int i = 0; i < disabledChildCount; i++) {
8606                        String disabledChildPackageName =
8607                                disabledPkgSetting.childPackageNames.get(i);
8608                        boolean disabledPackageAvailable = false;
8609                        for (int j = 0; j < scannedChildCount; j++) {
8610                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8611                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8612                                disabledPackageAvailable = true;
8613                                break;
8614                            }
8615                        }
8616                        if (!disabledPackageAvailable) {
8617                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8618                        }
8619                    }
8620                    // we're updating the disabled package, so, scan it as the package setting
8621                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
8622                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8623                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8624                            (pkg == mPlatformPackage), user);
8625                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8626                }
8627            }
8628        }
8629
8630        final boolean newPkgChangedPaths =
8631                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8632        final boolean newPkgVersionGreater =
8633                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8634        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8635                && newPkgChangedPaths && newPkgVersionGreater;
8636        if (isSystemPkgBetter) {
8637            // The version of the application on /system is greater than the version on
8638            // /data. Switch back to the application on /system.
8639            // It's safe to assume the application on /system will correctly scan. If not,
8640            // there won't be a working copy of the application.
8641            synchronized (mPackages) {
8642                // just remove the loaded entries from package lists
8643                mPackages.remove(pkgSetting.name);
8644            }
8645
8646            logCriticalInfo(Log.WARN,
8647                    "System package updated;"
8648                    + " name: " + pkgSetting.name
8649                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8650                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8651
8652            final InstallArgs args = createInstallArgsForExisting(
8653                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8654                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8655            args.cleanUpResourcesLI();
8656            synchronized (mPackages) {
8657                mSettings.enableSystemPackageLPw(pkgSetting.name);
8658            }
8659        }
8660
8661        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8662            // The version of the application on the /system partition is less than or
8663            // equal to the version on the /data partition. Throw an exception and use
8664            // the application already installed on the /data partition.
8665            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8666                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8667                    + " better than this " + pkg.getLongVersionCode());
8668        }
8669
8670        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8671        // force re-collecting certificate.
8672        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8673                disabledPkgSetting);
8674        // Full APK verification can be skipped during certificate collection, only if the file is
8675        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8676        // cases, only data in Signing Block is verified instead of the whole file.
8677        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8678                (forceCollect && canSkipFullPackageVerification(pkg));
8679        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8680
8681        boolean shouldHideSystemApp = false;
8682        // A new application appeared on /system, but, we already have a copy of
8683        // the application installed on /data.
8684        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8685                && !pkgSetting.isSystem()) {
8686
8687            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8688                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
8689                logCriticalInfo(Log.WARN,
8690                        "System package signature mismatch;"
8691                        + " name: " + pkgSetting.name);
8692                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8693                        "scanPackageInternalLI")) {
8694                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8695                }
8696                pkgSetting = null;
8697            } else if (newPkgVersionGreater) {
8698                // The application on /system is newer than the application on /data.
8699                // Simply remove the application on /data [keeping application data]
8700                // and replace it with the version on /system.
8701                logCriticalInfo(Log.WARN,
8702                        "System package enabled;"
8703                        + " name: " + pkgSetting.name
8704                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8705                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8706                InstallArgs args = createInstallArgsForExisting(
8707                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8708                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8709                synchronized (mInstallLock) {
8710                    args.cleanUpResourcesLI();
8711                }
8712            } else {
8713                // The application on /system is older than the application on /data. Hide
8714                // the application on /system and the version on /data will be scanned later
8715                // and re-added like an update.
8716                shouldHideSystemApp = true;
8717                logCriticalInfo(Log.INFO,
8718                        "System package disabled;"
8719                        + " name: " + pkgSetting.name
8720                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8721                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8722            }
8723        }
8724
8725        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8726                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8727
8728        if (shouldHideSystemApp) {
8729            synchronized (mPackages) {
8730                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8731            }
8732        }
8733        return scannedPkg;
8734    }
8735
8736    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8737        // Derive the new package synthetic package name
8738        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8739                + pkg.staticSharedLibVersion);
8740    }
8741
8742    private static String fixProcessName(String defProcessName,
8743            String processName) {
8744        if (processName == null) {
8745            return defProcessName;
8746        }
8747        return processName;
8748    }
8749
8750    /**
8751     * Enforces that only the system UID or root's UID can call a method exposed
8752     * via Binder.
8753     *
8754     * @param message used as message if SecurityException is thrown
8755     * @throws SecurityException if the caller is not system or root
8756     */
8757    private static final void enforceSystemOrRoot(String message) {
8758        final int uid = Binder.getCallingUid();
8759        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8760            throw new SecurityException(message);
8761        }
8762    }
8763
8764    @Override
8765    public void performFstrimIfNeeded() {
8766        enforceSystemOrRoot("Only the system can request fstrim");
8767
8768        // Before everything else, see whether we need to fstrim.
8769        try {
8770            IStorageManager sm = PackageHelper.getStorageManager();
8771            if (sm != null) {
8772                boolean doTrim = false;
8773                final long interval = android.provider.Settings.Global.getLong(
8774                        mContext.getContentResolver(),
8775                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8776                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8777                if (interval > 0) {
8778                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8779                    if (timeSinceLast > interval) {
8780                        doTrim = true;
8781                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8782                                + "; running immediately");
8783                    }
8784                }
8785                if (doTrim) {
8786                    final boolean dexOptDialogShown;
8787                    synchronized (mPackages) {
8788                        dexOptDialogShown = mDexOptDialogShown;
8789                    }
8790                    if (!isFirstBoot() && dexOptDialogShown) {
8791                        try {
8792                            ActivityManager.getService().showBootMessage(
8793                                    mContext.getResources().getString(
8794                                            R.string.android_upgrading_fstrim), true);
8795                        } catch (RemoteException e) {
8796                        }
8797                    }
8798                    sm.runMaintenance();
8799                }
8800            } else {
8801                Slog.e(TAG, "storageManager service unavailable!");
8802            }
8803        } catch (RemoteException e) {
8804            // Can't happen; StorageManagerService is local
8805        }
8806    }
8807
8808    @Override
8809    public void updatePackagesIfNeeded() {
8810        enforceSystemOrRoot("Only the system can request package update");
8811
8812        // We need to re-extract after an OTA.
8813        boolean causeUpgrade = isUpgrade();
8814
8815        // First boot or factory reset.
8816        // Note: we also handle devices that are upgrading to N right now as if it is their
8817        //       first boot, as they do not have profile data.
8818        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8819
8820        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8821        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8822
8823        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8824            return;
8825        }
8826
8827        List<PackageParser.Package> pkgs;
8828        synchronized (mPackages) {
8829            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8830        }
8831
8832        final long startTime = System.nanoTime();
8833        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8834                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
8835                    false /* bootComplete */);
8836
8837        final int elapsedTimeSeconds =
8838                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8839
8840        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8841        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8842        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8843        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8844        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8845    }
8846
8847    /*
8848     * Return the prebuilt profile path given a package base code path.
8849     */
8850    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8851        return pkg.baseCodePath + ".prof";
8852    }
8853
8854    /**
8855     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8856     * containing statistics about the invocation. The array consists of three elements,
8857     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8858     * and {@code numberOfPackagesFailed}.
8859     */
8860    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8861            final String compilerFilter, boolean bootComplete) {
8862
8863        int numberOfPackagesVisited = 0;
8864        int numberOfPackagesOptimized = 0;
8865        int numberOfPackagesSkipped = 0;
8866        int numberOfPackagesFailed = 0;
8867        final int numberOfPackagesToDexopt = pkgs.size();
8868
8869        for (PackageParser.Package pkg : pkgs) {
8870            numberOfPackagesVisited++;
8871
8872            boolean useProfileForDexopt = false;
8873
8874            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8875                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8876                // that are already compiled.
8877                File profileFile = new File(getPrebuildProfilePath(pkg));
8878                // Copy profile if it exists.
8879                if (profileFile.exists()) {
8880                    try {
8881                        // We could also do this lazily before calling dexopt in
8882                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8883                        // is that we don't have a good way to say "do this only once".
8884                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8885                                pkg.applicationInfo.uid, pkg.packageName,
8886                                ArtManager.getProfileName(null))) {
8887                            Log.e(TAG, "Installer failed to copy system profile!");
8888                        } else {
8889                            // Disabled as this causes speed-profile compilation during first boot
8890                            // even if things are already compiled.
8891                            // useProfileForDexopt = true;
8892                        }
8893                    } catch (Exception e) {
8894                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8895                                e);
8896                    }
8897                } else {
8898                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8899                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8900                    // minimize the number off apps being speed-profile compiled during first boot.
8901                    // The other paths will not change the filter.
8902                    if (disabledPs != null && disabledPs.pkg.isStub) {
8903                        // The package is the stub one, remove the stub suffix to get the normal
8904                        // package and APK names.
8905                        String systemProfilePath =
8906                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8907                        profileFile = new File(systemProfilePath);
8908                        // If we have a profile for a compressed APK, copy it to the reference
8909                        // location.
8910                        // Note that copying the profile here will cause it to override the
8911                        // reference profile every OTA even though the existing reference profile
8912                        // may have more data. We can't copy during decompression since the
8913                        // directories are not set up at that point.
8914                        if (profileFile.exists()) {
8915                            try {
8916                                // We could also do this lazily before calling dexopt in
8917                                // PackageDexOptimizer to prevent this happening on first boot. The
8918                                // issue is that we don't have a good way to say "do this only
8919                                // once".
8920                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8921                                        pkg.applicationInfo.uid, pkg.packageName,
8922                                        ArtManager.getProfileName(null))) {
8923                                    Log.e(TAG, "Failed to copy system profile for stub package!");
8924                                } else {
8925                                    useProfileForDexopt = true;
8926                                }
8927                            } catch (Exception e) {
8928                                Log.e(TAG, "Failed to copy profile " +
8929                                        profileFile.getAbsolutePath() + " ", e);
8930                            }
8931                        }
8932                    }
8933                }
8934            }
8935
8936            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8937                if (DEBUG_DEXOPT) {
8938                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8939                }
8940                numberOfPackagesSkipped++;
8941                continue;
8942            }
8943
8944            if (DEBUG_DEXOPT) {
8945                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8946                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8947            }
8948
8949            if (showDialog) {
8950                try {
8951                    ActivityManager.getService().showBootMessage(
8952                            mContext.getResources().getString(R.string.android_upgrading_apk,
8953                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8954                } catch (RemoteException e) {
8955                }
8956                synchronized (mPackages) {
8957                    mDexOptDialogShown = true;
8958                }
8959            }
8960
8961            String pkgCompilerFilter = compilerFilter;
8962            if (useProfileForDexopt) {
8963                // Use background dexopt mode to try and use the profile. Note that this does not
8964                // guarantee usage of the profile.
8965                pkgCompilerFilter =
8966                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
8967                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
8968            }
8969
8970            // checkProfiles is false to avoid merging profiles during boot which
8971            // might interfere with background compilation (b/28612421).
8972            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8973            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8974            // trade-off worth doing to save boot time work.
8975            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
8976            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
8977                    pkg.packageName,
8978                    pkgCompilerFilter,
8979                    dexoptFlags));
8980
8981            switch (primaryDexOptStaus) {
8982                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8983                    numberOfPackagesOptimized++;
8984                    break;
8985                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8986                    numberOfPackagesSkipped++;
8987                    break;
8988                case PackageDexOptimizer.DEX_OPT_FAILED:
8989                    numberOfPackagesFailed++;
8990                    break;
8991                default:
8992                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
8993                    break;
8994            }
8995        }
8996
8997        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8998                numberOfPackagesFailed };
8999    }
9000
9001    @Override
9002    public void notifyPackageUse(String packageName, int reason) {
9003        synchronized (mPackages) {
9004            final int callingUid = Binder.getCallingUid();
9005            final int callingUserId = UserHandle.getUserId(callingUid);
9006            if (getInstantAppPackageName(callingUid) != null) {
9007                if (!isCallerSameApp(packageName, callingUid)) {
9008                    return;
9009                }
9010            } else {
9011                if (isInstantApp(packageName, callingUserId)) {
9012                    return;
9013                }
9014            }
9015            notifyPackageUseLocked(packageName, reason);
9016        }
9017    }
9018
9019    @GuardedBy("mPackages")
9020    private void notifyPackageUseLocked(String packageName, int reason) {
9021        final PackageParser.Package p = mPackages.get(packageName);
9022        if (p == null) {
9023            return;
9024        }
9025        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9026    }
9027
9028    @Override
9029    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9030            List<String> classPaths, String loaderIsa) {
9031        int userId = UserHandle.getCallingUserId();
9032        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9033        if (ai == null) {
9034            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9035                + loadingPackageName + ", user=" + userId);
9036            return;
9037        }
9038        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9039    }
9040
9041    @Override
9042    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9043            IDexModuleRegisterCallback callback) {
9044        int userId = UserHandle.getCallingUserId();
9045        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9046        DexManager.RegisterDexModuleResult result;
9047        if (ai == null) {
9048            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9049                     " calling user. package=" + packageName + ", user=" + userId);
9050            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9051        } else {
9052            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9053        }
9054
9055        if (callback != null) {
9056            mHandler.post(() -> {
9057                try {
9058                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9059                } catch (RemoteException e) {
9060                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9061                }
9062            });
9063        }
9064    }
9065
9066    /**
9067     * Ask the package manager to perform a dex-opt with the given compiler filter.
9068     *
9069     * Note: exposed only for the shell command to allow moving packages explicitly to a
9070     *       definite state.
9071     */
9072    @Override
9073    public boolean performDexOptMode(String packageName,
9074            boolean checkProfiles, String targetCompilerFilter, boolean force,
9075            boolean bootComplete, String splitName) {
9076        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9077                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9078                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9079        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9080                splitName, flags));
9081    }
9082
9083    /**
9084     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9085     * secondary dex files belonging to the given package.
9086     *
9087     * Note: exposed only for the shell command to allow moving packages explicitly to a
9088     *       definite state.
9089     */
9090    @Override
9091    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9092            boolean force) {
9093        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9094                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9095                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9096                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9097        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9098    }
9099
9100    /*package*/ boolean performDexOpt(DexoptOptions options) {
9101        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9102            return false;
9103        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9104            return false;
9105        }
9106
9107        if (options.isDexoptOnlySecondaryDex()) {
9108            return mDexManager.dexoptSecondaryDex(options);
9109        } else {
9110            int dexoptStatus = performDexOptWithStatus(options);
9111            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9112        }
9113    }
9114
9115    /**
9116     * Perform dexopt on the given package and return one of following result:
9117     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9118     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9119     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9120     */
9121    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9122        return performDexOptTraced(options);
9123    }
9124
9125    private int performDexOptTraced(DexoptOptions options) {
9126        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9127        try {
9128            return performDexOptInternal(options);
9129        } finally {
9130            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9131        }
9132    }
9133
9134    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9135    // if the package can now be considered up to date for the given filter.
9136    private int performDexOptInternal(DexoptOptions options) {
9137        PackageParser.Package p;
9138        synchronized (mPackages) {
9139            p = mPackages.get(options.getPackageName());
9140            if (p == null) {
9141                // Package could not be found. Report failure.
9142                return PackageDexOptimizer.DEX_OPT_FAILED;
9143            }
9144            mPackageUsage.maybeWriteAsync(mPackages);
9145            mCompilerStats.maybeWriteAsync();
9146        }
9147        long callingId = Binder.clearCallingIdentity();
9148        try {
9149            synchronized (mInstallLock) {
9150                return performDexOptInternalWithDependenciesLI(p, options);
9151            }
9152        } finally {
9153            Binder.restoreCallingIdentity(callingId);
9154        }
9155    }
9156
9157    public ArraySet<String> getOptimizablePackages() {
9158        ArraySet<String> pkgs = new ArraySet<String>();
9159        synchronized (mPackages) {
9160            for (PackageParser.Package p : mPackages.values()) {
9161                if (PackageDexOptimizer.canOptimizePackage(p)) {
9162                    pkgs.add(p.packageName);
9163                }
9164            }
9165        }
9166        return pkgs;
9167    }
9168
9169    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9170            DexoptOptions options) {
9171        // Select the dex optimizer based on the force parameter.
9172        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9173        //       allocate an object here.
9174        PackageDexOptimizer pdo = options.isForce()
9175                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9176                : mPackageDexOptimizer;
9177
9178        // Dexopt all dependencies first. Note: we ignore the return value and march on
9179        // on errors.
9180        // Note that we are going to call performDexOpt on those libraries as many times as
9181        // they are referenced in packages. When we do a batch of performDexOpt (for example
9182        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9183        // and the first package that uses the library will dexopt it. The
9184        // others will see that the compiled code for the library is up to date.
9185        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9186        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9187        if (!deps.isEmpty()) {
9188            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9189                    options.getCompilerFilter(), options.getSplitName(),
9190                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9191            for (PackageParser.Package depPackage : deps) {
9192                // TODO: Analyze and investigate if we (should) profile libraries.
9193                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9194                        getOrCreateCompilerPackageStats(depPackage),
9195                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9196            }
9197        }
9198        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9199                getOrCreateCompilerPackageStats(p),
9200                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9201    }
9202
9203    /**
9204     * Reconcile the information we have about the secondary dex files belonging to
9205     * {@code packagName} and the actual dex files. For all dex files that were
9206     * deleted, update the internal records and delete the generated oat files.
9207     */
9208    @Override
9209    public void reconcileSecondaryDexFiles(String packageName) {
9210        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9211            return;
9212        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9213            return;
9214        }
9215        mDexManager.reconcileSecondaryDexFiles(packageName);
9216    }
9217
9218    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9219    // a reference there.
9220    /*package*/ DexManager getDexManager() {
9221        return mDexManager;
9222    }
9223
9224    /**
9225     * Execute the background dexopt job immediately.
9226     */
9227    @Override
9228    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9229        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9230            return false;
9231        }
9232        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9233    }
9234
9235    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9236        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9237                || p.usesStaticLibraries != null) {
9238            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9239            Set<String> collectedNames = new HashSet<>();
9240            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9241
9242            retValue.remove(p);
9243
9244            return retValue;
9245        } else {
9246            return Collections.emptyList();
9247        }
9248    }
9249
9250    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9251            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9252        if (!collectedNames.contains(p.packageName)) {
9253            collectedNames.add(p.packageName);
9254            collected.add(p);
9255
9256            if (p.usesLibraries != null) {
9257                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9258                        null, collected, collectedNames);
9259            }
9260            if (p.usesOptionalLibraries != null) {
9261                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9262                        null, collected, collectedNames);
9263            }
9264            if (p.usesStaticLibraries != null) {
9265                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9266                        p.usesStaticLibrariesVersions, collected, collectedNames);
9267            }
9268        }
9269    }
9270
9271    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9272            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9273        final int libNameCount = libs.size();
9274        for (int i = 0; i < libNameCount; i++) {
9275            String libName = libs.get(i);
9276            long version = (versions != null && versions.length == libNameCount)
9277                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9278            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9279            if (libPkg != null) {
9280                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9281            }
9282        }
9283    }
9284
9285    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9286        synchronized (mPackages) {
9287            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9288            if (libEntry != null) {
9289                return mPackages.get(libEntry.apk);
9290            }
9291            return null;
9292        }
9293    }
9294
9295    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9296        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9297        if (versionedLib == null) {
9298            return null;
9299        }
9300        return versionedLib.get(version);
9301    }
9302
9303    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9304        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9305                pkg.staticSharedLibName);
9306        if (versionedLib == null) {
9307            return null;
9308        }
9309        long previousLibVersion = -1;
9310        final int versionCount = versionedLib.size();
9311        for (int i = 0; i < versionCount; i++) {
9312            final long libVersion = versionedLib.keyAt(i);
9313            if (libVersion < pkg.staticSharedLibVersion) {
9314                previousLibVersion = Math.max(previousLibVersion, libVersion);
9315            }
9316        }
9317        if (previousLibVersion >= 0) {
9318            return versionedLib.get(previousLibVersion);
9319        }
9320        return null;
9321    }
9322
9323    public void shutdown() {
9324        mPackageUsage.writeNow(mPackages);
9325        mCompilerStats.writeNow();
9326        mDexManager.writePackageDexUsageNow();
9327    }
9328
9329    @Override
9330    public void dumpProfiles(String packageName) {
9331        PackageParser.Package pkg;
9332        synchronized (mPackages) {
9333            pkg = mPackages.get(packageName);
9334            if (pkg == null) {
9335                throw new IllegalArgumentException("Unknown package: " + packageName);
9336            }
9337        }
9338        /* Only the shell, root, or the app user should be able to dump profiles. */
9339        int callingUid = Binder.getCallingUid();
9340        if (callingUid != Process.SHELL_UID &&
9341            callingUid != Process.ROOT_UID &&
9342            callingUid != pkg.applicationInfo.uid) {
9343            throw new SecurityException("dumpProfiles");
9344        }
9345
9346        synchronized (mInstallLock) {
9347            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9348            mArtManagerService.dumpProfiles(pkg);
9349            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9350        }
9351    }
9352
9353    @Override
9354    public void forceDexOpt(String packageName) {
9355        enforceSystemOrRoot("forceDexOpt");
9356
9357        PackageParser.Package pkg;
9358        synchronized (mPackages) {
9359            pkg = mPackages.get(packageName);
9360            if (pkg == null) {
9361                throw new IllegalArgumentException("Unknown package: " + packageName);
9362            }
9363        }
9364
9365        synchronized (mInstallLock) {
9366            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9367
9368            // Whoever is calling forceDexOpt wants a compiled package.
9369            // Don't use profiles since that may cause compilation to be skipped.
9370            final int res = performDexOptInternalWithDependenciesLI(
9371                    pkg,
9372                    new DexoptOptions(packageName,
9373                            getDefaultCompilerFilter(),
9374                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9375
9376            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9377            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9378                throw new IllegalStateException("Failed to dexopt: " + res);
9379            }
9380        }
9381    }
9382
9383    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9384        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9385            Slog.w(TAG, "Unable to update from " + oldPkg.name
9386                    + " to " + newPkg.packageName
9387                    + ": old package not in system partition");
9388            return false;
9389        } else if (mPackages.get(oldPkg.name) != null) {
9390            Slog.w(TAG, "Unable to update from " + oldPkg.name
9391                    + " to " + newPkg.packageName
9392                    + ": old package still exists");
9393            return false;
9394        }
9395        return true;
9396    }
9397
9398    void removeCodePathLI(File codePath) {
9399        if (codePath.isDirectory()) {
9400            try {
9401                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9402            } catch (InstallerException e) {
9403                Slog.w(TAG, "Failed to remove code path", e);
9404            }
9405        } else {
9406            codePath.delete();
9407        }
9408    }
9409
9410    private int[] resolveUserIds(int userId) {
9411        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9412    }
9413
9414    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9415        if (pkg == null) {
9416            Slog.wtf(TAG, "Package was null!", new Throwable());
9417            return;
9418        }
9419        clearAppDataLeafLIF(pkg, userId, flags);
9420        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9421        for (int i = 0; i < childCount; i++) {
9422            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9423        }
9424
9425        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9426    }
9427
9428    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9429        final PackageSetting ps;
9430        synchronized (mPackages) {
9431            ps = mSettings.mPackages.get(pkg.packageName);
9432        }
9433        for (int realUserId : resolveUserIds(userId)) {
9434            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9435            try {
9436                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9437                        ceDataInode);
9438            } catch (InstallerException e) {
9439                Slog.w(TAG, String.valueOf(e));
9440            }
9441        }
9442    }
9443
9444    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9445        if (pkg == null) {
9446            Slog.wtf(TAG, "Package was null!", new Throwable());
9447            return;
9448        }
9449        destroyAppDataLeafLIF(pkg, userId, flags);
9450        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9451        for (int i = 0; i < childCount; i++) {
9452            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9453        }
9454    }
9455
9456    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9457        final PackageSetting ps;
9458        synchronized (mPackages) {
9459            ps = mSettings.mPackages.get(pkg.packageName);
9460        }
9461        for (int realUserId : resolveUserIds(userId)) {
9462            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9463            try {
9464                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9465                        ceDataInode);
9466            } catch (InstallerException e) {
9467                Slog.w(TAG, String.valueOf(e));
9468            }
9469            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9470        }
9471    }
9472
9473    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9474        if (pkg == null) {
9475            Slog.wtf(TAG, "Package was null!", new Throwable());
9476            return;
9477        }
9478        destroyAppProfilesLeafLIF(pkg);
9479        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9480        for (int i = 0; i < childCount; i++) {
9481            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9482        }
9483    }
9484
9485    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9486        try {
9487            mInstaller.destroyAppProfiles(pkg.packageName);
9488        } catch (InstallerException e) {
9489            Slog.w(TAG, String.valueOf(e));
9490        }
9491    }
9492
9493    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9494        if (pkg == null) {
9495            Slog.wtf(TAG, "Package was null!", new Throwable());
9496            return;
9497        }
9498        mArtManagerService.clearAppProfiles(pkg);
9499        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9500        for (int i = 0; i < childCount; i++) {
9501            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9502        }
9503    }
9504
9505    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9506            long lastUpdateTime) {
9507        // Set parent install/update time
9508        PackageSetting ps = (PackageSetting) pkg.mExtras;
9509        if (ps != null) {
9510            ps.firstInstallTime = firstInstallTime;
9511            ps.lastUpdateTime = lastUpdateTime;
9512        }
9513        // Set children install/update time
9514        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9515        for (int i = 0; i < childCount; i++) {
9516            PackageParser.Package childPkg = pkg.childPackages.get(i);
9517            ps = (PackageSetting) childPkg.mExtras;
9518            if (ps != null) {
9519                ps.firstInstallTime = firstInstallTime;
9520                ps.lastUpdateTime = lastUpdateTime;
9521            }
9522        }
9523    }
9524
9525    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9526            SharedLibraryEntry file,
9527            PackageParser.Package changingLib) {
9528        if (file.path != null) {
9529            usesLibraryFiles.add(file.path);
9530            return;
9531        }
9532        PackageParser.Package p = mPackages.get(file.apk);
9533        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9534            // If we are doing this while in the middle of updating a library apk,
9535            // then we need to make sure to use that new apk for determining the
9536            // dependencies here.  (We haven't yet finished committing the new apk
9537            // to the package manager state.)
9538            if (p == null || p.packageName.equals(changingLib.packageName)) {
9539                p = changingLib;
9540            }
9541        }
9542        if (p != null) {
9543            usesLibraryFiles.addAll(p.getAllCodePaths());
9544            if (p.usesLibraryFiles != null) {
9545                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9546            }
9547        }
9548    }
9549
9550    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9551            PackageParser.Package changingLib) throws PackageManagerException {
9552        if (pkg == null) {
9553            return;
9554        }
9555        // The collection used here must maintain the order of addition (so
9556        // that libraries are searched in the correct order) and must have no
9557        // duplicates.
9558        Set<String> usesLibraryFiles = null;
9559        if (pkg.usesLibraries != null) {
9560            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9561                    null, null, pkg.packageName, changingLib, true,
9562                    pkg.applicationInfo.targetSdkVersion, null);
9563        }
9564        if (pkg.usesStaticLibraries != null) {
9565            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9566                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9567                    pkg.packageName, changingLib, true,
9568                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9569        }
9570        if (pkg.usesOptionalLibraries != null) {
9571            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9572                    null, null, pkg.packageName, changingLib, false,
9573                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9574        }
9575        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9576            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9577        } else {
9578            pkg.usesLibraryFiles = null;
9579        }
9580    }
9581
9582    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9583            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9584            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9585            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9586            throws PackageManagerException {
9587        final int libCount = requestedLibraries.size();
9588        for (int i = 0; i < libCount; i++) {
9589            final String libName = requestedLibraries.get(i);
9590            final long libVersion = requiredVersions != null ? requiredVersions[i]
9591                    : SharedLibraryInfo.VERSION_UNDEFINED;
9592            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9593            if (libEntry == null) {
9594                if (required) {
9595                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9596                            "Package " + packageName + " requires unavailable shared library "
9597                                    + libName + "; failing!");
9598                } else if (DEBUG_SHARED_LIBRARIES) {
9599                    Slog.i(TAG, "Package " + packageName
9600                            + " desires unavailable shared library "
9601                            + libName + "; ignoring!");
9602                }
9603            } else {
9604                if (requiredVersions != null && requiredCertDigests != null) {
9605                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9606                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9607                            "Package " + packageName + " requires unavailable static shared"
9608                                    + " library " + libName + " version "
9609                                    + libEntry.info.getLongVersion() + "; failing!");
9610                    }
9611
9612                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9613                    if (libPkg == null) {
9614                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9615                                "Package " + packageName + " requires unavailable static shared"
9616                                        + " library; failing!");
9617                    }
9618
9619                    final String[] expectedCertDigests = requiredCertDigests[i];
9620
9621
9622                    if (expectedCertDigests.length > 1) {
9623
9624                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9625                        final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9626                                ? PackageUtils.computeSignaturesSha256Digests(
9627                                libPkg.mSigningDetails.signatures)
9628                                : PackageUtils.computeSignaturesSha256Digests(
9629                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9630
9631                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9632                        // target O we don't parse the "additional-certificate" tags similarly
9633                        // how we only consider all certs only for apps targeting O (see above).
9634                        // Therefore, the size check is safe to make.
9635                        if (expectedCertDigests.length != libCertDigests.length) {
9636                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9637                                    "Package " + packageName + " requires differently signed" +
9638                                            " static shared library; failing!");
9639                        }
9640
9641                        // Use a predictable order as signature order may vary
9642                        Arrays.sort(libCertDigests);
9643                        Arrays.sort(expectedCertDigests);
9644
9645                        final int certCount = libCertDigests.length;
9646                        for (int j = 0; j < certCount; j++) {
9647                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9648                                throw new PackageManagerException(
9649                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9650                                        "Package " + packageName + " requires differently signed" +
9651                                                " static shared library; failing!");
9652                            }
9653                        }
9654                    } else {
9655
9656                        // lib signing cert could have rotated beyond the one expected, check to see
9657                        // if the new one has been blessed by the old
9658                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9659                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9660                            throw new PackageManagerException(
9661                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9662                                    "Package " + packageName + " requires differently signed" +
9663                                            " static shared library; failing!");
9664                        }
9665                    }
9666                }
9667
9668                if (outUsedLibraries == null) {
9669                    // Use LinkedHashSet to preserve the order of files added to
9670                    // usesLibraryFiles while eliminating duplicates.
9671                    outUsedLibraries = new LinkedHashSet<>();
9672                }
9673                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9674            }
9675        }
9676        return outUsedLibraries;
9677    }
9678
9679    private static boolean hasString(List<String> list, List<String> which) {
9680        if (list == null) {
9681            return false;
9682        }
9683        for (int i=list.size()-1; i>=0; i--) {
9684            for (int j=which.size()-1; j>=0; j--) {
9685                if (which.get(j).equals(list.get(i))) {
9686                    return true;
9687                }
9688            }
9689        }
9690        return false;
9691    }
9692
9693    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9694            PackageParser.Package changingPkg) {
9695        ArrayList<PackageParser.Package> res = null;
9696        for (PackageParser.Package pkg : mPackages.values()) {
9697            if (changingPkg != null
9698                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9699                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9700                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9701                            changingPkg.staticSharedLibName)) {
9702                return null;
9703            }
9704            if (res == null) {
9705                res = new ArrayList<>();
9706            }
9707            res.add(pkg);
9708            try {
9709                updateSharedLibrariesLPr(pkg, changingPkg);
9710            } catch (PackageManagerException e) {
9711                // If a system app update or an app and a required lib missing we
9712                // delete the package and for updated system apps keep the data as
9713                // it is better for the user to reinstall than to be in an limbo
9714                // state. Also libs disappearing under an app should never happen
9715                // - just in case.
9716                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9717                    final int flags = pkg.isUpdatedSystemApp()
9718                            ? PackageManager.DELETE_KEEP_DATA : 0;
9719                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9720                            flags , null, true, null);
9721                }
9722                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9723            }
9724        }
9725        return res;
9726    }
9727
9728    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9729            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9730            @Nullable UserHandle user) throws PackageManagerException {
9731        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9732        // If the package has children and this is the first dive in the function
9733        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9734        // whether all packages (parent and children) would be successfully scanned
9735        // before the actual scan since scanning mutates internal state and we want
9736        // to atomically install the package and its children.
9737        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9738            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9739                scanFlags |= SCAN_CHECK_ONLY;
9740            }
9741        } else {
9742            scanFlags &= ~SCAN_CHECK_ONLY;
9743        }
9744
9745        final PackageParser.Package scannedPkg;
9746        try {
9747            // Scan the parent
9748            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9749            // Scan the children
9750            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9751            for (int i = 0; i < childCount; i++) {
9752                PackageParser.Package childPkg = pkg.childPackages.get(i);
9753                scanPackageNewLI(childPkg, parseFlags,
9754                        scanFlags, currentTime, user);
9755            }
9756        } finally {
9757            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9758        }
9759
9760        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9761            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9762        }
9763
9764        return scannedPkg;
9765    }
9766
9767    /** The result of a package scan. */
9768    private static class ScanResult {
9769        /** Whether or not the package scan was successful */
9770        public final boolean success;
9771        /**
9772         * The final package settings. This may be the same object passed in
9773         * the {@link ScanRequest}, but, with modified values.
9774         */
9775        @Nullable public final PackageSetting pkgSetting;
9776        /** ABI code paths that have changed in the package scan */
9777        @Nullable public final List<String> changedAbiCodePath;
9778        public ScanResult(
9779                boolean success,
9780                @Nullable PackageSetting pkgSetting,
9781                @Nullable List<String> changedAbiCodePath) {
9782            this.success = success;
9783            this.pkgSetting = pkgSetting;
9784            this.changedAbiCodePath = changedAbiCodePath;
9785        }
9786    }
9787
9788    /** A package to be scanned */
9789    private static class ScanRequest {
9790        /** The parsed package */
9791        @NonNull public final PackageParser.Package pkg;
9792        /** Shared user settings, if the package has a shared user */
9793        @Nullable public final SharedUserSetting sharedUserSetting;
9794        /**
9795         * Package settings of the currently installed version.
9796         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9797         * during scan.
9798         */
9799        @Nullable public final PackageSetting pkgSetting;
9800        /** A copy of the settings for the currently installed version */
9801        @Nullable public final PackageSetting oldPkgSetting;
9802        /** Package settings for the disabled version on the /system partition */
9803        @Nullable public final PackageSetting disabledPkgSetting;
9804        /** Package settings for the installed version under its original package name */
9805        @Nullable public final PackageSetting originalPkgSetting;
9806        /** The real package name of a renamed application */
9807        @Nullable public final String realPkgName;
9808        public final @ParseFlags int parseFlags;
9809        public final @ScanFlags int scanFlags;
9810        /** The user for which the package is being scanned */
9811        @Nullable public final UserHandle user;
9812        /** Whether or not the platform package is being scanned */
9813        public final boolean isPlatformPackage;
9814        public ScanRequest(
9815                @NonNull PackageParser.Package pkg,
9816                @Nullable SharedUserSetting sharedUserSetting,
9817                @Nullable PackageSetting pkgSetting,
9818                @Nullable PackageSetting disabledPkgSetting,
9819                @Nullable PackageSetting originalPkgSetting,
9820                @Nullable String realPkgName,
9821                @ParseFlags int parseFlags,
9822                @ScanFlags int scanFlags,
9823                boolean isPlatformPackage,
9824                @Nullable UserHandle user) {
9825            this.pkg = pkg;
9826            this.pkgSetting = pkgSetting;
9827            this.sharedUserSetting = sharedUserSetting;
9828            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9829            this.disabledPkgSetting = disabledPkgSetting;
9830            this.originalPkgSetting = originalPkgSetting;
9831            this.realPkgName = realPkgName;
9832            this.parseFlags = parseFlags;
9833            this.scanFlags = scanFlags;
9834            this.isPlatformPackage = isPlatformPackage;
9835            this.user = user;
9836        }
9837    }
9838
9839    /**
9840     * Returns the actual scan flags depending upon the state of the other settings.
9841     * <p>Updated system applications will not have the following flags set
9842     * by default and need to be adjusted after the fact:
9843     * <ul>
9844     * <li>{@link #SCAN_AS_SYSTEM}</li>
9845     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9846     * <li>{@link #SCAN_AS_OEM}</li>
9847     * <li>{@link #SCAN_AS_VENDOR}</li>
9848     * <li>{@link #SCAN_AS_PRODUCT}</li>
9849     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9850     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9851     * </ul>
9852     */
9853    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9854            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9855            PackageParser.Package pkg) {
9856        if (disabledPkgSetting != null) {
9857            // updated system application, must at least have SCAN_AS_SYSTEM
9858            scanFlags |= SCAN_AS_SYSTEM;
9859            if ((disabledPkgSetting.pkgPrivateFlags
9860                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9861                scanFlags |= SCAN_AS_PRIVILEGED;
9862            }
9863            if ((disabledPkgSetting.pkgPrivateFlags
9864                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9865                scanFlags |= SCAN_AS_OEM;
9866            }
9867            if ((disabledPkgSetting.pkgPrivateFlags
9868                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9869                scanFlags |= SCAN_AS_VENDOR;
9870            }
9871            if ((disabledPkgSetting.pkgPrivateFlags
9872                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9873                scanFlags |= SCAN_AS_PRODUCT;
9874            }
9875        }
9876        if (pkgSetting != null) {
9877            final int userId = ((user == null) ? 0 : user.getIdentifier());
9878            if (pkgSetting.getInstantApp(userId)) {
9879                scanFlags |= SCAN_AS_INSTANT_APP;
9880            }
9881            if (pkgSetting.getVirtulalPreload(userId)) {
9882                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9883            }
9884        }
9885
9886        // Scan as privileged apps that share a user with a priv-app.
9887        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9888                && (pkg.mSharedUserId != null)) {
9889            SharedUserSetting sharedUserSetting = null;
9890            try {
9891                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9892            } catch (PackageManagerException ignore) {}
9893            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9894                // Exempt SharedUsers signed with the platform key.
9895                // TODO(b/72378145) Fix this exemption. Force signature apps
9896                // to whitelist their privileged permissions just like other
9897                // priv-apps.
9898                synchronized (mPackages) {
9899                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9900                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
9901                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
9902                        scanFlags |= SCAN_AS_PRIVILEGED;
9903                    }
9904                }
9905            }
9906        }
9907
9908        return scanFlags;
9909    }
9910
9911    @GuardedBy("mInstallLock")
9912    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
9913            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9914            @Nullable UserHandle user) throws PackageManagerException {
9915
9916        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9917        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
9918        if (realPkgName != null) {
9919            ensurePackageRenamed(pkg, renamedPkgName);
9920        }
9921        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
9922        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9923        final PackageSetting disabledPkgSetting =
9924                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9925
9926        if (mTransferedPackages.contains(pkg.packageName)) {
9927            Slog.w(TAG, "Package " + pkg.packageName
9928                    + " was transferred to another, but its .apk remains");
9929        }
9930
9931        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
9932        synchronized (mPackages) {
9933            applyPolicy(pkg, parseFlags, scanFlags);
9934            assertPackageIsValid(pkg, parseFlags, scanFlags);
9935
9936            SharedUserSetting sharedUserSetting = null;
9937            if (pkg.mSharedUserId != null) {
9938                // SIDE EFFECTS; may potentially allocate a new shared user
9939                sharedUserSetting = mSettings.getSharedUserLPw(
9940                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9941                if (DEBUG_PACKAGE_SCANNING) {
9942                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
9943                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
9944                                + " (uid=" + sharedUserSetting.userId + "):"
9945                                + " packages=" + sharedUserSetting.packages);
9946                }
9947            }
9948
9949            boolean scanSucceeded = false;
9950            try {
9951                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
9952                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
9953                        (pkg == mPlatformPackage), user);
9954                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
9955                if (result.success) {
9956                    commitScanResultsLocked(request, result);
9957                }
9958                scanSucceeded = true;
9959            } finally {
9960                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9961                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
9962                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9963                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9964                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9965                  }
9966            }
9967        }
9968        return pkg;
9969    }
9970
9971    /**
9972     * Commits the package scan and modifies system state.
9973     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
9974     * of committing the package, leaving the system in an inconsistent state.
9975     * This needs to be fixed so, once we get to this point, no errors are
9976     * possible and the system is not left in an inconsistent state.
9977     */
9978    @GuardedBy("mPackages")
9979    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
9980            throws PackageManagerException {
9981        final PackageParser.Package pkg = request.pkg;
9982        final @ParseFlags int parseFlags = request.parseFlags;
9983        final @ScanFlags int scanFlags = request.scanFlags;
9984        final PackageSetting oldPkgSetting = request.oldPkgSetting;
9985        final PackageSetting originalPkgSetting = request.originalPkgSetting;
9986        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
9987        final UserHandle user = request.user;
9988        final String realPkgName = request.realPkgName;
9989        final PackageSetting pkgSetting = result.pkgSetting;
9990        final List<String> changedAbiCodePath = result.changedAbiCodePath;
9991        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
9992
9993        if (newPkgSettingCreated) {
9994            if (originalPkgSetting != null) {
9995                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
9996            }
9997            // THROWS: when we can't allocate a user id. add call to check if there's
9998            // enough space to ensure we won't throw; otherwise, don't modify state
9999            mSettings.addUserToSettingLPw(pkgSetting);
10000
10001            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10002                mTransferedPackages.add(originalPkgSetting.name);
10003            }
10004        }
10005        // TODO(toddke): Consider a method specifically for modifying the Package object
10006        // post scan; or, moving this stuff out of the Package object since it has nothing
10007        // to do with the package on disk.
10008        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10009        // for creating the application ID. If we did this earlier, we would be saving the
10010        // correct ID.
10011        pkg.applicationInfo.uid = pkgSetting.appId;
10012
10013        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10014
10015        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10016            mTransferedPackages.add(pkg.packageName);
10017        }
10018
10019        // THROWS: when requested libraries that can't be found. it only changes
10020        // the state of the passed in pkg object, so, move to the top of the method
10021        // and allow it to abort
10022        if ((scanFlags & SCAN_BOOTING) == 0
10023                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10024            // Check all shared libraries and map to their actual file path.
10025            // We only do this here for apps not on a system dir, because those
10026            // are the only ones that can fail an install due to this.  We
10027            // will take care of the system apps by updating all of their
10028            // library paths after the scan is done. Also during the initial
10029            // scan don't update any libs as we do this wholesale after all
10030            // apps are scanned to avoid dependency based scanning.
10031            updateSharedLibrariesLPr(pkg, null);
10032        }
10033
10034        // All versions of a static shared library are referenced with the same
10035        // package name. Internally, we use a synthetic package name to allow
10036        // multiple versions of the same shared library to be installed. So,
10037        // we need to generate the synthetic package name of the latest shared
10038        // library in order to compare signatures.
10039        PackageSetting signatureCheckPs = pkgSetting;
10040        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10041            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10042            if (libraryEntry != null) {
10043                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10044            }
10045        }
10046
10047        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10048        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10049            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10050                // We just determined the app is signed correctly, so bring
10051                // over the latest parsed certs.
10052                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10053            } else {
10054                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10055                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10056                            "Package " + pkg.packageName + " upgrade keys do not match the "
10057                                    + "previously installed version");
10058                } else {
10059                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10060                    String msg = "System package " + pkg.packageName
10061                            + " signature changed; retaining data.";
10062                    reportSettingsProblem(Log.WARN, msg);
10063                }
10064            }
10065        } else {
10066            try {
10067                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10068                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10069                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10070                        pkg.mSigningDetails, compareCompat, compareRecover);
10071                // The new KeySets will be re-added later in the scanning process.
10072                if (compatMatch) {
10073                    synchronized (mPackages) {
10074                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10075                    }
10076                }
10077                // We just determined the app is signed correctly, so bring
10078                // over the latest parsed certs.
10079                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10080
10081
10082                // if this is is a sharedUser, check to see if the new package is signed by a newer
10083                // signing certificate than the existing one, and if so, copy over the new details
10084                if (signatureCheckPs.sharedUser != null
10085                        && pkg.mSigningDetails.hasAncestor(
10086                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10087                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10088                }
10089            } catch (PackageManagerException e) {
10090                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10091                    throw e;
10092                }
10093                // The signature has changed, but this package is in the system
10094                // image...  let's recover!
10095                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10096                // However...  if this package is part of a shared user, but it
10097                // doesn't match the signature of the shared user, let's fail.
10098                // What this means is that you can't change the signatures
10099                // associated with an overall shared user, which doesn't seem all
10100                // that unreasonable.
10101                if (signatureCheckPs.sharedUser != null) {
10102                    if (compareSignatures(
10103                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10104                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10105                        throw new PackageManagerException(
10106                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10107                                "Signature mismatch for shared user: "
10108                                        + pkgSetting.sharedUser);
10109                    }
10110                }
10111                // File a report about this.
10112                String msg = "System package " + pkg.packageName
10113                        + " signature changed; retaining data.";
10114                reportSettingsProblem(Log.WARN, msg);
10115            } catch (IllegalArgumentException e) {
10116
10117                // should never happen: certs matched when checking, but not when comparing
10118                // old to new for sharedUser
10119                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10120                        "Signing certificates comparison made on incomparable signing details"
10121                        + " but somehow passed verifySignatures!");
10122            }
10123        }
10124
10125        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10126            // This package wants to adopt ownership of permissions from
10127            // another package.
10128            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10129                final String origName = pkg.mAdoptPermissions.get(i);
10130                final PackageSetting orig = mSettings.getPackageLPr(origName);
10131                if (orig != null) {
10132                    if (verifyPackageUpdateLPr(orig, pkg)) {
10133                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10134                                + pkg.packageName);
10135                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10136                    }
10137                }
10138            }
10139        }
10140
10141        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10142            for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
10143                final String codePathString = changedAbiCodePath.get(i);
10144                try {
10145                    mInstaller.rmdex(codePathString,
10146                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10147                } catch (InstallerException ignored) {
10148                }
10149            }
10150        }
10151
10152        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10153            if (oldPkgSetting != null) {
10154                synchronized (mPackages) {
10155                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10156                }
10157            }
10158        } else {
10159            final int userId = user == null ? 0 : user.getIdentifier();
10160            // Modify state for the given package setting
10161            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10162                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10163            if (pkgSetting.getInstantApp(userId)) {
10164                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10165            }
10166        }
10167    }
10168
10169    /**
10170     * Returns the "real" name of the package.
10171     * <p>This may differ from the package's actual name if the application has already
10172     * been installed under one of this package's original names.
10173     */
10174    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10175            @Nullable String renamedPkgName) {
10176        if (isPackageRenamed(pkg, renamedPkgName)) {
10177            return pkg.mRealPackage;
10178        }
10179        return null;
10180    }
10181
10182    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10183    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10184            @Nullable String renamedPkgName) {
10185        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10186    }
10187
10188    /**
10189     * Returns the original package setting.
10190     * <p>A package can migrate its name during an update. In this scenario, a package
10191     * designates a set of names that it considers as one of its original names.
10192     * <p>An original package must be signed identically and it must have the same
10193     * shared user [if any].
10194     */
10195    @GuardedBy("mPackages")
10196    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10197            @Nullable String renamedPkgName) {
10198        if (!isPackageRenamed(pkg, renamedPkgName)) {
10199            return null;
10200        }
10201        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10202            final PackageSetting originalPs =
10203                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10204            if (originalPs != null) {
10205                // the package is already installed under its original name...
10206                // but, should we use it?
10207                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10208                    // the new package is incompatible with the original
10209                    continue;
10210                } else if (originalPs.sharedUser != null) {
10211                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10212                        // the shared user id is incompatible with the original
10213                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10214                                + " to " + pkg.packageName + ": old uid "
10215                                + originalPs.sharedUser.name
10216                                + " differs from " + pkg.mSharedUserId);
10217                        continue;
10218                    }
10219                    // TODO: Add case when shared user id is added [b/28144775]
10220                } else {
10221                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10222                            + pkg.packageName + " to old name " + originalPs.name);
10223                }
10224                return originalPs;
10225            }
10226        }
10227        return null;
10228    }
10229
10230    /**
10231     * Renames the package if it was installed under a different name.
10232     * <p>When we've already installed the package under an original name, update
10233     * the new package so we can continue to have the old name.
10234     */
10235    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10236            @NonNull String renamedPackageName) {
10237        if (pkg.mOriginalPackages == null
10238                || !pkg.mOriginalPackages.contains(renamedPackageName)
10239                || pkg.packageName.equals(renamedPackageName)) {
10240            return;
10241        }
10242        pkg.setPackageName(renamedPackageName);
10243    }
10244
10245    /**
10246     * Just scans the package without any side effects.
10247     * <p>Not entirely true at the moment. There is still one side effect -- this
10248     * method potentially modifies a live {@link PackageSetting} object representing
10249     * the package being scanned. This will be resolved in the future.
10250     *
10251     * @param request Information about the package to be scanned
10252     * @param isUnderFactoryTest Whether or not the device is under factory test
10253     * @param currentTime The current time, in millis
10254     * @return The results of the scan
10255     */
10256    @GuardedBy("mInstallLock")
10257    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10258            boolean isUnderFactoryTest, long currentTime)
10259                    throws PackageManagerException {
10260        final PackageParser.Package pkg = request.pkg;
10261        PackageSetting pkgSetting = request.pkgSetting;
10262        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10263        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10264        final @ParseFlags int parseFlags = request.parseFlags;
10265        final @ScanFlags int scanFlags = request.scanFlags;
10266        final String realPkgName = request.realPkgName;
10267        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10268        final UserHandle user = request.user;
10269        final boolean isPlatformPackage = request.isPlatformPackage;
10270
10271        List<String> changedAbiCodePath = null;
10272
10273        if (DEBUG_PACKAGE_SCANNING) {
10274            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10275                Log.d(TAG, "Scanning package " + pkg.packageName);
10276        }
10277
10278        if (Build.IS_DEBUGGABLE &&
10279                pkg.isPrivileged() &&
10280                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10281            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10282        }
10283
10284        // Initialize package source and resource directories
10285        final File scanFile = new File(pkg.codePath);
10286        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10287        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10288
10289        // We keep references to the derived CPU Abis from settings in oder to reuse
10290        // them in the case where we're not upgrading or booting for the first time.
10291        String primaryCpuAbiFromSettings = null;
10292        String secondaryCpuAbiFromSettings = null;
10293        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10294
10295        if (!needToDeriveAbi) {
10296            if (pkgSetting != null) {
10297                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10298                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10299            } else {
10300                // Re-scanning a system package after uninstalling updates; need to derive ABI
10301                needToDeriveAbi = true;
10302            }
10303        }
10304
10305        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10306            PackageManagerService.reportSettingsProblem(Log.WARN,
10307                    "Package " + pkg.packageName + " shared user changed from "
10308                            + (pkgSetting.sharedUser != null
10309                            ? pkgSetting.sharedUser.name : "<nothing>")
10310                            + " to "
10311                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10312                            + "; replacing with new");
10313            pkgSetting = null;
10314        }
10315
10316        String[] usesStaticLibraries = null;
10317        if (pkg.usesStaticLibraries != null) {
10318            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10319            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10320        }
10321        final boolean createNewPackage = (pkgSetting == null);
10322        if (createNewPackage) {
10323            final String parentPackageName = (pkg.parentPackage != null)
10324                    ? pkg.parentPackage.packageName : null;
10325            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10326            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10327            // REMOVE SharedUserSetting from method; update in a separate call
10328            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10329                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10330                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10331                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10332                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10333                    user, true /*allowInstall*/, instantApp, virtualPreload,
10334                    parentPackageName, pkg.getChildPackageNames(),
10335                    UserManagerService.getInstance(), usesStaticLibraries,
10336                    pkg.usesStaticLibrariesVersions);
10337        } else {
10338            // REMOVE SharedUserSetting from method; update in a separate call.
10339            //
10340            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10341            // secondaryCpuAbi are not known at this point so we always update them
10342            // to null here, only to reset them at a later point.
10343            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10344                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10345                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10346                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10347                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10348                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10349        }
10350        if (createNewPackage && originalPkgSetting != null) {
10351            // This is the initial transition from the original package, so,
10352            // fix up the new package's name now. We must do this after looking
10353            // up the package under its new name, so getPackageLP takes care of
10354            // fiddling things correctly.
10355            pkg.setPackageName(originalPkgSetting.name);
10356
10357            // File a report about this.
10358            String msg = "New package " + pkgSetting.realName
10359                    + " renamed to replace old package " + pkgSetting.name;
10360            reportSettingsProblem(Log.WARN, msg);
10361        }
10362
10363        if (disabledPkgSetting != null) {
10364            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10365        }
10366
10367        // SELinux sandboxes become more restrictive as targetSdkVersion increases.
10368        // To ensure that apps with sharedUserId are placed in the same selinux domain
10369        // without breaking any assumptions about access, put them into the least
10370        // restrictive targetSdkVersion=25 domain.
10371        // TODO(b/72290969): Base this on the actual targetSdkVersion(s) of the apps within the
10372        // sharedUserSetting, instead of defaulting to the least restrictive domain.
10373        final int targetSdk = (sharedUserSetting != null) ? 25
10374                : pkg.applicationInfo.targetSdkVersion;
10375        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10376        // They currently can be if the sharedUser apps are signed with the platform key.
10377        final boolean isPrivileged = (sharedUserSetting != null) ?
10378            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10379
10380        SELinuxMMAC.assignSeInfoValue(pkg, isPrivileged, targetSdk);
10381
10382        pkg.mExtras = pkgSetting;
10383        pkg.applicationInfo.processName = fixProcessName(
10384                pkg.applicationInfo.packageName,
10385                pkg.applicationInfo.processName);
10386
10387        if (!isPlatformPackage) {
10388            // Get all of our default paths setup
10389            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10390        }
10391
10392        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10393
10394        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10395            if (needToDeriveAbi) {
10396                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10397                final boolean extractNativeLibs = !pkg.isLibrary();
10398                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10399                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10400
10401                // Some system apps still use directory structure for native libraries
10402                // in which case we might end up not detecting abi solely based on apk
10403                // structure. Try to detect abi based on directory structure.
10404                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10405                        pkg.applicationInfo.primaryCpuAbi == null) {
10406                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10407                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10408                }
10409            } else {
10410                // This is not a first boot or an upgrade, don't bother deriving the
10411                // ABI during the scan. Instead, trust the value that was stored in the
10412                // package setting.
10413                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10414                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10415
10416                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10417
10418                if (DEBUG_ABI_SELECTION) {
10419                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10420                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10421                            pkg.applicationInfo.secondaryCpuAbi);
10422                }
10423            }
10424        } else {
10425            if ((scanFlags & SCAN_MOVE) != 0) {
10426                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10427                // but we already have this packages package info in the PackageSetting. We just
10428                // use that and derive the native library path based on the new codepath.
10429                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10430                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10431            }
10432
10433            // Set native library paths again. For moves, the path will be updated based on the
10434            // ABIs we've determined above. For non-moves, the path will be updated based on the
10435            // ABIs we determined during compilation, but the path will depend on the final
10436            // package path (after the rename away from the stage path).
10437            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10438        }
10439
10440        // This is a special case for the "system" package, where the ABI is
10441        // dictated by the zygote configuration (and init.rc). We should keep track
10442        // of this ABI so that we can deal with "normal" applications that run under
10443        // the same UID correctly.
10444        if (isPlatformPackage) {
10445            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10446                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10447        }
10448
10449        // If there's a mismatch between the abi-override in the package setting
10450        // and the abiOverride specified for the install. Warn about this because we
10451        // would've already compiled the app without taking the package setting into
10452        // account.
10453        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10454            if (cpuAbiOverride == null && pkg.packageName != null) {
10455                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10456                        " for package " + pkg.packageName);
10457            }
10458        }
10459
10460        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10461        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10462        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10463
10464        // Copy the derived override back to the parsed package, so that we can
10465        // update the package settings accordingly.
10466        pkg.cpuAbiOverride = cpuAbiOverride;
10467
10468        if (DEBUG_ABI_SELECTION) {
10469            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10470                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10471                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10472        }
10473
10474        // Push the derived path down into PackageSettings so we know what to
10475        // clean up at uninstall time.
10476        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10477
10478        if (DEBUG_ABI_SELECTION) {
10479            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10480                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10481                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10482        }
10483
10484        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10485            // We don't do this here during boot because we can do it all
10486            // at once after scanning all existing packages.
10487            //
10488            // We also do this *before* we perform dexopt on this package, so that
10489            // we can avoid redundant dexopts, and also to make sure we've got the
10490            // code and package path correct.
10491            changedAbiCodePath =
10492                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10493        }
10494
10495        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10496                android.Manifest.permission.FACTORY_TEST)) {
10497            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10498        }
10499
10500        if (isSystemApp(pkg)) {
10501            pkgSetting.isOrphaned = true;
10502        }
10503
10504        // Take care of first install / last update times.
10505        final long scanFileTime = getLastModifiedTime(pkg);
10506        if (currentTime != 0) {
10507            if (pkgSetting.firstInstallTime == 0) {
10508                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10509            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10510                pkgSetting.lastUpdateTime = currentTime;
10511            }
10512        } else if (pkgSetting.firstInstallTime == 0) {
10513            // We need *something*.  Take time time stamp of the file.
10514            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10515        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10516            if (scanFileTime != pkgSetting.timeStamp) {
10517                // A package on the system image has changed; consider this
10518                // to be an update.
10519                pkgSetting.lastUpdateTime = scanFileTime;
10520            }
10521        }
10522        pkgSetting.setTimeStamp(scanFileTime);
10523
10524        pkgSetting.pkg = pkg;
10525        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10526        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10527            pkgSetting.versionCode = pkg.getLongVersionCode();
10528        }
10529        // Update volume if needed
10530        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10531        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10532            Slog.i(PackageManagerService.TAG,
10533                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10534                    + " package " + pkg.packageName
10535                    + " volume from " + pkgSetting.volumeUuid
10536                    + " to " + volumeUuid);
10537            pkgSetting.volumeUuid = volumeUuid;
10538        }
10539
10540        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10541    }
10542
10543    /**
10544     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10545     */
10546    private static boolean apkHasCode(String fileName) {
10547        StrictJarFile jarFile = null;
10548        try {
10549            jarFile = new StrictJarFile(fileName,
10550                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10551            return jarFile.findEntry("classes.dex") != null;
10552        } catch (IOException ignore) {
10553        } finally {
10554            try {
10555                if (jarFile != null) {
10556                    jarFile.close();
10557                }
10558            } catch (IOException ignore) {}
10559        }
10560        return false;
10561    }
10562
10563    /**
10564     * Enforces code policy for the package. This ensures that if an APK has
10565     * declared hasCode="true" in its manifest that the APK actually contains
10566     * code.
10567     *
10568     * @throws PackageManagerException If bytecode could not be found when it should exist
10569     */
10570    private static void assertCodePolicy(PackageParser.Package pkg)
10571            throws PackageManagerException {
10572        final boolean shouldHaveCode =
10573                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10574        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10575            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10576                    "Package " + pkg.baseCodePath + " code is missing");
10577        }
10578
10579        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10580            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10581                final boolean splitShouldHaveCode =
10582                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10583                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10584                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10585                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10586                }
10587            }
10588        }
10589    }
10590
10591    /**
10592     * Applies policy to the parsed package based upon the given policy flags.
10593     * Ensures the package is in a good state.
10594     * <p>
10595     * Implementation detail: This method must NOT have any side effect. It would
10596     * ideally be static, but, it requires locks to read system state.
10597     */
10598    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10599            final @ScanFlags int scanFlags) {
10600        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10601            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10602            if (pkg.applicationInfo.isDirectBootAware()) {
10603                // we're direct boot aware; set for all components
10604                for (PackageParser.Service s : pkg.services) {
10605                    s.info.encryptionAware = s.info.directBootAware = true;
10606                }
10607                for (PackageParser.Provider p : pkg.providers) {
10608                    p.info.encryptionAware = p.info.directBootAware = true;
10609                }
10610                for (PackageParser.Activity a : pkg.activities) {
10611                    a.info.encryptionAware = a.info.directBootAware = true;
10612                }
10613                for (PackageParser.Activity r : pkg.receivers) {
10614                    r.info.encryptionAware = r.info.directBootAware = true;
10615                }
10616            }
10617            if (compressedFileExists(pkg.codePath)) {
10618                pkg.isStub = true;
10619            }
10620        } else {
10621            // non system apps can't be flagged as core
10622            pkg.coreApp = false;
10623            // clear flags not applicable to regular apps
10624            pkg.applicationInfo.flags &=
10625                    ~ApplicationInfo.FLAG_PERSISTENT;
10626            pkg.applicationInfo.privateFlags &=
10627                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10628            pkg.applicationInfo.privateFlags &=
10629                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10630            // cap permission priorities
10631            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10632                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10633                    pkg.permissionGroups.get(i).info.priority = 0;
10634                }
10635            }
10636        }
10637        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10638            // clear protected broadcasts
10639            pkg.protectedBroadcasts = null;
10640            // ignore export request for single user receivers
10641            if (pkg.receivers != null) {
10642                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10643                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10644                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10645                        receiver.info.exported = false;
10646                    }
10647                }
10648            }
10649            // ignore export request for single user services
10650            if (pkg.services != null) {
10651                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10652                    final PackageParser.Service service = pkg.services.get(i);
10653                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10654                        service.info.exported = false;
10655                    }
10656                }
10657            }
10658            // ignore export request for single user providers
10659            if (pkg.providers != null) {
10660                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10661                    final PackageParser.Provider provider = pkg.providers.get(i);
10662                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10663                        provider.info.exported = false;
10664                    }
10665                }
10666            }
10667        }
10668
10669        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10670            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10671        }
10672
10673        if ((scanFlags & SCAN_AS_OEM) != 0) {
10674            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10675        }
10676
10677        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10678            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10679        }
10680
10681        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10682            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10683        }
10684
10685        if (!isSystemApp(pkg)) {
10686            // Only system apps can use these features.
10687            pkg.mOriginalPackages = null;
10688            pkg.mRealPackage = null;
10689            pkg.mAdoptPermissions = null;
10690        }
10691    }
10692
10693    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10694            throws PackageManagerException {
10695        if (object == null) {
10696            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10697        }
10698        return object;
10699    }
10700
10701    /**
10702     * Asserts the parsed package is valid according to the given policy. If the
10703     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10704     * <p>
10705     * Implementation detail: This method must NOT have any side effects. It would
10706     * ideally be static, but, it requires locks to read system state.
10707     *
10708     * @throws PackageManagerException If the package fails any of the validation checks
10709     */
10710    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10711            final @ScanFlags int scanFlags)
10712                    throws PackageManagerException {
10713        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10714            assertCodePolicy(pkg);
10715        }
10716
10717        if (pkg.applicationInfo.getCodePath() == null ||
10718                pkg.applicationInfo.getResourcePath() == null) {
10719            // Bail out. The resource and code paths haven't been set.
10720            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10721                    "Code and resource paths haven't been set correctly");
10722        }
10723
10724        // Make sure we're not adding any bogus keyset info
10725        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10726        ksms.assertScannedPackageValid(pkg);
10727
10728        synchronized (mPackages) {
10729            // The special "android" package can only be defined once
10730            if (pkg.packageName.equals("android")) {
10731                if (mAndroidApplication != null) {
10732                    Slog.w(TAG, "*************************************************");
10733                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10734                    Slog.w(TAG, " codePath=" + pkg.codePath);
10735                    Slog.w(TAG, "*************************************************");
10736                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10737                            "Core android package being redefined.  Skipping.");
10738                }
10739            }
10740
10741            // A package name must be unique; don't allow duplicates
10742            if (mPackages.containsKey(pkg.packageName)) {
10743                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10744                        "Application package " + pkg.packageName
10745                        + " already installed.  Skipping duplicate.");
10746            }
10747
10748            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10749                // Static libs have a synthetic package name containing the version
10750                // but we still want the base name to be unique.
10751                if (mPackages.containsKey(pkg.manifestPackageName)) {
10752                    throw new PackageManagerException(
10753                            "Duplicate static shared lib provider package");
10754                }
10755
10756                // Static shared libraries should have at least O target SDK
10757                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10758                    throw new PackageManagerException(
10759                            "Packages declaring static-shared libs must target O SDK or higher");
10760                }
10761
10762                // Package declaring static a shared lib cannot be instant apps
10763                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10764                    throw new PackageManagerException(
10765                            "Packages declaring static-shared libs cannot be instant apps");
10766                }
10767
10768                // Package declaring static a shared lib cannot be renamed since the package
10769                // name is synthetic and apps can't code around package manager internals.
10770                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10771                    throw new PackageManagerException(
10772                            "Packages declaring static-shared libs cannot be renamed");
10773                }
10774
10775                // Package declaring static a shared lib cannot declare child packages
10776                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10777                    throw new PackageManagerException(
10778                            "Packages declaring static-shared libs cannot have child packages");
10779                }
10780
10781                // Package declaring static a shared lib cannot declare dynamic libs
10782                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10783                    throw new PackageManagerException(
10784                            "Packages declaring static-shared libs cannot declare dynamic libs");
10785                }
10786
10787                // Package declaring static a shared lib cannot declare shared users
10788                if (pkg.mSharedUserId != null) {
10789                    throw new PackageManagerException(
10790                            "Packages declaring static-shared libs cannot declare shared users");
10791                }
10792
10793                // Static shared libs cannot declare activities
10794                if (!pkg.activities.isEmpty()) {
10795                    throw new PackageManagerException(
10796                            "Static shared libs cannot declare activities");
10797                }
10798
10799                // Static shared libs cannot declare services
10800                if (!pkg.services.isEmpty()) {
10801                    throw new PackageManagerException(
10802                            "Static shared libs cannot declare services");
10803                }
10804
10805                // Static shared libs cannot declare providers
10806                if (!pkg.providers.isEmpty()) {
10807                    throw new PackageManagerException(
10808                            "Static shared libs cannot declare content providers");
10809                }
10810
10811                // Static shared libs cannot declare receivers
10812                if (!pkg.receivers.isEmpty()) {
10813                    throw new PackageManagerException(
10814                            "Static shared libs cannot declare broadcast receivers");
10815                }
10816
10817                // Static shared libs cannot declare permission groups
10818                if (!pkg.permissionGroups.isEmpty()) {
10819                    throw new PackageManagerException(
10820                            "Static shared libs cannot declare permission groups");
10821                }
10822
10823                // Static shared libs cannot declare permissions
10824                if (!pkg.permissions.isEmpty()) {
10825                    throw new PackageManagerException(
10826                            "Static shared libs cannot declare permissions");
10827                }
10828
10829                // Static shared libs cannot declare protected broadcasts
10830                if (pkg.protectedBroadcasts != null) {
10831                    throw new PackageManagerException(
10832                            "Static shared libs cannot declare protected broadcasts");
10833                }
10834
10835                // Static shared libs cannot be overlay targets
10836                if (pkg.mOverlayTarget != null) {
10837                    throw new PackageManagerException(
10838                            "Static shared libs cannot be overlay targets");
10839                }
10840
10841                // The version codes must be ordered as lib versions
10842                long minVersionCode = Long.MIN_VALUE;
10843                long maxVersionCode = Long.MAX_VALUE;
10844
10845                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10846                        pkg.staticSharedLibName);
10847                if (versionedLib != null) {
10848                    final int versionCount = versionedLib.size();
10849                    for (int i = 0; i < versionCount; i++) {
10850                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10851                        final long libVersionCode = libInfo.getDeclaringPackage()
10852                                .getLongVersionCode();
10853                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10854                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10855                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10856                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10857                        } else {
10858                            minVersionCode = maxVersionCode = libVersionCode;
10859                            break;
10860                        }
10861                    }
10862                }
10863                if (pkg.getLongVersionCode() < minVersionCode
10864                        || pkg.getLongVersionCode() > maxVersionCode) {
10865                    throw new PackageManagerException("Static shared"
10866                            + " lib version codes must be ordered as lib versions");
10867                }
10868            }
10869
10870            // Only privileged apps and updated privileged apps can add child packages.
10871            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10872                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10873                    throw new PackageManagerException("Only privileged apps can add child "
10874                            + "packages. Ignoring package " + pkg.packageName);
10875                }
10876                final int childCount = pkg.childPackages.size();
10877                for (int i = 0; i < childCount; i++) {
10878                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10879                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10880                            childPkg.packageName)) {
10881                        throw new PackageManagerException("Can't override child of "
10882                                + "another disabled app. Ignoring package " + pkg.packageName);
10883                    }
10884                }
10885            }
10886
10887            // If we're only installing presumed-existing packages, require that the
10888            // scanned APK is both already known and at the path previously established
10889            // for it.  Previously unknown packages we pick up normally, but if we have an
10890            // a priori expectation about this package's install presence, enforce it.
10891            // With a singular exception for new system packages. When an OTA contains
10892            // a new system package, we allow the codepath to change from a system location
10893            // to the user-installed location. If we don't allow this change, any newer,
10894            // user-installed version of the application will be ignored.
10895            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10896                if (mExpectingBetter.containsKey(pkg.packageName)) {
10897                    logCriticalInfo(Log.WARN,
10898                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10899                } else {
10900                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10901                    if (known != null) {
10902                        if (DEBUG_PACKAGE_SCANNING) {
10903                            Log.d(TAG, "Examining " + pkg.codePath
10904                                    + " and requiring known paths " + known.codePathString
10905                                    + " & " + known.resourcePathString);
10906                        }
10907                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10908                                || !pkg.applicationInfo.getResourcePath().equals(
10909                                        known.resourcePathString)) {
10910                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10911                                    "Application package " + pkg.packageName
10912                                    + " found at " + pkg.applicationInfo.getCodePath()
10913                                    + " but expected at " + known.codePathString
10914                                    + "; ignoring.");
10915                        }
10916                    } else {
10917                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10918                                "Application package " + pkg.packageName
10919                                + " not found; ignoring.");
10920                    }
10921                }
10922            }
10923
10924            // Verify that this new package doesn't have any content providers
10925            // that conflict with existing packages.  Only do this if the
10926            // package isn't already installed, since we don't want to break
10927            // things that are installed.
10928            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10929                final int N = pkg.providers.size();
10930                int i;
10931                for (i=0; i<N; i++) {
10932                    PackageParser.Provider p = pkg.providers.get(i);
10933                    if (p.info.authority != null) {
10934                        String names[] = p.info.authority.split(";");
10935                        for (int j = 0; j < names.length; j++) {
10936                            if (mProvidersByAuthority.containsKey(names[j])) {
10937                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10938                                final String otherPackageName =
10939                                        ((other != null && other.getComponentName() != null) ?
10940                                                other.getComponentName().getPackageName() : "?");
10941                                throw new PackageManagerException(
10942                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10943                                        "Can't install because provider name " + names[j]
10944                                                + " (in package " + pkg.applicationInfo.packageName
10945                                                + ") is already used by " + otherPackageName);
10946                            }
10947                        }
10948                    }
10949                }
10950            }
10951
10952            // Verify that packages sharing a user with a privileged app are marked as privileged.
10953            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
10954                SharedUserSetting sharedUserSetting = null;
10955                try {
10956                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
10957                } catch (PackageManagerException ignore) {}
10958                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
10959                    // Exempt SharedUsers signed with the platform key.
10960                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
10961                    if ((platformPkgSetting.signatures.mSigningDetails
10962                            != PackageParser.SigningDetails.UNKNOWN)
10963                            && (compareSignatures(
10964                                    platformPkgSetting.signatures.mSigningDetails.signatures,
10965                                    pkg.mSigningDetails.signatures)
10966                                            != PackageManager.SIGNATURE_MATCH)) {
10967                        throw new PackageManagerException("Apps that share a user with a " +
10968                                "privileged app must themselves be marked as privileged. " +
10969                                pkg.packageName + " shares privileged user " +
10970                                pkg.mSharedUserId + ".");
10971                    }
10972                }
10973            }
10974
10975            // Apply policies specific for runtime resource overlays (RROs).
10976            if (pkg.mOverlayTarget != null) {
10977                // System overlays have some restrictions on their use of the 'static' state.
10978                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10979                    // We are scanning a system overlay. This can be the first scan of the
10980                    // system/vendor/oem partition, or an update to the system overlay.
10981                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10982                        // This must be an update to a system overlay.
10983                        final PackageSetting previousPkg = assertNotNull(
10984                                mSettings.getPackageLPr(pkg.packageName),
10985                                "previous package state not present");
10986
10987                        // Static overlays cannot be updated.
10988                        if (previousPkg.pkg.mOverlayIsStatic) {
10989                            throw new PackageManagerException("Overlay " + pkg.packageName +
10990                                    " is static and cannot be upgraded.");
10991                        // Non-static overlays cannot be converted to static overlays.
10992                        } else if (pkg.mOverlayIsStatic) {
10993                            throw new PackageManagerException("Overlay " + pkg.packageName +
10994                                    " cannot be upgraded into a static overlay.");
10995                        }
10996                    }
10997                } else {
10998                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
10999                    if (pkg.mOverlayIsStatic) {
11000                        throw new PackageManagerException("Overlay " + pkg.packageName +
11001                                " is static but not pre-installed.");
11002                    }
11003
11004                    // The only case where we allow installation of a non-system overlay is when
11005                    // its signature is signed with the platform certificate.
11006                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11007                    if ((platformPkgSetting.signatures.mSigningDetails
11008                            != PackageParser.SigningDetails.UNKNOWN)
11009                            && (compareSignatures(
11010                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11011                                    pkg.mSigningDetails.signatures)
11012                                            != PackageManager.SIGNATURE_MATCH)) {
11013                        throw new PackageManagerException("Overlay " + pkg.packageName +
11014                                " must be signed with the platform certificate.");
11015                    }
11016                }
11017            }
11018        }
11019    }
11020
11021    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11022            int type, String declaringPackageName, long declaringVersionCode) {
11023        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11024        if (versionedLib == null) {
11025            versionedLib = new LongSparseArray<>();
11026            mSharedLibraries.put(name, versionedLib);
11027            if (type == SharedLibraryInfo.TYPE_STATIC) {
11028                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11029            }
11030        } else if (versionedLib.indexOfKey(version) >= 0) {
11031            return false;
11032        }
11033        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11034                version, type, declaringPackageName, declaringVersionCode);
11035        versionedLib.put(version, libEntry);
11036        return true;
11037    }
11038
11039    private boolean removeSharedLibraryLPw(String name, long version) {
11040        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11041        if (versionedLib == null) {
11042            return false;
11043        }
11044        final int libIdx = versionedLib.indexOfKey(version);
11045        if (libIdx < 0) {
11046            return false;
11047        }
11048        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11049        versionedLib.remove(version);
11050        if (versionedLib.size() <= 0) {
11051            mSharedLibraries.remove(name);
11052            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11053                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11054                        .getPackageName());
11055            }
11056        }
11057        return true;
11058    }
11059
11060    /**
11061     * Adds a scanned package to the system. When this method is finished, the package will
11062     * be available for query, resolution, etc...
11063     */
11064    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11065            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
11066        final String pkgName = pkg.packageName;
11067        if (mCustomResolverComponentName != null &&
11068                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11069            setUpCustomResolverActivity(pkg);
11070        }
11071
11072        if (pkg.packageName.equals("android")) {
11073            synchronized (mPackages) {
11074                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11075                    // Set up information for our fall-back user intent resolution activity.
11076                    mPlatformPackage = pkg;
11077                    pkg.mVersionCode = mSdkVersion;
11078                    pkg.mVersionCodeMajor = 0;
11079                    mAndroidApplication = pkg.applicationInfo;
11080                    if (!mResolverReplaced) {
11081                        mResolveActivity.applicationInfo = mAndroidApplication;
11082                        mResolveActivity.name = ResolverActivity.class.getName();
11083                        mResolveActivity.packageName = mAndroidApplication.packageName;
11084                        mResolveActivity.processName = "system:ui";
11085                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11086                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11087                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11088                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11089                        mResolveActivity.exported = true;
11090                        mResolveActivity.enabled = true;
11091                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11092                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11093                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11094                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11095                                | ActivityInfo.CONFIG_ORIENTATION
11096                                | ActivityInfo.CONFIG_KEYBOARD
11097                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11098                        mResolveInfo.activityInfo = mResolveActivity;
11099                        mResolveInfo.priority = 0;
11100                        mResolveInfo.preferredOrder = 0;
11101                        mResolveInfo.match = 0;
11102                        mResolveComponentName = new ComponentName(
11103                                mAndroidApplication.packageName, mResolveActivity.name);
11104                    }
11105                }
11106            }
11107        }
11108
11109        ArrayList<PackageParser.Package> clientLibPkgs = null;
11110        // writer
11111        synchronized (mPackages) {
11112            boolean hasStaticSharedLibs = false;
11113
11114            // Any app can add new static shared libraries
11115            if (pkg.staticSharedLibName != null) {
11116                // Static shared libs don't allow renaming as they have synthetic package
11117                // names to allow install of multiple versions, so use name from manifest.
11118                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11119                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11120                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11121                    hasStaticSharedLibs = true;
11122                } else {
11123                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11124                                + pkg.staticSharedLibName + " already exists; skipping");
11125                }
11126                // Static shared libs cannot be updated once installed since they
11127                // use synthetic package name which includes the version code, so
11128                // not need to update other packages's shared lib dependencies.
11129            }
11130
11131            if (!hasStaticSharedLibs
11132                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11133                // Only system apps can add new dynamic shared libraries.
11134                if (pkg.libraryNames != null) {
11135                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11136                        String name = pkg.libraryNames.get(i);
11137                        boolean allowed = false;
11138                        if (pkg.isUpdatedSystemApp()) {
11139                            // New library entries can only be added through the
11140                            // system image.  This is important to get rid of a lot
11141                            // of nasty edge cases: for example if we allowed a non-
11142                            // system update of the app to add a library, then uninstalling
11143                            // the update would make the library go away, and assumptions
11144                            // we made such as through app install filtering would now
11145                            // have allowed apps on the device which aren't compatible
11146                            // with it.  Better to just have the restriction here, be
11147                            // conservative, and create many fewer cases that can negatively
11148                            // impact the user experience.
11149                            final PackageSetting sysPs = mSettings
11150                                    .getDisabledSystemPkgLPr(pkg.packageName);
11151                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11152                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11153                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11154                                        allowed = true;
11155                                        break;
11156                                    }
11157                                }
11158                            }
11159                        } else {
11160                            allowed = true;
11161                        }
11162                        if (allowed) {
11163                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11164                                    SharedLibraryInfo.VERSION_UNDEFINED,
11165                                    SharedLibraryInfo.TYPE_DYNAMIC,
11166                                    pkg.packageName, pkg.getLongVersionCode())) {
11167                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11168                                        + name + " already exists; skipping");
11169                            }
11170                        } else {
11171                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11172                                    + name + " that is not declared on system image; skipping");
11173                        }
11174                    }
11175
11176                    if ((scanFlags & SCAN_BOOTING) == 0) {
11177                        // If we are not booting, we need to update any applications
11178                        // that are clients of our shared library.  If we are booting,
11179                        // this will all be done once the scan is complete.
11180                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11181                    }
11182                }
11183            }
11184        }
11185
11186        if ((scanFlags & SCAN_BOOTING) != 0) {
11187            // No apps can run during boot scan, so they don't need to be frozen
11188        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11189            // Caller asked to not kill app, so it's probably not frozen
11190        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11191            // Caller asked us to ignore frozen check for some reason; they
11192            // probably didn't know the package name
11193        } else {
11194            // We're doing major surgery on this package, so it better be frozen
11195            // right now to keep it from launching
11196            checkPackageFrozen(pkgName);
11197        }
11198
11199        // Also need to kill any apps that are dependent on the library.
11200        if (clientLibPkgs != null) {
11201            for (int i=0; i<clientLibPkgs.size(); i++) {
11202                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11203                killApplication(clientPkg.applicationInfo.packageName,
11204                        clientPkg.applicationInfo.uid, "update lib");
11205            }
11206        }
11207
11208        // writer
11209        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11210
11211        synchronized (mPackages) {
11212            // We don't expect installation to fail beyond this point
11213
11214            // Add the new setting to mSettings
11215            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11216            // Add the new setting to mPackages
11217            mPackages.put(pkg.applicationInfo.packageName, pkg);
11218            // Make sure we don't accidentally delete its data.
11219            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11220            while (iter.hasNext()) {
11221                PackageCleanItem item = iter.next();
11222                if (pkgName.equals(item.packageName)) {
11223                    iter.remove();
11224                }
11225            }
11226
11227            // Add the package's KeySets to the global KeySetManagerService
11228            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11229            ksms.addScannedPackageLPw(pkg);
11230
11231            int N = pkg.providers.size();
11232            StringBuilder r = null;
11233            int i;
11234            for (i=0; i<N; i++) {
11235                PackageParser.Provider p = pkg.providers.get(i);
11236                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11237                        p.info.processName);
11238                mProviders.addProvider(p);
11239                p.syncable = p.info.isSyncable;
11240                if (p.info.authority != null) {
11241                    String names[] = p.info.authority.split(";");
11242                    p.info.authority = null;
11243                    for (int j = 0; j < names.length; j++) {
11244                        if (j == 1 && p.syncable) {
11245                            // We only want the first authority for a provider to possibly be
11246                            // syncable, so if we already added this provider using a different
11247                            // authority clear the syncable flag. We copy the provider before
11248                            // changing it because the mProviders object contains a reference
11249                            // to a provider that we don't want to change.
11250                            // Only do this for the second authority since the resulting provider
11251                            // object can be the same for all future authorities for this provider.
11252                            p = new PackageParser.Provider(p);
11253                            p.syncable = false;
11254                        }
11255                        if (!mProvidersByAuthority.containsKey(names[j])) {
11256                            mProvidersByAuthority.put(names[j], p);
11257                            if (p.info.authority == null) {
11258                                p.info.authority = names[j];
11259                            } else {
11260                                p.info.authority = p.info.authority + ";" + names[j];
11261                            }
11262                            if (DEBUG_PACKAGE_SCANNING) {
11263                                if (chatty)
11264                                    Log.d(TAG, "Registered content provider: " + names[j]
11265                                            + ", className = " + p.info.name + ", isSyncable = "
11266                                            + p.info.isSyncable);
11267                            }
11268                        } else {
11269                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11270                            Slog.w(TAG, "Skipping provider name " + names[j] +
11271                                    " (in package " + pkg.applicationInfo.packageName +
11272                                    "): name already used by "
11273                                    + ((other != null && other.getComponentName() != null)
11274                                            ? other.getComponentName().getPackageName() : "?"));
11275                        }
11276                    }
11277                }
11278                if (chatty) {
11279                    if (r == null) {
11280                        r = new StringBuilder(256);
11281                    } else {
11282                        r.append(' ');
11283                    }
11284                    r.append(p.info.name);
11285                }
11286            }
11287            if (r != null) {
11288                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11289            }
11290
11291            N = pkg.services.size();
11292            r = null;
11293            for (i=0; i<N; i++) {
11294                PackageParser.Service s = pkg.services.get(i);
11295                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11296                        s.info.processName);
11297                mServices.addService(s);
11298                if (chatty) {
11299                    if (r == null) {
11300                        r = new StringBuilder(256);
11301                    } else {
11302                        r.append(' ');
11303                    }
11304                    r.append(s.info.name);
11305                }
11306            }
11307            if (r != null) {
11308                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11309            }
11310
11311            N = pkg.receivers.size();
11312            r = null;
11313            for (i=0; i<N; i++) {
11314                PackageParser.Activity a = pkg.receivers.get(i);
11315                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11316                        a.info.processName);
11317                mReceivers.addActivity(a, "receiver");
11318                if (chatty) {
11319                    if (r == null) {
11320                        r = new StringBuilder(256);
11321                    } else {
11322                        r.append(' ');
11323                    }
11324                    r.append(a.info.name);
11325                }
11326            }
11327            if (r != null) {
11328                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11329            }
11330
11331            N = pkg.activities.size();
11332            r = null;
11333            for (i=0; i<N; i++) {
11334                PackageParser.Activity a = pkg.activities.get(i);
11335                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11336                        a.info.processName);
11337                mActivities.addActivity(a, "activity");
11338                if (chatty) {
11339                    if (r == null) {
11340                        r = new StringBuilder(256);
11341                    } else {
11342                        r.append(' ');
11343                    }
11344                    r.append(a.info.name);
11345                }
11346            }
11347            if (r != null) {
11348                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11349            }
11350
11351            // Don't allow ephemeral applications to define new permissions groups.
11352            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11353                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11354                        + " ignored: instant apps cannot define new permission groups.");
11355            } else {
11356                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11357            }
11358
11359            // Don't allow ephemeral applications to define new permissions.
11360            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11361                Slog.w(TAG, "Permissions from package " + pkg.packageName
11362                        + " ignored: instant apps cannot define new permissions.");
11363            } else {
11364                mPermissionManager.addAllPermissions(pkg, chatty);
11365            }
11366
11367            N = pkg.instrumentation.size();
11368            r = null;
11369            for (i=0; i<N; i++) {
11370                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11371                a.info.packageName = pkg.applicationInfo.packageName;
11372                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11373                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11374                a.info.splitNames = pkg.splitNames;
11375                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11376                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11377                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11378                a.info.dataDir = pkg.applicationInfo.dataDir;
11379                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11380                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11381                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11382                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11383                mInstrumentation.put(a.getComponentName(), a);
11384                if (chatty) {
11385                    if (r == null) {
11386                        r = new StringBuilder(256);
11387                    } else {
11388                        r.append(' ');
11389                    }
11390                    r.append(a.info.name);
11391                }
11392            }
11393            if (r != null) {
11394                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11395            }
11396
11397            if (pkg.protectedBroadcasts != null) {
11398                N = pkg.protectedBroadcasts.size();
11399                synchronized (mProtectedBroadcasts) {
11400                    for (i = 0; i < N; i++) {
11401                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11402                    }
11403                }
11404            }
11405        }
11406
11407        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11408    }
11409
11410    /**
11411     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11412     * is derived purely on the basis of the contents of {@code scanFile} and
11413     * {@code cpuAbiOverride}.
11414     *
11415     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11416     */
11417    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11418            boolean extractLibs)
11419                    throws PackageManagerException {
11420        // Give ourselves some initial paths; we'll come back for another
11421        // pass once we've determined ABI below.
11422        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11423
11424        // We would never need to extract libs for forward-locked and external packages,
11425        // since the container service will do it for us. We shouldn't attempt to
11426        // extract libs from system app when it was not updated.
11427        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11428                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11429            extractLibs = false;
11430        }
11431
11432        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11433        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11434
11435        NativeLibraryHelper.Handle handle = null;
11436        try {
11437            handle = NativeLibraryHelper.Handle.create(pkg);
11438            // TODO(multiArch): This can be null for apps that didn't go through the
11439            // usual installation process. We can calculate it again, like we
11440            // do during install time.
11441            //
11442            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11443            // unnecessary.
11444            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11445
11446            // Null out the abis so that they can be recalculated.
11447            pkg.applicationInfo.primaryCpuAbi = null;
11448            pkg.applicationInfo.secondaryCpuAbi = null;
11449            if (isMultiArch(pkg.applicationInfo)) {
11450                // Warn if we've set an abiOverride for multi-lib packages..
11451                // By definition, we need to copy both 32 and 64 bit libraries for
11452                // such packages.
11453                if (pkg.cpuAbiOverride != null
11454                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11455                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11456                }
11457
11458                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11459                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11460                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11461                    if (extractLibs) {
11462                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11463                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11464                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11465                                useIsaSpecificSubdirs);
11466                    } else {
11467                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11468                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11469                    }
11470                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11471                }
11472
11473                // Shared library native code should be in the APK zip aligned
11474                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11475                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11476                            "Shared library native lib extraction not supported");
11477                }
11478
11479                maybeThrowExceptionForMultiArchCopy(
11480                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11481
11482                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11483                    if (extractLibs) {
11484                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11485                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11486                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11487                                useIsaSpecificSubdirs);
11488                    } else {
11489                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11490                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11491                    }
11492                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11493                }
11494
11495                maybeThrowExceptionForMultiArchCopy(
11496                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11497
11498                if (abi64 >= 0) {
11499                    // Shared library native libs should be in the APK zip aligned
11500                    if (extractLibs && pkg.isLibrary()) {
11501                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11502                                "Shared library native lib extraction not supported");
11503                    }
11504                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11505                }
11506
11507                if (abi32 >= 0) {
11508                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11509                    if (abi64 >= 0) {
11510                        if (pkg.use32bitAbi) {
11511                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11512                            pkg.applicationInfo.primaryCpuAbi = abi;
11513                        } else {
11514                            pkg.applicationInfo.secondaryCpuAbi = abi;
11515                        }
11516                    } else {
11517                        pkg.applicationInfo.primaryCpuAbi = abi;
11518                    }
11519                }
11520            } else {
11521                String[] abiList = (cpuAbiOverride != null) ?
11522                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11523
11524                // Enable gross and lame hacks for apps that are built with old
11525                // SDK tools. We must scan their APKs for renderscript bitcode and
11526                // not launch them if it's present. Don't bother checking on devices
11527                // that don't have 64 bit support.
11528                boolean needsRenderScriptOverride = false;
11529                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11530                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11531                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11532                    needsRenderScriptOverride = true;
11533                }
11534
11535                final int copyRet;
11536                if (extractLibs) {
11537                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11538                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11539                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11540                } else {
11541                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11542                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11543                }
11544                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11545
11546                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11547                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11548                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11549                }
11550
11551                if (copyRet >= 0) {
11552                    // Shared libraries that have native libs must be multi-architecture
11553                    if (pkg.isLibrary()) {
11554                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11555                                "Shared library with native libs must be multiarch");
11556                    }
11557                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11558                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11559                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11560                } else if (needsRenderScriptOverride) {
11561                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11562                }
11563            }
11564        } catch (IOException ioe) {
11565            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11566        } finally {
11567            IoUtils.closeQuietly(handle);
11568        }
11569
11570        // Now that we've calculated the ABIs and determined if it's an internal app,
11571        // we will go ahead and populate the nativeLibraryPath.
11572        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11573    }
11574
11575    /**
11576     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11577     * i.e, so that all packages can be run inside a single process if required.
11578     *
11579     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11580     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11581     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11582     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11583     * updating a package that belongs to a shared user.
11584     *
11585     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11586     * adds unnecessary complexity.
11587     */
11588    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11589            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11590        List<String> changedAbiCodePath = null;
11591        String requiredInstructionSet = null;
11592        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11593            requiredInstructionSet = VMRuntime.getInstructionSet(
11594                     scannedPackage.applicationInfo.primaryCpuAbi);
11595        }
11596
11597        PackageSetting requirer = null;
11598        for (PackageSetting ps : packagesForUser) {
11599            // If packagesForUser contains scannedPackage, we skip it. This will happen
11600            // when scannedPackage is an update of an existing package. Without this check,
11601            // we will never be able to change the ABI of any package belonging to a shared
11602            // user, even if it's compatible with other packages.
11603            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11604                if (ps.primaryCpuAbiString == null) {
11605                    continue;
11606                }
11607
11608                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11609                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11610                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11611                    // this but there's not much we can do.
11612                    String errorMessage = "Instruction set mismatch, "
11613                            + ((requirer == null) ? "[caller]" : requirer)
11614                            + " requires " + requiredInstructionSet + " whereas " + ps
11615                            + " requires " + instructionSet;
11616                    Slog.w(TAG, errorMessage);
11617                }
11618
11619                if (requiredInstructionSet == null) {
11620                    requiredInstructionSet = instructionSet;
11621                    requirer = ps;
11622                }
11623            }
11624        }
11625
11626        if (requiredInstructionSet != null) {
11627            String adjustedAbi;
11628            if (requirer != null) {
11629                // requirer != null implies that either scannedPackage was null or that scannedPackage
11630                // did not require an ABI, in which case we have to adjust scannedPackage to match
11631                // the ABI of the set (which is the same as requirer's ABI)
11632                adjustedAbi = requirer.primaryCpuAbiString;
11633                if (scannedPackage != null) {
11634                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11635                }
11636            } else {
11637                // requirer == null implies that we're updating all ABIs in the set to
11638                // match scannedPackage.
11639                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11640            }
11641
11642            for (PackageSetting ps : packagesForUser) {
11643                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11644                    if (ps.primaryCpuAbiString != null) {
11645                        continue;
11646                    }
11647
11648                    ps.primaryCpuAbiString = adjustedAbi;
11649                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11650                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11651                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11652                        if (DEBUG_ABI_SELECTION) {
11653                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11654                                    + " (requirer="
11655                                    + (requirer != null ? requirer.pkg : "null")
11656                                    + ", scannedPackage="
11657                                    + (scannedPackage != null ? scannedPackage : "null")
11658                                    + ")");
11659                        }
11660                        if (changedAbiCodePath == null) {
11661                            changedAbiCodePath = new ArrayList<>();
11662                        }
11663                        changedAbiCodePath.add(ps.codePathString);
11664                    }
11665                }
11666            }
11667        }
11668        return changedAbiCodePath;
11669    }
11670
11671    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11672        synchronized (mPackages) {
11673            mResolverReplaced = true;
11674            // Set up information for custom user intent resolution activity.
11675            mResolveActivity.applicationInfo = pkg.applicationInfo;
11676            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11677            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11678            mResolveActivity.processName = pkg.applicationInfo.packageName;
11679            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11680            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11681                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11682            mResolveActivity.theme = 0;
11683            mResolveActivity.exported = true;
11684            mResolveActivity.enabled = true;
11685            mResolveInfo.activityInfo = mResolveActivity;
11686            mResolveInfo.priority = 0;
11687            mResolveInfo.preferredOrder = 0;
11688            mResolveInfo.match = 0;
11689            mResolveComponentName = mCustomResolverComponentName;
11690            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11691                    mResolveComponentName);
11692        }
11693    }
11694
11695    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11696        if (installerActivity == null) {
11697            if (DEBUG_INSTANT) {
11698                Slog.d(TAG, "Clear ephemeral installer activity");
11699            }
11700            mInstantAppInstallerActivity = null;
11701            return;
11702        }
11703
11704        if (DEBUG_INSTANT) {
11705            Slog.d(TAG, "Set ephemeral installer activity: "
11706                    + installerActivity.getComponentName());
11707        }
11708        // Set up information for ephemeral installer activity
11709        mInstantAppInstallerActivity = installerActivity;
11710        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11711                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11712        mInstantAppInstallerActivity.exported = true;
11713        mInstantAppInstallerActivity.enabled = true;
11714        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11715        mInstantAppInstallerInfo.priority = 1;
11716        mInstantAppInstallerInfo.preferredOrder = 1;
11717        mInstantAppInstallerInfo.isDefault = true;
11718        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11719                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11720    }
11721
11722    private static String calculateBundledApkRoot(final String codePathString) {
11723        final File codePath = new File(codePathString);
11724        final File codeRoot;
11725        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11726            codeRoot = Environment.getRootDirectory();
11727        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11728            codeRoot = Environment.getOemDirectory();
11729        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11730            codeRoot = Environment.getVendorDirectory();
11731        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11732            codeRoot = Environment.getProductDirectory();
11733        } else {
11734            // Unrecognized code path; take its top real segment as the apk root:
11735            // e.g. /something/app/blah.apk => /something
11736            try {
11737                File f = codePath.getCanonicalFile();
11738                File parent = f.getParentFile();    // non-null because codePath is a file
11739                File tmp;
11740                while ((tmp = parent.getParentFile()) != null) {
11741                    f = parent;
11742                    parent = tmp;
11743                }
11744                codeRoot = f;
11745                Slog.w(TAG, "Unrecognized code path "
11746                        + codePath + " - using " + codeRoot);
11747            } catch (IOException e) {
11748                // Can't canonicalize the code path -- shenanigans?
11749                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11750                return Environment.getRootDirectory().getPath();
11751            }
11752        }
11753        return codeRoot.getPath();
11754    }
11755
11756    /**
11757     * Derive and set the location of native libraries for the given package,
11758     * which varies depending on where and how the package was installed.
11759     */
11760    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11761        final ApplicationInfo info = pkg.applicationInfo;
11762        final String codePath = pkg.codePath;
11763        final File codeFile = new File(codePath);
11764        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11765        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11766
11767        info.nativeLibraryRootDir = null;
11768        info.nativeLibraryRootRequiresIsa = false;
11769        info.nativeLibraryDir = null;
11770        info.secondaryNativeLibraryDir = null;
11771
11772        if (isApkFile(codeFile)) {
11773            // Monolithic install
11774            if (bundledApp) {
11775                // If "/system/lib64/apkname" exists, assume that is the per-package
11776                // native library directory to use; otherwise use "/system/lib/apkname".
11777                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11778                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11779                        getPrimaryInstructionSet(info));
11780
11781                // This is a bundled system app so choose the path based on the ABI.
11782                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11783                // is just the default path.
11784                final String apkName = deriveCodePathName(codePath);
11785                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11786                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11787                        apkName).getAbsolutePath();
11788
11789                if (info.secondaryCpuAbi != null) {
11790                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11791                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11792                            secondaryLibDir, apkName).getAbsolutePath();
11793                }
11794            } else if (asecApp) {
11795                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11796                        .getAbsolutePath();
11797            } else {
11798                final String apkName = deriveCodePathName(codePath);
11799                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11800                        .getAbsolutePath();
11801            }
11802
11803            info.nativeLibraryRootRequiresIsa = false;
11804            info.nativeLibraryDir = info.nativeLibraryRootDir;
11805        } else {
11806            // Cluster install
11807            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11808            info.nativeLibraryRootRequiresIsa = true;
11809
11810            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11811                    getPrimaryInstructionSet(info)).getAbsolutePath();
11812
11813            if (info.secondaryCpuAbi != null) {
11814                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11815                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11816            }
11817        }
11818    }
11819
11820    /**
11821     * Calculate the abis and roots for a bundled app. These can uniquely
11822     * be determined from the contents of the system partition, i.e whether
11823     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11824     * of this information, and instead assume that the system was built
11825     * sensibly.
11826     */
11827    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11828                                           PackageSetting pkgSetting) {
11829        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11830
11831        // If "/system/lib64/apkname" exists, assume that is the per-package
11832        // native library directory to use; otherwise use "/system/lib/apkname".
11833        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11834        setBundledAppAbi(pkg, apkRoot, apkName);
11835        // pkgSetting might be null during rescan following uninstall of updates
11836        // to a bundled app, so accommodate that possibility.  The settings in
11837        // that case will be established later from the parsed package.
11838        //
11839        // If the settings aren't null, sync them up with what we've just derived.
11840        // note that apkRoot isn't stored in the package settings.
11841        if (pkgSetting != null) {
11842            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11843            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11844        }
11845    }
11846
11847    /**
11848     * Deduces the ABI of a bundled app and sets the relevant fields on the
11849     * parsed pkg object.
11850     *
11851     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11852     *        under which system libraries are installed.
11853     * @param apkName the name of the installed package.
11854     */
11855    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11856        final File codeFile = new File(pkg.codePath);
11857
11858        final boolean has64BitLibs;
11859        final boolean has32BitLibs;
11860        if (isApkFile(codeFile)) {
11861            // Monolithic install
11862            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11863            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11864        } else {
11865            // Cluster install
11866            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11867            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11868                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11869                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11870                has64BitLibs = (new File(rootDir, isa)).exists();
11871            } else {
11872                has64BitLibs = false;
11873            }
11874            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11875                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11876                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11877                has32BitLibs = (new File(rootDir, isa)).exists();
11878            } else {
11879                has32BitLibs = false;
11880            }
11881        }
11882
11883        if (has64BitLibs && !has32BitLibs) {
11884            // The package has 64 bit libs, but not 32 bit libs. Its primary
11885            // ABI should be 64 bit. We can safely assume here that the bundled
11886            // native libraries correspond to the most preferred ABI in the list.
11887
11888            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11889            pkg.applicationInfo.secondaryCpuAbi = null;
11890        } else if (has32BitLibs && !has64BitLibs) {
11891            // The package has 32 bit libs but not 64 bit libs. Its primary
11892            // ABI should be 32 bit.
11893
11894            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11895            pkg.applicationInfo.secondaryCpuAbi = null;
11896        } else if (has32BitLibs && has64BitLibs) {
11897            // The application has both 64 and 32 bit bundled libraries. We check
11898            // here that the app declares multiArch support, and warn if it doesn't.
11899            //
11900            // We will be lenient here and record both ABIs. The primary will be the
11901            // ABI that's higher on the list, i.e, a device that's configured to prefer
11902            // 64 bit apps will see a 64 bit primary ABI,
11903
11904            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11905                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11906            }
11907
11908            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11909                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11910                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11911            } else {
11912                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11913                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11914            }
11915        } else {
11916            pkg.applicationInfo.primaryCpuAbi = null;
11917            pkg.applicationInfo.secondaryCpuAbi = null;
11918        }
11919    }
11920
11921    private void killApplication(String pkgName, int appId, String reason) {
11922        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11923    }
11924
11925    private void killApplication(String pkgName, int appId, int userId, String reason) {
11926        // Request the ActivityManager to kill the process(only for existing packages)
11927        // so that we do not end up in a confused state while the user is still using the older
11928        // version of the application while the new one gets installed.
11929        final long token = Binder.clearCallingIdentity();
11930        try {
11931            IActivityManager am = ActivityManager.getService();
11932            if (am != null) {
11933                try {
11934                    am.killApplication(pkgName, appId, userId, reason);
11935                } catch (RemoteException e) {
11936                }
11937            }
11938        } finally {
11939            Binder.restoreCallingIdentity(token);
11940        }
11941    }
11942
11943    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11944        // Remove the parent package setting
11945        PackageSetting ps = (PackageSetting) pkg.mExtras;
11946        if (ps != null) {
11947            removePackageLI(ps, chatty);
11948        }
11949        // Remove the child package setting
11950        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11951        for (int i = 0; i < childCount; i++) {
11952            PackageParser.Package childPkg = pkg.childPackages.get(i);
11953            ps = (PackageSetting) childPkg.mExtras;
11954            if (ps != null) {
11955                removePackageLI(ps, chatty);
11956            }
11957        }
11958    }
11959
11960    void removePackageLI(PackageSetting ps, boolean chatty) {
11961        if (DEBUG_INSTALL) {
11962            if (chatty)
11963                Log.d(TAG, "Removing package " + ps.name);
11964        }
11965
11966        // writer
11967        synchronized (mPackages) {
11968            mPackages.remove(ps.name);
11969            final PackageParser.Package pkg = ps.pkg;
11970            if (pkg != null) {
11971                cleanPackageDataStructuresLILPw(pkg, chatty);
11972            }
11973        }
11974    }
11975
11976    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11977        if (DEBUG_INSTALL) {
11978            if (chatty)
11979                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11980        }
11981
11982        // writer
11983        synchronized (mPackages) {
11984            // Remove the parent package
11985            mPackages.remove(pkg.applicationInfo.packageName);
11986            cleanPackageDataStructuresLILPw(pkg, chatty);
11987
11988            // Remove the child packages
11989            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11990            for (int i = 0; i < childCount; i++) {
11991                PackageParser.Package childPkg = pkg.childPackages.get(i);
11992                mPackages.remove(childPkg.applicationInfo.packageName);
11993                cleanPackageDataStructuresLILPw(childPkg, chatty);
11994            }
11995        }
11996    }
11997
11998    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11999        int N = pkg.providers.size();
12000        StringBuilder r = null;
12001        int i;
12002        for (i=0; i<N; i++) {
12003            PackageParser.Provider p = pkg.providers.get(i);
12004            mProviders.removeProvider(p);
12005            if (p.info.authority == null) {
12006
12007                /* There was another ContentProvider with this authority when
12008                 * this app was installed so this authority is null,
12009                 * Ignore it as we don't have to unregister the provider.
12010                 */
12011                continue;
12012            }
12013            String names[] = p.info.authority.split(";");
12014            for (int j = 0; j < names.length; j++) {
12015                if (mProvidersByAuthority.get(names[j]) == p) {
12016                    mProvidersByAuthority.remove(names[j]);
12017                    if (DEBUG_REMOVE) {
12018                        if (chatty)
12019                            Log.d(TAG, "Unregistered content provider: " + names[j]
12020                                    + ", className = " + p.info.name + ", isSyncable = "
12021                                    + p.info.isSyncable);
12022                    }
12023                }
12024            }
12025            if (DEBUG_REMOVE && chatty) {
12026                if (r == null) {
12027                    r = new StringBuilder(256);
12028                } else {
12029                    r.append(' ');
12030                }
12031                r.append(p.info.name);
12032            }
12033        }
12034        if (r != null) {
12035            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12036        }
12037
12038        N = pkg.services.size();
12039        r = null;
12040        for (i=0; i<N; i++) {
12041            PackageParser.Service s = pkg.services.get(i);
12042            mServices.removeService(s);
12043            if (chatty) {
12044                if (r == null) {
12045                    r = new StringBuilder(256);
12046                } else {
12047                    r.append(' ');
12048                }
12049                r.append(s.info.name);
12050            }
12051        }
12052        if (r != null) {
12053            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12054        }
12055
12056        N = pkg.receivers.size();
12057        r = null;
12058        for (i=0; i<N; i++) {
12059            PackageParser.Activity a = pkg.receivers.get(i);
12060            mReceivers.removeActivity(a, "receiver");
12061            if (DEBUG_REMOVE && chatty) {
12062                if (r == null) {
12063                    r = new StringBuilder(256);
12064                } else {
12065                    r.append(' ');
12066                }
12067                r.append(a.info.name);
12068            }
12069        }
12070        if (r != null) {
12071            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12072        }
12073
12074        N = pkg.activities.size();
12075        r = null;
12076        for (i=0; i<N; i++) {
12077            PackageParser.Activity a = pkg.activities.get(i);
12078            mActivities.removeActivity(a, "activity");
12079            if (DEBUG_REMOVE && chatty) {
12080                if (r == null) {
12081                    r = new StringBuilder(256);
12082                } else {
12083                    r.append(' ');
12084                }
12085                r.append(a.info.name);
12086            }
12087        }
12088        if (r != null) {
12089            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12090        }
12091
12092        mPermissionManager.removeAllPermissions(pkg, chatty);
12093
12094        N = pkg.instrumentation.size();
12095        r = null;
12096        for (i=0; i<N; i++) {
12097            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12098            mInstrumentation.remove(a.getComponentName());
12099            if (DEBUG_REMOVE && chatty) {
12100                if (r == null) {
12101                    r = new StringBuilder(256);
12102                } else {
12103                    r.append(' ');
12104                }
12105                r.append(a.info.name);
12106            }
12107        }
12108        if (r != null) {
12109            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12110        }
12111
12112        r = null;
12113        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12114            // Only system apps can hold shared libraries.
12115            if (pkg.libraryNames != null) {
12116                for (i = 0; i < pkg.libraryNames.size(); i++) {
12117                    String name = pkg.libraryNames.get(i);
12118                    if (removeSharedLibraryLPw(name, 0)) {
12119                        if (DEBUG_REMOVE && chatty) {
12120                            if (r == null) {
12121                                r = new StringBuilder(256);
12122                            } else {
12123                                r.append(' ');
12124                            }
12125                            r.append(name);
12126                        }
12127                    }
12128                }
12129            }
12130        }
12131
12132        r = null;
12133
12134        // Any package can hold static shared libraries.
12135        if (pkg.staticSharedLibName != null) {
12136            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12137                if (DEBUG_REMOVE && chatty) {
12138                    if (r == null) {
12139                        r = new StringBuilder(256);
12140                    } else {
12141                        r.append(' ');
12142                    }
12143                    r.append(pkg.staticSharedLibName);
12144                }
12145            }
12146        }
12147
12148        if (r != null) {
12149            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12150        }
12151    }
12152
12153
12154    final class ActivityIntentResolver
12155            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12156        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12157                boolean defaultOnly, int userId) {
12158            if (!sUserManager.exists(userId)) return null;
12159            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12160            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12161        }
12162
12163        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12164                int userId) {
12165            if (!sUserManager.exists(userId)) return null;
12166            mFlags = flags;
12167            return super.queryIntent(intent, resolvedType,
12168                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12169                    userId);
12170        }
12171
12172        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12173                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12174            if (!sUserManager.exists(userId)) return null;
12175            if (packageActivities == null) {
12176                return null;
12177            }
12178            mFlags = flags;
12179            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12180            final int N = packageActivities.size();
12181            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12182                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12183
12184            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12185            for (int i = 0; i < N; ++i) {
12186                intentFilters = packageActivities.get(i).intents;
12187                if (intentFilters != null && intentFilters.size() > 0) {
12188                    PackageParser.ActivityIntentInfo[] array =
12189                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12190                    intentFilters.toArray(array);
12191                    listCut.add(array);
12192                }
12193            }
12194            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12195        }
12196
12197        /**
12198         * Finds a privileged activity that matches the specified activity names.
12199         */
12200        private PackageParser.Activity findMatchingActivity(
12201                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12202            for (PackageParser.Activity sysActivity : activityList) {
12203                if (sysActivity.info.name.equals(activityInfo.name)) {
12204                    return sysActivity;
12205                }
12206                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12207                    return sysActivity;
12208                }
12209                if (sysActivity.info.targetActivity != null) {
12210                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12211                        return sysActivity;
12212                    }
12213                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12214                        return sysActivity;
12215                    }
12216                }
12217            }
12218            return null;
12219        }
12220
12221        public class IterGenerator<E> {
12222            public Iterator<E> generate(ActivityIntentInfo info) {
12223                return null;
12224            }
12225        }
12226
12227        public class ActionIterGenerator extends IterGenerator<String> {
12228            @Override
12229            public Iterator<String> generate(ActivityIntentInfo info) {
12230                return info.actionsIterator();
12231            }
12232        }
12233
12234        public class CategoriesIterGenerator extends IterGenerator<String> {
12235            @Override
12236            public Iterator<String> generate(ActivityIntentInfo info) {
12237                return info.categoriesIterator();
12238            }
12239        }
12240
12241        public class SchemesIterGenerator extends IterGenerator<String> {
12242            @Override
12243            public Iterator<String> generate(ActivityIntentInfo info) {
12244                return info.schemesIterator();
12245            }
12246        }
12247
12248        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12249            @Override
12250            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12251                return info.authoritiesIterator();
12252            }
12253        }
12254
12255        /**
12256         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12257         * MODIFIED. Do not pass in a list that should not be changed.
12258         */
12259        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12260                IterGenerator<T> generator, Iterator<T> searchIterator) {
12261            // loop through the set of actions; every one must be found in the intent filter
12262            while (searchIterator.hasNext()) {
12263                // we must have at least one filter in the list to consider a match
12264                if (intentList.size() == 0) {
12265                    break;
12266                }
12267
12268                final T searchAction = searchIterator.next();
12269
12270                // loop through the set of intent filters
12271                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12272                while (intentIter.hasNext()) {
12273                    final ActivityIntentInfo intentInfo = intentIter.next();
12274                    boolean selectionFound = false;
12275
12276                    // loop through the intent filter's selection criteria; at least one
12277                    // of them must match the searched criteria
12278                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12279                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12280                        final T intentSelection = intentSelectionIter.next();
12281                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12282                            selectionFound = true;
12283                            break;
12284                        }
12285                    }
12286
12287                    // the selection criteria wasn't found in this filter's set; this filter
12288                    // is not a potential match
12289                    if (!selectionFound) {
12290                        intentIter.remove();
12291                    }
12292                }
12293            }
12294        }
12295
12296        private boolean isProtectedAction(ActivityIntentInfo filter) {
12297            final Iterator<String> actionsIter = filter.actionsIterator();
12298            while (actionsIter != null && actionsIter.hasNext()) {
12299                final String filterAction = actionsIter.next();
12300                if (PROTECTED_ACTIONS.contains(filterAction)) {
12301                    return true;
12302                }
12303            }
12304            return false;
12305        }
12306
12307        /**
12308         * Adjusts the priority of the given intent filter according to policy.
12309         * <p>
12310         * <ul>
12311         * <li>The priority for non privileged applications is capped to '0'</li>
12312         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12313         * <li>The priority for unbundled updates to privileged applications is capped to the
12314         *      priority defined on the system partition</li>
12315         * </ul>
12316         * <p>
12317         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12318         * allowed to obtain any priority on any action.
12319         */
12320        private void adjustPriority(
12321                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12322            // nothing to do; priority is fine as-is
12323            if (intent.getPriority() <= 0) {
12324                return;
12325            }
12326
12327            final ActivityInfo activityInfo = intent.activity.info;
12328            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12329
12330            final boolean privilegedApp =
12331                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12332            if (!privilegedApp) {
12333                // non-privileged applications can never define a priority >0
12334                if (DEBUG_FILTERS) {
12335                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12336                            + " package: " + applicationInfo.packageName
12337                            + " activity: " + intent.activity.className
12338                            + " origPrio: " + intent.getPriority());
12339                }
12340                intent.setPriority(0);
12341                return;
12342            }
12343
12344            if (systemActivities == null) {
12345                // the system package is not disabled; we're parsing the system partition
12346                if (isProtectedAction(intent)) {
12347                    if (mDeferProtectedFilters) {
12348                        // We can't deal with these just yet. No component should ever obtain a
12349                        // >0 priority for a protected actions, with ONE exception -- the setup
12350                        // wizard. The setup wizard, however, cannot be known until we're able to
12351                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12352                        // until all intent filters have been processed. Chicken, meet egg.
12353                        // Let the filter temporarily have a high priority and rectify the
12354                        // priorities after all system packages have been scanned.
12355                        mProtectedFilters.add(intent);
12356                        if (DEBUG_FILTERS) {
12357                            Slog.i(TAG, "Protected action; save for later;"
12358                                    + " package: " + applicationInfo.packageName
12359                                    + " activity: " + intent.activity.className
12360                                    + " origPrio: " + intent.getPriority());
12361                        }
12362                        return;
12363                    } else {
12364                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12365                            Slog.i(TAG, "No setup wizard;"
12366                                + " All protected intents capped to priority 0");
12367                        }
12368                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12369                            if (DEBUG_FILTERS) {
12370                                Slog.i(TAG, "Found setup wizard;"
12371                                    + " allow priority " + intent.getPriority() + ";"
12372                                    + " package: " + intent.activity.info.packageName
12373                                    + " activity: " + intent.activity.className
12374                                    + " priority: " + intent.getPriority());
12375                            }
12376                            // setup wizard gets whatever it wants
12377                            return;
12378                        }
12379                        if (DEBUG_FILTERS) {
12380                            Slog.i(TAG, "Protected action; cap priority to 0;"
12381                                    + " package: " + intent.activity.info.packageName
12382                                    + " activity: " + intent.activity.className
12383                                    + " origPrio: " + intent.getPriority());
12384                        }
12385                        intent.setPriority(0);
12386                        return;
12387                    }
12388                }
12389                // privileged apps on the system image get whatever priority they request
12390                return;
12391            }
12392
12393            // privileged app unbundled update ... try to find the same activity
12394            final PackageParser.Activity foundActivity =
12395                    findMatchingActivity(systemActivities, activityInfo);
12396            if (foundActivity == null) {
12397                // this is a new activity; it cannot obtain >0 priority
12398                if (DEBUG_FILTERS) {
12399                    Slog.i(TAG, "New activity; cap priority to 0;"
12400                            + " package: " + applicationInfo.packageName
12401                            + " activity: " + intent.activity.className
12402                            + " origPrio: " + intent.getPriority());
12403                }
12404                intent.setPriority(0);
12405                return;
12406            }
12407
12408            // found activity, now check for filter equivalence
12409
12410            // a shallow copy is enough; we modify the list, not its contents
12411            final List<ActivityIntentInfo> intentListCopy =
12412                    new ArrayList<>(foundActivity.intents);
12413            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12414
12415            // find matching action subsets
12416            final Iterator<String> actionsIterator = intent.actionsIterator();
12417            if (actionsIterator != null) {
12418                getIntentListSubset(
12419                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12420                if (intentListCopy.size() == 0) {
12421                    // no more intents to match; we're not equivalent
12422                    if (DEBUG_FILTERS) {
12423                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12424                                + " package: " + applicationInfo.packageName
12425                                + " activity: " + intent.activity.className
12426                                + " origPrio: " + intent.getPriority());
12427                    }
12428                    intent.setPriority(0);
12429                    return;
12430                }
12431            }
12432
12433            // find matching category subsets
12434            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12435            if (categoriesIterator != null) {
12436                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12437                        categoriesIterator);
12438                if (intentListCopy.size() == 0) {
12439                    // no more intents to match; we're not equivalent
12440                    if (DEBUG_FILTERS) {
12441                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12442                                + " package: " + applicationInfo.packageName
12443                                + " activity: " + intent.activity.className
12444                                + " origPrio: " + intent.getPriority());
12445                    }
12446                    intent.setPriority(0);
12447                    return;
12448                }
12449            }
12450
12451            // find matching schemes subsets
12452            final Iterator<String> schemesIterator = intent.schemesIterator();
12453            if (schemesIterator != null) {
12454                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12455                        schemesIterator);
12456                if (intentListCopy.size() == 0) {
12457                    // no more intents to match; we're not equivalent
12458                    if (DEBUG_FILTERS) {
12459                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12460                                + " package: " + applicationInfo.packageName
12461                                + " activity: " + intent.activity.className
12462                                + " origPrio: " + intent.getPriority());
12463                    }
12464                    intent.setPriority(0);
12465                    return;
12466                }
12467            }
12468
12469            // find matching authorities subsets
12470            final Iterator<IntentFilter.AuthorityEntry>
12471                    authoritiesIterator = intent.authoritiesIterator();
12472            if (authoritiesIterator != null) {
12473                getIntentListSubset(intentListCopy,
12474                        new AuthoritiesIterGenerator(),
12475                        authoritiesIterator);
12476                if (intentListCopy.size() == 0) {
12477                    // no more intents to match; we're not equivalent
12478                    if (DEBUG_FILTERS) {
12479                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12480                                + " package: " + applicationInfo.packageName
12481                                + " activity: " + intent.activity.className
12482                                + " origPrio: " + intent.getPriority());
12483                    }
12484                    intent.setPriority(0);
12485                    return;
12486                }
12487            }
12488
12489            // we found matching filter(s); app gets the max priority of all intents
12490            int cappedPriority = 0;
12491            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12492                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12493            }
12494            if (intent.getPriority() > cappedPriority) {
12495                if (DEBUG_FILTERS) {
12496                    Slog.i(TAG, "Found matching filter(s);"
12497                            + " cap priority to " + cappedPriority + ";"
12498                            + " package: " + applicationInfo.packageName
12499                            + " activity: " + intent.activity.className
12500                            + " origPrio: " + intent.getPriority());
12501                }
12502                intent.setPriority(cappedPriority);
12503                return;
12504            }
12505            // all this for nothing; the requested priority was <= what was on the system
12506        }
12507
12508        public final void addActivity(PackageParser.Activity a, String type) {
12509            mActivities.put(a.getComponentName(), a);
12510            if (DEBUG_SHOW_INFO)
12511                Log.v(
12512                TAG, "  " + type + " " +
12513                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12514            if (DEBUG_SHOW_INFO)
12515                Log.v(TAG, "    Class=" + a.info.name);
12516            final int NI = a.intents.size();
12517            for (int j=0; j<NI; j++) {
12518                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12519                if ("activity".equals(type)) {
12520                    final PackageSetting ps =
12521                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12522                    final List<PackageParser.Activity> systemActivities =
12523                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12524                    adjustPriority(systemActivities, intent);
12525                }
12526                if (DEBUG_SHOW_INFO) {
12527                    Log.v(TAG, "    IntentFilter:");
12528                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12529                }
12530                if (!intent.debugCheck()) {
12531                    Log.w(TAG, "==> For Activity " + a.info.name);
12532                }
12533                addFilter(intent);
12534            }
12535        }
12536
12537        public final void removeActivity(PackageParser.Activity a, String type) {
12538            mActivities.remove(a.getComponentName());
12539            if (DEBUG_SHOW_INFO) {
12540                Log.v(TAG, "  " + type + " "
12541                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12542                                : a.info.name) + ":");
12543                Log.v(TAG, "    Class=" + a.info.name);
12544            }
12545            final int NI = a.intents.size();
12546            for (int j=0; j<NI; j++) {
12547                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12548                if (DEBUG_SHOW_INFO) {
12549                    Log.v(TAG, "    IntentFilter:");
12550                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12551                }
12552                removeFilter(intent);
12553            }
12554        }
12555
12556        @Override
12557        protected boolean allowFilterResult(
12558                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12559            ActivityInfo filterAi = filter.activity.info;
12560            for (int i=dest.size()-1; i>=0; i--) {
12561                ActivityInfo destAi = dest.get(i).activityInfo;
12562                if (destAi.name == filterAi.name
12563                        && destAi.packageName == filterAi.packageName) {
12564                    return false;
12565                }
12566            }
12567            return true;
12568        }
12569
12570        @Override
12571        protected ActivityIntentInfo[] newArray(int size) {
12572            return new ActivityIntentInfo[size];
12573        }
12574
12575        @Override
12576        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12577            if (!sUserManager.exists(userId)) return true;
12578            PackageParser.Package p = filter.activity.owner;
12579            if (p != null) {
12580                PackageSetting ps = (PackageSetting)p.mExtras;
12581                if (ps != null) {
12582                    // System apps are never considered stopped for purposes of
12583                    // filtering, because there may be no way for the user to
12584                    // actually re-launch them.
12585                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12586                            && ps.getStopped(userId);
12587                }
12588            }
12589            return false;
12590        }
12591
12592        @Override
12593        protected boolean isPackageForFilter(String packageName,
12594                PackageParser.ActivityIntentInfo info) {
12595            return packageName.equals(info.activity.owner.packageName);
12596        }
12597
12598        @Override
12599        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12600                int match, int userId) {
12601            if (!sUserManager.exists(userId)) return null;
12602            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12603                return null;
12604            }
12605            final PackageParser.Activity activity = info.activity;
12606            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12607            if (ps == null) {
12608                return null;
12609            }
12610            final PackageUserState userState = ps.readUserState(userId);
12611            ActivityInfo ai =
12612                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12613            if (ai == null) {
12614                return null;
12615            }
12616            final boolean matchExplicitlyVisibleOnly =
12617                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12618            final boolean matchVisibleToInstantApp =
12619                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12620            final boolean componentVisible =
12621                    matchVisibleToInstantApp
12622                    && info.isVisibleToInstantApp()
12623                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12624            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12625            // throw out filters that aren't visible to ephemeral apps
12626            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12627                return null;
12628            }
12629            // throw out instant app filters if we're not explicitly requesting them
12630            if (!matchInstantApp && userState.instantApp) {
12631                return null;
12632            }
12633            // throw out instant app filters if updates are available; will trigger
12634            // instant app resolution
12635            if (userState.instantApp && ps.isUpdateAvailable()) {
12636                return null;
12637            }
12638            final ResolveInfo res = new ResolveInfo();
12639            res.activityInfo = ai;
12640            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12641                res.filter = info;
12642            }
12643            if (info != null) {
12644                res.handleAllWebDataURI = info.handleAllWebDataURI();
12645            }
12646            res.priority = info.getPriority();
12647            res.preferredOrder = activity.owner.mPreferredOrder;
12648            //System.out.println("Result: " + res.activityInfo.className +
12649            //                   " = " + res.priority);
12650            res.match = match;
12651            res.isDefault = info.hasDefault;
12652            res.labelRes = info.labelRes;
12653            res.nonLocalizedLabel = info.nonLocalizedLabel;
12654            if (userNeedsBadging(userId)) {
12655                res.noResourceId = true;
12656            } else {
12657                res.icon = info.icon;
12658            }
12659            res.iconResourceId = info.icon;
12660            res.system = res.activityInfo.applicationInfo.isSystemApp();
12661            res.isInstantAppAvailable = userState.instantApp;
12662            return res;
12663        }
12664
12665        @Override
12666        protected void sortResults(List<ResolveInfo> results) {
12667            Collections.sort(results, mResolvePrioritySorter);
12668        }
12669
12670        @Override
12671        protected void dumpFilter(PrintWriter out, String prefix,
12672                PackageParser.ActivityIntentInfo filter) {
12673            out.print(prefix); out.print(
12674                    Integer.toHexString(System.identityHashCode(filter.activity)));
12675                    out.print(' ');
12676                    filter.activity.printComponentShortName(out);
12677                    out.print(" filter ");
12678                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12679        }
12680
12681        @Override
12682        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12683            return filter.activity;
12684        }
12685
12686        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12687            PackageParser.Activity activity = (PackageParser.Activity)label;
12688            out.print(prefix); out.print(
12689                    Integer.toHexString(System.identityHashCode(activity)));
12690                    out.print(' ');
12691                    activity.printComponentShortName(out);
12692            if (count > 1) {
12693                out.print(" ("); out.print(count); out.print(" filters)");
12694            }
12695            out.println();
12696        }
12697
12698        // Keys are String (activity class name), values are Activity.
12699        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12700                = new ArrayMap<ComponentName, PackageParser.Activity>();
12701        private int mFlags;
12702    }
12703
12704    private final class ServiceIntentResolver
12705            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12706        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12707                boolean defaultOnly, int userId) {
12708            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12709            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12710        }
12711
12712        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12713                int userId) {
12714            if (!sUserManager.exists(userId)) return null;
12715            mFlags = flags;
12716            return super.queryIntent(intent, resolvedType,
12717                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12718                    userId);
12719        }
12720
12721        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12722                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12723            if (!sUserManager.exists(userId)) return null;
12724            if (packageServices == null) {
12725                return null;
12726            }
12727            mFlags = flags;
12728            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12729            final int N = packageServices.size();
12730            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12731                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12732
12733            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12734            for (int i = 0; i < N; ++i) {
12735                intentFilters = packageServices.get(i).intents;
12736                if (intentFilters != null && intentFilters.size() > 0) {
12737                    PackageParser.ServiceIntentInfo[] array =
12738                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12739                    intentFilters.toArray(array);
12740                    listCut.add(array);
12741                }
12742            }
12743            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12744        }
12745
12746        public final void addService(PackageParser.Service s) {
12747            mServices.put(s.getComponentName(), s);
12748            if (DEBUG_SHOW_INFO) {
12749                Log.v(TAG, "  "
12750                        + (s.info.nonLocalizedLabel != null
12751                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12752                Log.v(TAG, "    Class=" + s.info.name);
12753            }
12754            final int NI = s.intents.size();
12755            int j;
12756            for (j=0; j<NI; j++) {
12757                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12758                if (DEBUG_SHOW_INFO) {
12759                    Log.v(TAG, "    IntentFilter:");
12760                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12761                }
12762                if (!intent.debugCheck()) {
12763                    Log.w(TAG, "==> For Service " + s.info.name);
12764                }
12765                addFilter(intent);
12766            }
12767        }
12768
12769        public final void removeService(PackageParser.Service s) {
12770            mServices.remove(s.getComponentName());
12771            if (DEBUG_SHOW_INFO) {
12772                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12773                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12774                Log.v(TAG, "    Class=" + s.info.name);
12775            }
12776            final int NI = s.intents.size();
12777            int j;
12778            for (j=0; j<NI; j++) {
12779                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12780                if (DEBUG_SHOW_INFO) {
12781                    Log.v(TAG, "    IntentFilter:");
12782                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12783                }
12784                removeFilter(intent);
12785            }
12786        }
12787
12788        @Override
12789        protected boolean allowFilterResult(
12790                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12791            ServiceInfo filterSi = filter.service.info;
12792            for (int i=dest.size()-1; i>=0; i--) {
12793                ServiceInfo destAi = dest.get(i).serviceInfo;
12794                if (destAi.name == filterSi.name
12795                        && destAi.packageName == filterSi.packageName) {
12796                    return false;
12797                }
12798            }
12799            return true;
12800        }
12801
12802        @Override
12803        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12804            return new PackageParser.ServiceIntentInfo[size];
12805        }
12806
12807        @Override
12808        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12809            if (!sUserManager.exists(userId)) return true;
12810            PackageParser.Package p = filter.service.owner;
12811            if (p != null) {
12812                PackageSetting ps = (PackageSetting)p.mExtras;
12813                if (ps != null) {
12814                    // System apps are never considered stopped for purposes of
12815                    // filtering, because there may be no way for the user to
12816                    // actually re-launch them.
12817                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12818                            && ps.getStopped(userId);
12819                }
12820            }
12821            return false;
12822        }
12823
12824        @Override
12825        protected boolean isPackageForFilter(String packageName,
12826                PackageParser.ServiceIntentInfo info) {
12827            return packageName.equals(info.service.owner.packageName);
12828        }
12829
12830        @Override
12831        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12832                int match, int userId) {
12833            if (!sUserManager.exists(userId)) return null;
12834            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12835            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12836                return null;
12837            }
12838            final PackageParser.Service service = info.service;
12839            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12840            if (ps == null) {
12841                return null;
12842            }
12843            final PackageUserState userState = ps.readUserState(userId);
12844            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12845                    userState, userId);
12846            if (si == null) {
12847                return null;
12848            }
12849            final boolean matchVisibleToInstantApp =
12850                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12851            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12852            // throw out filters that aren't visible to ephemeral apps
12853            if (matchVisibleToInstantApp
12854                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12855                return null;
12856            }
12857            // throw out ephemeral filters if we're not explicitly requesting them
12858            if (!isInstantApp && userState.instantApp) {
12859                return null;
12860            }
12861            // throw out instant app filters if updates are available; will trigger
12862            // instant app resolution
12863            if (userState.instantApp && ps.isUpdateAvailable()) {
12864                return null;
12865            }
12866            final ResolveInfo res = new ResolveInfo();
12867            res.serviceInfo = si;
12868            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12869                res.filter = filter;
12870            }
12871            res.priority = info.getPriority();
12872            res.preferredOrder = service.owner.mPreferredOrder;
12873            res.match = match;
12874            res.isDefault = info.hasDefault;
12875            res.labelRes = info.labelRes;
12876            res.nonLocalizedLabel = info.nonLocalizedLabel;
12877            res.icon = info.icon;
12878            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12879            return res;
12880        }
12881
12882        @Override
12883        protected void sortResults(List<ResolveInfo> results) {
12884            Collections.sort(results, mResolvePrioritySorter);
12885        }
12886
12887        @Override
12888        protected void dumpFilter(PrintWriter out, String prefix,
12889                PackageParser.ServiceIntentInfo filter) {
12890            out.print(prefix); out.print(
12891                    Integer.toHexString(System.identityHashCode(filter.service)));
12892                    out.print(' ');
12893                    filter.service.printComponentShortName(out);
12894                    out.print(" filter ");
12895                    out.print(Integer.toHexString(System.identityHashCode(filter)));
12896                    if (filter.service.info.permission != null) {
12897                        out.print(" permission "); out.println(filter.service.info.permission);
12898                    } else {
12899                        out.println();
12900                    }
12901        }
12902
12903        @Override
12904        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12905            return filter.service;
12906        }
12907
12908        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12909            PackageParser.Service service = (PackageParser.Service)label;
12910            out.print(prefix); out.print(
12911                    Integer.toHexString(System.identityHashCode(service)));
12912                    out.print(' ');
12913                    service.printComponentShortName(out);
12914            if (count > 1) {
12915                out.print(" ("); out.print(count); out.print(" filters)");
12916            }
12917            out.println();
12918        }
12919
12920//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12921//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12922//            final List<ResolveInfo> retList = Lists.newArrayList();
12923//            while (i.hasNext()) {
12924//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12925//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12926//                    retList.add(resolveInfo);
12927//                }
12928//            }
12929//            return retList;
12930//        }
12931
12932        // Keys are String (activity class name), values are Activity.
12933        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12934                = new ArrayMap<ComponentName, PackageParser.Service>();
12935        private int mFlags;
12936    }
12937
12938    private final class ProviderIntentResolver
12939            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12940        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12941                boolean defaultOnly, int userId) {
12942            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12943            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12944        }
12945
12946        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12947                int userId) {
12948            if (!sUserManager.exists(userId))
12949                return null;
12950            mFlags = flags;
12951            return super.queryIntent(intent, resolvedType,
12952                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12953                    userId);
12954        }
12955
12956        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12957                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12958            if (!sUserManager.exists(userId))
12959                return null;
12960            if (packageProviders == null) {
12961                return null;
12962            }
12963            mFlags = flags;
12964            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12965            final int N = packageProviders.size();
12966            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12967                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12968
12969            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12970            for (int i = 0; i < N; ++i) {
12971                intentFilters = packageProviders.get(i).intents;
12972                if (intentFilters != null && intentFilters.size() > 0) {
12973                    PackageParser.ProviderIntentInfo[] array =
12974                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12975                    intentFilters.toArray(array);
12976                    listCut.add(array);
12977                }
12978            }
12979            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12980        }
12981
12982        public final void addProvider(PackageParser.Provider p) {
12983            if (mProviders.containsKey(p.getComponentName())) {
12984                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12985                return;
12986            }
12987
12988            mProviders.put(p.getComponentName(), p);
12989            if (DEBUG_SHOW_INFO) {
12990                Log.v(TAG, "  "
12991                        + (p.info.nonLocalizedLabel != null
12992                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12993                Log.v(TAG, "    Class=" + p.info.name);
12994            }
12995            final int NI = p.intents.size();
12996            int j;
12997            for (j = 0; j < NI; j++) {
12998                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12999                if (DEBUG_SHOW_INFO) {
13000                    Log.v(TAG, "    IntentFilter:");
13001                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13002                }
13003                if (!intent.debugCheck()) {
13004                    Log.w(TAG, "==> For Provider " + p.info.name);
13005                }
13006                addFilter(intent);
13007            }
13008        }
13009
13010        public final void removeProvider(PackageParser.Provider p) {
13011            mProviders.remove(p.getComponentName());
13012            if (DEBUG_SHOW_INFO) {
13013                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13014                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13015                Log.v(TAG, "    Class=" + p.info.name);
13016            }
13017            final int NI = p.intents.size();
13018            int j;
13019            for (j = 0; j < NI; j++) {
13020                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13021                if (DEBUG_SHOW_INFO) {
13022                    Log.v(TAG, "    IntentFilter:");
13023                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13024                }
13025                removeFilter(intent);
13026            }
13027        }
13028
13029        @Override
13030        protected boolean allowFilterResult(
13031                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13032            ProviderInfo filterPi = filter.provider.info;
13033            for (int i = dest.size() - 1; i >= 0; i--) {
13034                ProviderInfo destPi = dest.get(i).providerInfo;
13035                if (destPi.name == filterPi.name
13036                        && destPi.packageName == filterPi.packageName) {
13037                    return false;
13038                }
13039            }
13040            return true;
13041        }
13042
13043        @Override
13044        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13045            return new PackageParser.ProviderIntentInfo[size];
13046        }
13047
13048        @Override
13049        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13050            if (!sUserManager.exists(userId))
13051                return true;
13052            PackageParser.Package p = filter.provider.owner;
13053            if (p != null) {
13054                PackageSetting ps = (PackageSetting) p.mExtras;
13055                if (ps != null) {
13056                    // System apps are never considered stopped for purposes of
13057                    // filtering, because there may be no way for the user to
13058                    // actually re-launch them.
13059                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13060                            && ps.getStopped(userId);
13061                }
13062            }
13063            return false;
13064        }
13065
13066        @Override
13067        protected boolean isPackageForFilter(String packageName,
13068                PackageParser.ProviderIntentInfo info) {
13069            return packageName.equals(info.provider.owner.packageName);
13070        }
13071
13072        @Override
13073        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13074                int match, int userId) {
13075            if (!sUserManager.exists(userId))
13076                return null;
13077            final PackageParser.ProviderIntentInfo info = filter;
13078            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13079                return null;
13080            }
13081            final PackageParser.Provider provider = info.provider;
13082            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13083            if (ps == null) {
13084                return null;
13085            }
13086            final PackageUserState userState = ps.readUserState(userId);
13087            final boolean matchVisibleToInstantApp =
13088                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13089            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13090            // throw out filters that aren't visible to instant applications
13091            if (matchVisibleToInstantApp
13092                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13093                return null;
13094            }
13095            // throw out instant application filters if we're not explicitly requesting them
13096            if (!isInstantApp && userState.instantApp) {
13097                return null;
13098            }
13099            // throw out instant application filters if updates are available; will trigger
13100            // instant application resolution
13101            if (userState.instantApp && ps.isUpdateAvailable()) {
13102                return null;
13103            }
13104            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13105                    userState, userId);
13106            if (pi == null) {
13107                return null;
13108            }
13109            final ResolveInfo res = new ResolveInfo();
13110            res.providerInfo = pi;
13111            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13112                res.filter = filter;
13113            }
13114            res.priority = info.getPriority();
13115            res.preferredOrder = provider.owner.mPreferredOrder;
13116            res.match = match;
13117            res.isDefault = info.hasDefault;
13118            res.labelRes = info.labelRes;
13119            res.nonLocalizedLabel = info.nonLocalizedLabel;
13120            res.icon = info.icon;
13121            res.system = res.providerInfo.applicationInfo.isSystemApp();
13122            return res;
13123        }
13124
13125        @Override
13126        protected void sortResults(List<ResolveInfo> results) {
13127            Collections.sort(results, mResolvePrioritySorter);
13128        }
13129
13130        @Override
13131        protected void dumpFilter(PrintWriter out, String prefix,
13132                PackageParser.ProviderIntentInfo filter) {
13133            out.print(prefix);
13134            out.print(
13135                    Integer.toHexString(System.identityHashCode(filter.provider)));
13136            out.print(' ');
13137            filter.provider.printComponentShortName(out);
13138            out.print(" filter ");
13139            out.println(Integer.toHexString(System.identityHashCode(filter)));
13140        }
13141
13142        @Override
13143        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13144            return filter.provider;
13145        }
13146
13147        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13148            PackageParser.Provider provider = (PackageParser.Provider)label;
13149            out.print(prefix); out.print(
13150                    Integer.toHexString(System.identityHashCode(provider)));
13151                    out.print(' ');
13152                    provider.printComponentShortName(out);
13153            if (count > 1) {
13154                out.print(" ("); out.print(count); out.print(" filters)");
13155            }
13156            out.println();
13157        }
13158
13159        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13160                = new ArrayMap<ComponentName, PackageParser.Provider>();
13161        private int mFlags;
13162    }
13163
13164    static final class InstantAppIntentResolver
13165            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13166            AuxiliaryResolveInfo.AuxiliaryFilter> {
13167        /**
13168         * The result that has the highest defined order. Ordering applies on a
13169         * per-package basis. Mapping is from package name to Pair of order and
13170         * EphemeralResolveInfo.
13171         * <p>
13172         * NOTE: This is implemented as a field variable for convenience and efficiency.
13173         * By having a field variable, we're able to track filter ordering as soon as
13174         * a non-zero order is defined. Otherwise, multiple loops across the result set
13175         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13176         * this needs to be contained entirely within {@link #filterResults}.
13177         */
13178        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13179
13180        @Override
13181        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13182            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13183        }
13184
13185        @Override
13186        protected boolean isPackageForFilter(String packageName,
13187                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13188            return true;
13189        }
13190
13191        @Override
13192        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13193                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13194            if (!sUserManager.exists(userId)) {
13195                return null;
13196            }
13197            final String packageName = responseObj.resolveInfo.getPackageName();
13198            final Integer order = responseObj.getOrder();
13199            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13200                    mOrderResult.get(packageName);
13201            // ordering is enabled and this item's order isn't high enough
13202            if (lastOrderResult != null && lastOrderResult.first >= order) {
13203                return null;
13204            }
13205            final InstantAppResolveInfo res = responseObj.resolveInfo;
13206            if (order > 0) {
13207                // non-zero order, enable ordering
13208                mOrderResult.put(packageName, new Pair<>(order, res));
13209            }
13210            return responseObj;
13211        }
13212
13213        @Override
13214        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13215            // only do work if ordering is enabled [most of the time it won't be]
13216            if (mOrderResult.size() == 0) {
13217                return;
13218            }
13219            int resultSize = results.size();
13220            for (int i = 0; i < resultSize; i++) {
13221                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13222                final String packageName = info.getPackageName();
13223                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13224                if (savedInfo == null) {
13225                    // package doesn't having ordering
13226                    continue;
13227                }
13228                if (savedInfo.second == info) {
13229                    // circled back to the highest ordered item; remove from order list
13230                    mOrderResult.remove(packageName);
13231                    if (mOrderResult.size() == 0) {
13232                        // no more ordered items
13233                        break;
13234                    }
13235                    continue;
13236                }
13237                // item has a worse order, remove it from the result list
13238                results.remove(i);
13239                resultSize--;
13240                i--;
13241            }
13242        }
13243    }
13244
13245    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13246            new Comparator<ResolveInfo>() {
13247        public int compare(ResolveInfo r1, ResolveInfo r2) {
13248            int v1 = r1.priority;
13249            int v2 = r2.priority;
13250            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13251            if (v1 != v2) {
13252                return (v1 > v2) ? -1 : 1;
13253            }
13254            v1 = r1.preferredOrder;
13255            v2 = r2.preferredOrder;
13256            if (v1 != v2) {
13257                return (v1 > v2) ? -1 : 1;
13258            }
13259            if (r1.isDefault != r2.isDefault) {
13260                return r1.isDefault ? -1 : 1;
13261            }
13262            v1 = r1.match;
13263            v2 = r2.match;
13264            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13265            if (v1 != v2) {
13266                return (v1 > v2) ? -1 : 1;
13267            }
13268            if (r1.system != r2.system) {
13269                return r1.system ? -1 : 1;
13270            }
13271            if (r1.activityInfo != null) {
13272                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13273            }
13274            if (r1.serviceInfo != null) {
13275                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13276            }
13277            if (r1.providerInfo != null) {
13278                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13279            }
13280            return 0;
13281        }
13282    };
13283
13284    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13285            new Comparator<ProviderInfo>() {
13286        public int compare(ProviderInfo p1, ProviderInfo p2) {
13287            final int v1 = p1.initOrder;
13288            final int v2 = p2.initOrder;
13289            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13290        }
13291    };
13292
13293    @Override
13294    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13295            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13296            final int[] userIds, int[] instantUserIds) {
13297        mHandler.post(new Runnable() {
13298            @Override
13299            public void run() {
13300                try {
13301                    final IActivityManager am = ActivityManager.getService();
13302                    if (am == null) return;
13303                    final int[] resolvedUserIds;
13304                    if (userIds == null) {
13305                        resolvedUserIds = am.getRunningUserIds();
13306                    } else {
13307                        resolvedUserIds = userIds;
13308                    }
13309                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13310                            resolvedUserIds, false);
13311                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13312                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13313                                instantUserIds, true);
13314                    }
13315                } catch (RemoteException ex) {
13316                }
13317            }
13318        });
13319    }
13320
13321    @Override
13322    public void notifyPackageAdded(String packageName) {
13323        final PackageListObserver[] observers;
13324        synchronized (mPackages) {
13325            if (mPackageListObservers.size() == 0) {
13326                return;
13327            }
13328            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13329        }
13330        for (int i = observers.length - 1; i >= 0; --i) {
13331            observers[i].onPackageAdded(packageName);
13332        }
13333    }
13334
13335    @Override
13336    public void notifyPackageRemoved(String packageName) {
13337        final PackageListObserver[] observers;
13338        synchronized (mPackages) {
13339            if (mPackageListObservers.size() == 0) {
13340                return;
13341            }
13342            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13343        }
13344        for (int i = observers.length - 1; i >= 0; --i) {
13345            observers[i].onPackageRemoved(packageName);
13346        }
13347    }
13348
13349    /**
13350     * Sends a broadcast for the given action.
13351     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13352     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13353     * the system and applications allowed to see instant applications to receive package
13354     * lifecycle events for instant applications.
13355     */
13356    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13357            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13358            int[] userIds, boolean isInstantApp)
13359                    throws RemoteException {
13360        for (int id : userIds) {
13361            final Intent intent = new Intent(action,
13362                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13363            final String[] requiredPermissions =
13364                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13365            if (extras != null) {
13366                intent.putExtras(extras);
13367            }
13368            if (targetPkg != null) {
13369                intent.setPackage(targetPkg);
13370            }
13371            // Modify the UID when posting to other users
13372            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13373            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13374                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13375                intent.putExtra(Intent.EXTRA_UID, uid);
13376            }
13377            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13378            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13379            if (DEBUG_BROADCASTS) {
13380                RuntimeException here = new RuntimeException("here");
13381                here.fillInStackTrace();
13382                Slog.d(TAG, "Sending to user " + id + ": "
13383                        + intent.toShortString(false, true, false, false)
13384                        + " " + intent.getExtras(), here);
13385            }
13386            am.broadcastIntent(null, intent, null, finishedReceiver,
13387                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13388                    null, finishedReceiver != null, false, id);
13389        }
13390    }
13391
13392    /**
13393     * Check if the external storage media is available. This is true if there
13394     * is a mounted external storage medium or if the external storage is
13395     * emulated.
13396     */
13397    private boolean isExternalMediaAvailable() {
13398        return mMediaMounted || Environment.isExternalStorageEmulated();
13399    }
13400
13401    @Override
13402    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13403        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13404            return null;
13405        }
13406        if (!isExternalMediaAvailable()) {
13407                // If the external storage is no longer mounted at this point,
13408                // the caller may not have been able to delete all of this
13409                // packages files and can not delete any more.  Bail.
13410            return null;
13411        }
13412        synchronized (mPackages) {
13413            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13414            if (lastPackage != null) {
13415                pkgs.remove(lastPackage);
13416            }
13417            if (pkgs.size() > 0) {
13418                return pkgs.get(0);
13419            }
13420        }
13421        return null;
13422    }
13423
13424    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13425        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13426                userId, andCode ? 1 : 0, packageName);
13427        if (mSystemReady) {
13428            msg.sendToTarget();
13429        } else {
13430            if (mPostSystemReadyMessages == null) {
13431                mPostSystemReadyMessages = new ArrayList<>();
13432            }
13433            mPostSystemReadyMessages.add(msg);
13434        }
13435    }
13436
13437    void startCleaningPackages() {
13438        // reader
13439        if (!isExternalMediaAvailable()) {
13440            return;
13441        }
13442        synchronized (mPackages) {
13443            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13444                return;
13445            }
13446        }
13447        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13448        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13449        IActivityManager am = ActivityManager.getService();
13450        if (am != null) {
13451            int dcsUid = -1;
13452            synchronized (mPackages) {
13453                if (!mDefaultContainerWhitelisted) {
13454                    mDefaultContainerWhitelisted = true;
13455                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13456                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13457                }
13458            }
13459            try {
13460                if (dcsUid > 0) {
13461                    am.backgroundWhitelistUid(dcsUid);
13462                }
13463                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13464                        UserHandle.USER_SYSTEM);
13465            } catch (RemoteException e) {
13466            }
13467        }
13468    }
13469
13470    /**
13471     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13472     * it is acting on behalf on an enterprise or the user).
13473     *
13474     * Note that the ordering of the conditionals in this method is important. The checks we perform
13475     * are as follows, in this order:
13476     *
13477     * 1) If the install is being performed by a system app, we can trust the app to have set the
13478     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13479     *    what it is.
13480     * 2) If the install is being performed by a device or profile owner app, the install reason
13481     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13482     *    set the install reason correctly. If the app targets an older SDK version where install
13483     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13484     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13485     * 3) In all other cases, the install is being performed by a regular app that is neither part
13486     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13487     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13488     *    set to enterprise policy and if so, change it to unknown instead.
13489     */
13490    private int fixUpInstallReason(String installerPackageName, int installerUid,
13491            int installReason) {
13492        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13493                == PERMISSION_GRANTED) {
13494            // If the install is being performed by a system app, we trust that app to have set the
13495            // install reason correctly.
13496            return installReason;
13497        }
13498
13499        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13500            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13501        if (dpm != null) {
13502            ComponentName owner = null;
13503            try {
13504                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13505                if (owner == null) {
13506                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13507                }
13508            } catch (RemoteException e) {
13509            }
13510            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13511                // If the install is being performed by a device or profile owner, the install
13512                // reason should be enterprise policy.
13513                return PackageManager.INSTALL_REASON_POLICY;
13514            }
13515        }
13516
13517        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13518            // If the install is being performed by a regular app (i.e. neither system app nor
13519            // device or profile owner), we have no reason to believe that the app is acting on
13520            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13521            // change it to unknown instead.
13522            return PackageManager.INSTALL_REASON_UNKNOWN;
13523        }
13524
13525        // If the install is being performed by a regular app and the install reason was set to any
13526        // value but enterprise policy, leave the install reason unchanged.
13527        return installReason;
13528    }
13529
13530    void installStage(String packageName, File stagedDir,
13531            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13532            String installerPackageName, int installerUid, UserHandle user,
13533            PackageParser.SigningDetails signingDetails) {
13534        if (DEBUG_INSTANT) {
13535            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13536                Slog.d(TAG, "Ephemeral install of " + packageName);
13537            }
13538        }
13539        final VerificationInfo verificationInfo = new VerificationInfo(
13540                sessionParams.originatingUri, sessionParams.referrerUri,
13541                sessionParams.originatingUid, installerUid);
13542
13543        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13544
13545        final Message msg = mHandler.obtainMessage(INIT_COPY);
13546        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13547                sessionParams.installReason);
13548        final InstallParams params = new InstallParams(origin, null, observer,
13549                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13550                verificationInfo, user, sessionParams.abiOverride,
13551                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13552        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13553        msg.obj = params;
13554
13555        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13556                System.identityHashCode(msg.obj));
13557        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13558                System.identityHashCode(msg.obj));
13559
13560        mHandler.sendMessage(msg);
13561    }
13562
13563    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13564            int userId) {
13565        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13566        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13567        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13568        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13569        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13570                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13571
13572        // Send a session commit broadcast
13573        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13574        info.installReason = pkgSetting.getInstallReason(userId);
13575        info.appPackageName = packageName;
13576        sendSessionCommitBroadcast(info, userId);
13577    }
13578
13579    @Override
13580    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13581            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13582        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13583            return;
13584        }
13585        Bundle extras = new Bundle(1);
13586        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13587        final int uid = UserHandle.getUid(
13588                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13589        extras.putInt(Intent.EXTRA_UID, uid);
13590
13591        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13592                packageName, extras, 0, null, null, userIds, instantUserIds);
13593        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13594            mHandler.post(() -> {
13595                        for (int userId : userIds) {
13596                            sendBootCompletedBroadcastToSystemApp(
13597                                    packageName, includeStopped, userId);
13598                        }
13599                    }
13600            );
13601        }
13602    }
13603
13604    /**
13605     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13606     * automatically without needing an explicit launch.
13607     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13608     */
13609    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13610            int userId) {
13611        // If user is not running, the app didn't miss any broadcast
13612        if (!mUserManagerInternal.isUserRunning(userId)) {
13613            return;
13614        }
13615        final IActivityManager am = ActivityManager.getService();
13616        try {
13617            // Deliver LOCKED_BOOT_COMPLETED first
13618            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13619                    .setPackage(packageName);
13620            if (includeStopped) {
13621                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13622            }
13623            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13624            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13625                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13626
13627            // Deliver BOOT_COMPLETED only if user is unlocked
13628            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13629                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13630                if (includeStopped) {
13631                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13632                }
13633                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13634                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13635            }
13636        } catch (RemoteException e) {
13637            throw e.rethrowFromSystemServer();
13638        }
13639    }
13640
13641    @Override
13642    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13643            int userId) {
13644        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13645        PackageSetting pkgSetting;
13646        final int callingUid = Binder.getCallingUid();
13647        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13648                true /* requireFullPermission */, true /* checkShell */,
13649                "setApplicationHiddenSetting for user " + userId);
13650
13651        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13652            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13653            return false;
13654        }
13655
13656        long callingId = Binder.clearCallingIdentity();
13657        try {
13658            boolean sendAdded = false;
13659            boolean sendRemoved = false;
13660            // writer
13661            synchronized (mPackages) {
13662                pkgSetting = mSettings.mPackages.get(packageName);
13663                if (pkgSetting == null) {
13664                    return false;
13665                }
13666                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13667                    return false;
13668                }
13669                // Do not allow "android" is being disabled
13670                if ("android".equals(packageName)) {
13671                    Slog.w(TAG, "Cannot hide package: android");
13672                    return false;
13673                }
13674                // Cannot hide static shared libs as they are considered
13675                // a part of the using app (emulating static linking). Also
13676                // static libs are installed always on internal storage.
13677                PackageParser.Package pkg = mPackages.get(packageName);
13678                if (pkg != null && pkg.staticSharedLibName != null) {
13679                    Slog.w(TAG, "Cannot hide package: " + packageName
13680                            + " providing static shared library: "
13681                            + pkg.staticSharedLibName);
13682                    return false;
13683                }
13684                // Only allow protected packages to hide themselves.
13685                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13686                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13687                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13688                    return false;
13689                }
13690
13691                if (pkgSetting.getHidden(userId) != hidden) {
13692                    pkgSetting.setHidden(hidden, userId);
13693                    mSettings.writePackageRestrictionsLPr(userId);
13694                    if (hidden) {
13695                        sendRemoved = true;
13696                    } else {
13697                        sendAdded = true;
13698                    }
13699                }
13700            }
13701            if (sendAdded) {
13702                sendPackageAddedForUser(packageName, pkgSetting, userId);
13703                return true;
13704            }
13705            if (sendRemoved) {
13706                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13707                        "hiding pkg");
13708                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13709                return true;
13710            }
13711        } finally {
13712            Binder.restoreCallingIdentity(callingId);
13713        }
13714        return false;
13715    }
13716
13717    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13718            int userId) {
13719        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13720        info.removedPackage = packageName;
13721        info.installerPackageName = pkgSetting.installerPackageName;
13722        info.removedUsers = new int[] {userId};
13723        info.broadcastUsers = new int[] {userId};
13724        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13725        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13726    }
13727
13728    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13729        if (pkgList.length > 0) {
13730            Bundle extras = new Bundle(1);
13731            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13732
13733            sendPackageBroadcast(
13734                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13735                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13736                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13737                    new int[] {userId}, null);
13738        }
13739    }
13740
13741    /**
13742     * Returns true if application is not found or there was an error. Otherwise it returns
13743     * the hidden state of the package for the given user.
13744     */
13745    @Override
13746    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13747        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13748        final int callingUid = Binder.getCallingUid();
13749        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13750                true /* requireFullPermission */, false /* checkShell */,
13751                "getApplicationHidden for user " + userId);
13752        PackageSetting ps;
13753        long callingId = Binder.clearCallingIdentity();
13754        try {
13755            // writer
13756            synchronized (mPackages) {
13757                ps = mSettings.mPackages.get(packageName);
13758                if (ps == null) {
13759                    return true;
13760                }
13761                if (filterAppAccessLPr(ps, callingUid, userId)) {
13762                    return true;
13763                }
13764                return ps.getHidden(userId);
13765            }
13766        } finally {
13767            Binder.restoreCallingIdentity(callingId);
13768        }
13769    }
13770
13771    /**
13772     * @hide
13773     */
13774    @Override
13775    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13776            int installReason) {
13777        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13778                null);
13779        PackageSetting pkgSetting;
13780        final int callingUid = Binder.getCallingUid();
13781        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13782                true /* requireFullPermission */, true /* checkShell */,
13783                "installExistingPackage for user " + userId);
13784        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13785            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13786        }
13787
13788        long callingId = Binder.clearCallingIdentity();
13789        try {
13790            boolean installed = false;
13791            final boolean instantApp =
13792                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13793            final boolean fullApp =
13794                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13795
13796            // writer
13797            synchronized (mPackages) {
13798                pkgSetting = mSettings.mPackages.get(packageName);
13799                if (pkgSetting == null) {
13800                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13801                }
13802                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13803                    // only allow the existing package to be used if it's installed as a full
13804                    // application for at least one user
13805                    boolean installAllowed = false;
13806                    for (int checkUserId : sUserManager.getUserIds()) {
13807                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13808                        if (installAllowed) {
13809                            break;
13810                        }
13811                    }
13812                    if (!installAllowed) {
13813                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13814                    }
13815                }
13816                if (!pkgSetting.getInstalled(userId)) {
13817                    pkgSetting.setInstalled(true, userId);
13818                    pkgSetting.setHidden(false, userId);
13819                    pkgSetting.setInstallReason(installReason, userId);
13820                    mSettings.writePackageRestrictionsLPr(userId);
13821                    mSettings.writeKernelMappingLPr(pkgSetting);
13822                    installed = true;
13823                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13824                    // upgrade app from instant to full; we don't allow app downgrade
13825                    installed = true;
13826                }
13827                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13828            }
13829
13830            if (installed) {
13831                if (pkgSetting.pkg != null) {
13832                    synchronized (mInstallLock) {
13833                        // We don't need to freeze for a brand new install
13834                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13835                    }
13836                }
13837                sendPackageAddedForUser(packageName, pkgSetting, userId);
13838                synchronized (mPackages) {
13839                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13840                }
13841            }
13842        } finally {
13843            Binder.restoreCallingIdentity(callingId);
13844        }
13845
13846        return PackageManager.INSTALL_SUCCEEDED;
13847    }
13848
13849    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13850            boolean instantApp, boolean fullApp) {
13851        // no state specified; do nothing
13852        if (!instantApp && !fullApp) {
13853            return;
13854        }
13855        if (userId != UserHandle.USER_ALL) {
13856            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13857                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13858            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13859                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13860            }
13861        } else {
13862            for (int currentUserId : sUserManager.getUserIds()) {
13863                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13864                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13865                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13866                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13867                }
13868            }
13869        }
13870    }
13871
13872    boolean isUserRestricted(int userId, String restrictionKey) {
13873        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13874        if (restrictions.getBoolean(restrictionKey, false)) {
13875            Log.w(TAG, "User is restricted: " + restrictionKey);
13876            return true;
13877        }
13878        return false;
13879    }
13880
13881    @Override
13882    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13883            int userId) {
13884        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13885        final int callingUid = Binder.getCallingUid();
13886        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13887                true /* requireFullPermission */, true /* checkShell */,
13888                "setPackagesSuspended for user " + userId);
13889
13890        if (ArrayUtils.isEmpty(packageNames)) {
13891            return packageNames;
13892        }
13893
13894        // List of package names for whom the suspended state has changed.
13895        List<String> changedPackages = new ArrayList<>(packageNames.length);
13896        // List of package names for whom the suspended state is not set as requested in this
13897        // method.
13898        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13899        long callingId = Binder.clearCallingIdentity();
13900        try {
13901            for (int i = 0; i < packageNames.length; i++) {
13902                String packageName = packageNames[i];
13903                boolean changed = false;
13904                final int appId;
13905                synchronized (mPackages) {
13906                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13907                    if (pkgSetting == null
13908                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13909                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13910                                + "\". Skipping suspending/un-suspending.");
13911                        unactionedPackages.add(packageName);
13912                        continue;
13913                    }
13914                    appId = pkgSetting.appId;
13915                    if (pkgSetting.getSuspended(userId) != suspended) {
13916                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13917                            unactionedPackages.add(packageName);
13918                            continue;
13919                        }
13920                        pkgSetting.setSuspended(suspended, userId);
13921                        mSettings.writePackageRestrictionsLPr(userId);
13922                        changed = true;
13923                        changedPackages.add(packageName);
13924                    }
13925                }
13926
13927                if (changed && suspended) {
13928                    killApplication(packageName, UserHandle.getUid(userId, appId),
13929                            "suspending package");
13930                }
13931            }
13932        } finally {
13933            Binder.restoreCallingIdentity(callingId);
13934        }
13935
13936        if (!changedPackages.isEmpty()) {
13937            sendPackagesSuspendedForUser(changedPackages.toArray(
13938                    new String[changedPackages.size()]), userId, suspended);
13939        }
13940
13941        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13942    }
13943
13944    @Override
13945    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13946        final int callingUid = Binder.getCallingUid();
13947        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13948                true /* requireFullPermission */, false /* checkShell */,
13949                "isPackageSuspendedForUser for user " + userId);
13950        synchronized (mPackages) {
13951            final PackageSetting ps = mSettings.mPackages.get(packageName);
13952            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
13953                throw new IllegalArgumentException("Unknown target package: " + packageName);
13954            }
13955            return ps.getSuspended(userId);
13956        }
13957    }
13958
13959    @GuardedBy("mPackages")
13960    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13961        if (isPackageDeviceAdmin(packageName, userId)) {
13962            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13963                    + "\": has an active device admin");
13964            return false;
13965        }
13966
13967        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13968        if (packageName.equals(activeLauncherPackageName)) {
13969            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13970                    + "\": contains the active launcher");
13971            return false;
13972        }
13973
13974        if (packageName.equals(mRequiredInstallerPackage)) {
13975            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13976                    + "\": required for package installation");
13977            return false;
13978        }
13979
13980        if (packageName.equals(mRequiredUninstallerPackage)) {
13981            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13982                    + "\": required for package uninstallation");
13983            return false;
13984        }
13985
13986        if (packageName.equals(mRequiredVerifierPackage)) {
13987            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13988                    + "\": required for package verification");
13989            return false;
13990        }
13991
13992        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13993            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13994                    + "\": is the default dialer");
13995            return false;
13996        }
13997
13998        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13999            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14000                    + "\": protected package");
14001            return false;
14002        }
14003
14004        // Cannot suspend static shared libs as they are considered
14005        // a part of the using app (emulating static linking). Also
14006        // static libs are installed always on internal storage.
14007        PackageParser.Package pkg = mPackages.get(packageName);
14008        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14009            Slog.w(TAG, "Cannot suspend package: " + packageName
14010                    + " providing static shared library: "
14011                    + pkg.staticSharedLibName);
14012            return false;
14013        }
14014
14015        return true;
14016    }
14017
14018    private String getActiveLauncherPackageName(int userId) {
14019        Intent intent = new Intent(Intent.ACTION_MAIN);
14020        intent.addCategory(Intent.CATEGORY_HOME);
14021        ResolveInfo resolveInfo = resolveIntent(
14022                intent,
14023                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14024                PackageManager.MATCH_DEFAULT_ONLY,
14025                userId);
14026
14027        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14028    }
14029
14030    private String getDefaultDialerPackageName(int userId) {
14031        synchronized (mPackages) {
14032            return mSettings.getDefaultDialerPackageNameLPw(userId);
14033        }
14034    }
14035
14036    @Override
14037    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14038        mContext.enforceCallingOrSelfPermission(
14039                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14040                "Only package verification agents can verify applications");
14041
14042        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14043        final PackageVerificationResponse response = new PackageVerificationResponse(
14044                verificationCode, Binder.getCallingUid());
14045        msg.arg1 = id;
14046        msg.obj = response;
14047        mHandler.sendMessage(msg);
14048    }
14049
14050    @Override
14051    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14052            long millisecondsToDelay) {
14053        mContext.enforceCallingOrSelfPermission(
14054                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14055                "Only package verification agents can extend verification timeouts");
14056
14057        final PackageVerificationState state = mPendingVerification.get(id);
14058        final PackageVerificationResponse response = new PackageVerificationResponse(
14059                verificationCodeAtTimeout, Binder.getCallingUid());
14060
14061        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14062            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14063        }
14064        if (millisecondsToDelay < 0) {
14065            millisecondsToDelay = 0;
14066        }
14067        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14068                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14069            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14070        }
14071
14072        if ((state != null) && !state.timeoutExtended()) {
14073            state.extendTimeout();
14074
14075            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14076            msg.arg1 = id;
14077            msg.obj = response;
14078            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14079        }
14080    }
14081
14082    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14083            int verificationCode, UserHandle user) {
14084        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14085        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14086        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14087        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14088        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14089
14090        mContext.sendBroadcastAsUser(intent, user,
14091                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14092    }
14093
14094    private ComponentName matchComponentForVerifier(String packageName,
14095            List<ResolveInfo> receivers) {
14096        ActivityInfo targetReceiver = null;
14097
14098        final int NR = receivers.size();
14099        for (int i = 0; i < NR; i++) {
14100            final ResolveInfo info = receivers.get(i);
14101            if (info.activityInfo == null) {
14102                continue;
14103            }
14104
14105            if (packageName.equals(info.activityInfo.packageName)) {
14106                targetReceiver = info.activityInfo;
14107                break;
14108            }
14109        }
14110
14111        if (targetReceiver == null) {
14112            return null;
14113        }
14114
14115        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14116    }
14117
14118    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14119            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14120        if (pkgInfo.verifiers.length == 0) {
14121            return null;
14122        }
14123
14124        final int N = pkgInfo.verifiers.length;
14125        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14126        for (int i = 0; i < N; i++) {
14127            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14128
14129            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14130                    receivers);
14131            if (comp == null) {
14132                continue;
14133            }
14134
14135            final int verifierUid = getUidForVerifier(verifierInfo);
14136            if (verifierUid == -1) {
14137                continue;
14138            }
14139
14140            if (DEBUG_VERIFY) {
14141                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14142                        + " with the correct signature");
14143            }
14144            sufficientVerifiers.add(comp);
14145            verificationState.addSufficientVerifier(verifierUid);
14146        }
14147
14148        return sufficientVerifiers;
14149    }
14150
14151    private int getUidForVerifier(VerifierInfo verifierInfo) {
14152        synchronized (mPackages) {
14153            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14154            if (pkg == null) {
14155                return -1;
14156            } else if (pkg.mSigningDetails.signatures.length != 1) {
14157                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14158                        + " has more than one signature; ignoring");
14159                return -1;
14160            }
14161
14162            /*
14163             * If the public key of the package's signature does not match
14164             * our expected public key, then this is a different package and
14165             * we should skip.
14166             */
14167
14168            final byte[] expectedPublicKey;
14169            try {
14170                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14171                final PublicKey publicKey = verifierSig.getPublicKey();
14172                expectedPublicKey = publicKey.getEncoded();
14173            } catch (CertificateException e) {
14174                return -1;
14175            }
14176
14177            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14178
14179            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14180                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14181                        + " does not have the expected public key; ignoring");
14182                return -1;
14183            }
14184
14185            return pkg.applicationInfo.uid;
14186        }
14187    }
14188
14189    @Override
14190    public void finishPackageInstall(int token, boolean didLaunch) {
14191        enforceSystemOrRoot("Only the system is allowed to finish installs");
14192
14193        if (DEBUG_INSTALL) {
14194            Slog.v(TAG, "BM finishing package install for " + token);
14195        }
14196        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14197
14198        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14199        mHandler.sendMessage(msg);
14200    }
14201
14202    /**
14203     * Get the verification agent timeout.  Used for both the APK verifier and the
14204     * intent filter verifier.
14205     *
14206     * @return verification timeout in milliseconds
14207     */
14208    private long getVerificationTimeout() {
14209        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14210                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14211                DEFAULT_VERIFICATION_TIMEOUT);
14212    }
14213
14214    /**
14215     * Get the default verification agent response code.
14216     *
14217     * @return default verification response code
14218     */
14219    private int getDefaultVerificationResponse(UserHandle user) {
14220        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14221            return PackageManager.VERIFICATION_REJECT;
14222        }
14223        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14224                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14225                DEFAULT_VERIFICATION_RESPONSE);
14226    }
14227
14228    /**
14229     * Check whether or not package verification has been enabled.
14230     *
14231     * @return true if verification should be performed
14232     */
14233    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14234        if (!DEFAULT_VERIFY_ENABLE) {
14235            return false;
14236        }
14237
14238        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14239
14240        // Check if installing from ADB
14241        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14242            // Do not run verification in a test harness environment
14243            if (ActivityManager.isRunningInTestHarness()) {
14244                return false;
14245            }
14246            if (ensureVerifyAppsEnabled) {
14247                return true;
14248            }
14249            // Check if the developer does not want package verification for ADB installs
14250            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14251                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14252                return false;
14253            }
14254        } else {
14255            // only when not installed from ADB, skip verification for instant apps when
14256            // the installer and verifier are the same.
14257            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14258                if (mInstantAppInstallerActivity != null
14259                        && mInstantAppInstallerActivity.packageName.equals(
14260                                mRequiredVerifierPackage)) {
14261                    try {
14262                        mContext.getSystemService(AppOpsManager.class)
14263                                .checkPackage(installerUid, mRequiredVerifierPackage);
14264                        if (DEBUG_VERIFY) {
14265                            Slog.i(TAG, "disable verification for instant app");
14266                        }
14267                        return false;
14268                    } catch (SecurityException ignore) { }
14269                }
14270            }
14271        }
14272
14273        if (ensureVerifyAppsEnabled) {
14274            return true;
14275        }
14276
14277        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14278                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14279    }
14280
14281    @Override
14282    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14283            throws RemoteException {
14284        mContext.enforceCallingOrSelfPermission(
14285                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14286                "Only intentfilter verification agents can verify applications");
14287
14288        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14289        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14290                Binder.getCallingUid(), verificationCode, failedDomains);
14291        msg.arg1 = id;
14292        msg.obj = response;
14293        mHandler.sendMessage(msg);
14294    }
14295
14296    @Override
14297    public int getIntentVerificationStatus(String packageName, int userId) {
14298        final int callingUid = Binder.getCallingUid();
14299        if (UserHandle.getUserId(callingUid) != userId) {
14300            mContext.enforceCallingOrSelfPermission(
14301                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14302                    "getIntentVerificationStatus" + userId);
14303        }
14304        if (getInstantAppPackageName(callingUid) != null) {
14305            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14306        }
14307        synchronized (mPackages) {
14308            final PackageSetting ps = mSettings.mPackages.get(packageName);
14309            if (ps == null
14310                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14311                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14312            }
14313            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14314        }
14315    }
14316
14317    @Override
14318    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14319        mContext.enforceCallingOrSelfPermission(
14320                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14321
14322        boolean result = false;
14323        synchronized (mPackages) {
14324            final PackageSetting ps = mSettings.mPackages.get(packageName);
14325            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14326                return false;
14327            }
14328            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14329        }
14330        if (result) {
14331            scheduleWritePackageRestrictionsLocked(userId);
14332        }
14333        return result;
14334    }
14335
14336    @Override
14337    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14338            String packageName) {
14339        final int callingUid = Binder.getCallingUid();
14340        if (getInstantAppPackageName(callingUid) != null) {
14341            return ParceledListSlice.emptyList();
14342        }
14343        synchronized (mPackages) {
14344            final PackageSetting ps = mSettings.mPackages.get(packageName);
14345            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14346                return ParceledListSlice.emptyList();
14347            }
14348            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14349        }
14350    }
14351
14352    @Override
14353    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14354        if (TextUtils.isEmpty(packageName)) {
14355            return ParceledListSlice.emptyList();
14356        }
14357        final int callingUid = Binder.getCallingUid();
14358        final int callingUserId = UserHandle.getUserId(callingUid);
14359        synchronized (mPackages) {
14360            PackageParser.Package pkg = mPackages.get(packageName);
14361            if (pkg == null || pkg.activities == null) {
14362                return ParceledListSlice.emptyList();
14363            }
14364            if (pkg.mExtras == null) {
14365                return ParceledListSlice.emptyList();
14366            }
14367            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14368            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14369                return ParceledListSlice.emptyList();
14370            }
14371            final int count = pkg.activities.size();
14372            ArrayList<IntentFilter> result = new ArrayList<>();
14373            for (int n=0; n<count; n++) {
14374                PackageParser.Activity activity = pkg.activities.get(n);
14375                if (activity.intents != null && activity.intents.size() > 0) {
14376                    result.addAll(activity.intents);
14377                }
14378            }
14379            return new ParceledListSlice<>(result);
14380        }
14381    }
14382
14383    @Override
14384    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14385        mContext.enforceCallingOrSelfPermission(
14386                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14387        if (UserHandle.getCallingUserId() != userId) {
14388            mContext.enforceCallingOrSelfPermission(
14389                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14390        }
14391
14392        synchronized (mPackages) {
14393            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14394            if (packageName != null) {
14395                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14396                        packageName, userId);
14397            }
14398            return result;
14399        }
14400    }
14401
14402    @Override
14403    public String getDefaultBrowserPackageName(int userId) {
14404        if (UserHandle.getCallingUserId() != userId) {
14405            mContext.enforceCallingOrSelfPermission(
14406                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14407        }
14408        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14409            return null;
14410        }
14411        synchronized (mPackages) {
14412            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14413        }
14414    }
14415
14416    /**
14417     * Get the "allow unknown sources" setting.
14418     *
14419     * @return the current "allow unknown sources" setting
14420     */
14421    private int getUnknownSourcesSettings() {
14422        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14423                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14424                -1);
14425    }
14426
14427    @Override
14428    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14429        final int callingUid = Binder.getCallingUid();
14430        if (getInstantAppPackageName(callingUid) != null) {
14431            return;
14432        }
14433        // writer
14434        synchronized (mPackages) {
14435            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14436            if (targetPackageSetting == null
14437                    || filterAppAccessLPr(
14438                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14439                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14440            }
14441
14442            PackageSetting installerPackageSetting;
14443            if (installerPackageName != null) {
14444                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14445                if (installerPackageSetting == null) {
14446                    throw new IllegalArgumentException("Unknown installer package: "
14447                            + installerPackageName);
14448                }
14449            } else {
14450                installerPackageSetting = null;
14451            }
14452
14453            Signature[] callerSignature;
14454            Object obj = mSettings.getUserIdLPr(callingUid);
14455            if (obj != null) {
14456                if (obj instanceof SharedUserSetting) {
14457                    callerSignature =
14458                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14459                } else if (obj instanceof PackageSetting) {
14460                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14461                } else {
14462                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14463                }
14464            } else {
14465                throw new SecurityException("Unknown calling UID: " + callingUid);
14466            }
14467
14468            // Verify: can't set installerPackageName to a package that is
14469            // not signed with the same cert as the caller.
14470            if (installerPackageSetting != null) {
14471                if (compareSignatures(callerSignature,
14472                        installerPackageSetting.signatures.mSigningDetails.signatures)
14473                        != PackageManager.SIGNATURE_MATCH) {
14474                    throw new SecurityException(
14475                            "Caller does not have same cert as new installer package "
14476                            + installerPackageName);
14477                }
14478            }
14479
14480            // Verify: if target already has an installer package, it must
14481            // be signed with the same cert as the caller.
14482            if (targetPackageSetting.installerPackageName != null) {
14483                PackageSetting setting = mSettings.mPackages.get(
14484                        targetPackageSetting.installerPackageName);
14485                // If the currently set package isn't valid, then it's always
14486                // okay to change it.
14487                if (setting != null) {
14488                    if (compareSignatures(callerSignature,
14489                            setting.signatures.mSigningDetails.signatures)
14490                            != PackageManager.SIGNATURE_MATCH) {
14491                        throw new SecurityException(
14492                                "Caller does not have same cert as old installer package "
14493                                + targetPackageSetting.installerPackageName);
14494                    }
14495                }
14496            }
14497
14498            // Okay!
14499            targetPackageSetting.installerPackageName = installerPackageName;
14500            if (installerPackageName != null) {
14501                mSettings.mInstallerPackages.add(installerPackageName);
14502            }
14503            scheduleWriteSettingsLocked();
14504        }
14505    }
14506
14507    @Override
14508    public void setApplicationCategoryHint(String packageName, int categoryHint,
14509            String callerPackageName) {
14510        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14511            throw new SecurityException("Instant applications don't have access to this method");
14512        }
14513        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14514                callerPackageName);
14515        synchronized (mPackages) {
14516            PackageSetting ps = mSettings.mPackages.get(packageName);
14517            if (ps == null) {
14518                throw new IllegalArgumentException("Unknown target package " + packageName);
14519            }
14520            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14521                throw new IllegalArgumentException("Unknown target package " + packageName);
14522            }
14523            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14524                throw new IllegalArgumentException("Calling package " + callerPackageName
14525                        + " is not installer for " + packageName);
14526            }
14527
14528            if (ps.categoryHint != categoryHint) {
14529                ps.categoryHint = categoryHint;
14530                scheduleWriteSettingsLocked();
14531            }
14532        }
14533    }
14534
14535    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14536        // Queue up an async operation since the package installation may take a little while.
14537        mHandler.post(new Runnable() {
14538            public void run() {
14539                mHandler.removeCallbacks(this);
14540                 // Result object to be returned
14541                PackageInstalledInfo res = new PackageInstalledInfo();
14542                res.setReturnCode(currentStatus);
14543                res.uid = -1;
14544                res.pkg = null;
14545                res.removedInfo = null;
14546                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14547                    args.doPreInstall(res.returnCode);
14548                    synchronized (mInstallLock) {
14549                        installPackageTracedLI(args, res);
14550                    }
14551                    args.doPostInstall(res.returnCode, res.uid);
14552                }
14553
14554                // A restore should be performed at this point if (a) the install
14555                // succeeded, (b) the operation is not an update, and (c) the new
14556                // package has not opted out of backup participation.
14557                final boolean update = res.removedInfo != null
14558                        && res.removedInfo.removedPackage != null;
14559                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14560                boolean doRestore = !update
14561                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14562
14563                // Set up the post-install work request bookkeeping.  This will be used
14564                // and cleaned up by the post-install event handling regardless of whether
14565                // there's a restore pass performed.  Token values are >= 1.
14566                int token;
14567                if (mNextInstallToken < 0) mNextInstallToken = 1;
14568                token = mNextInstallToken++;
14569
14570                PostInstallData data = new PostInstallData(args, res);
14571                mRunningInstalls.put(token, data);
14572                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14573
14574                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14575                    // Pass responsibility to the Backup Manager.  It will perform a
14576                    // restore if appropriate, then pass responsibility back to the
14577                    // Package Manager to run the post-install observer callbacks
14578                    // and broadcasts.
14579                    IBackupManager bm = IBackupManager.Stub.asInterface(
14580                            ServiceManager.getService(Context.BACKUP_SERVICE));
14581                    if (bm != null) {
14582                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14583                                + " to BM for possible restore");
14584                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14585                        try {
14586                            // TODO: http://b/22388012
14587                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14588                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14589                            } else {
14590                                doRestore = false;
14591                            }
14592                        } catch (RemoteException e) {
14593                            // can't happen; the backup manager is local
14594                        } catch (Exception e) {
14595                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14596                            doRestore = false;
14597                        }
14598                    } else {
14599                        Slog.e(TAG, "Backup Manager not found!");
14600                        doRestore = false;
14601                    }
14602                }
14603
14604                if (!doRestore) {
14605                    // No restore possible, or the Backup Manager was mysteriously not
14606                    // available -- just fire the post-install work request directly.
14607                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14608
14609                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14610
14611                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14612                    mHandler.sendMessage(msg);
14613                }
14614            }
14615        });
14616    }
14617
14618    /**
14619     * Callback from PackageSettings whenever an app is first transitioned out of the
14620     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14621     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14622     * here whether the app is the target of an ongoing install, and only send the
14623     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14624     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14625     * handling.
14626     */
14627    void notifyFirstLaunch(final String packageName, final String installerPackage,
14628            final int userId) {
14629        // Serialize this with the rest of the install-process message chain.  In the
14630        // restore-at-install case, this Runnable will necessarily run before the
14631        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14632        // are coherent.  In the non-restore case, the app has already completed install
14633        // and been launched through some other means, so it is not in a problematic
14634        // state for observers to see the FIRST_LAUNCH signal.
14635        mHandler.post(new Runnable() {
14636            @Override
14637            public void run() {
14638                for (int i = 0; i < mRunningInstalls.size(); i++) {
14639                    final PostInstallData data = mRunningInstalls.valueAt(i);
14640                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14641                        continue;
14642                    }
14643                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14644                        // right package; but is it for the right user?
14645                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14646                            if (userId == data.res.newUsers[uIndex]) {
14647                                if (DEBUG_BACKUP) {
14648                                    Slog.i(TAG, "Package " + packageName
14649                                            + " being restored so deferring FIRST_LAUNCH");
14650                                }
14651                                return;
14652                            }
14653                        }
14654                    }
14655                }
14656                // didn't find it, so not being restored
14657                if (DEBUG_BACKUP) {
14658                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14659                }
14660                final boolean isInstantApp = isInstantApp(packageName, userId);
14661                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14662                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14663                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14664            }
14665        });
14666    }
14667
14668    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14669            int[] userIds, int[] instantUserIds) {
14670        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14671                installerPkg, null, userIds, instantUserIds);
14672    }
14673
14674    private abstract class HandlerParams {
14675        private static final int MAX_RETRIES = 4;
14676
14677        /**
14678         * Number of times startCopy() has been attempted and had a non-fatal
14679         * error.
14680         */
14681        private int mRetries = 0;
14682
14683        /** User handle for the user requesting the information or installation. */
14684        private final UserHandle mUser;
14685        String traceMethod;
14686        int traceCookie;
14687
14688        HandlerParams(UserHandle user) {
14689            mUser = user;
14690        }
14691
14692        UserHandle getUser() {
14693            return mUser;
14694        }
14695
14696        HandlerParams setTraceMethod(String traceMethod) {
14697            this.traceMethod = traceMethod;
14698            return this;
14699        }
14700
14701        HandlerParams setTraceCookie(int traceCookie) {
14702            this.traceCookie = traceCookie;
14703            return this;
14704        }
14705
14706        final boolean startCopy() {
14707            boolean res;
14708            try {
14709                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14710
14711                if (++mRetries > MAX_RETRIES) {
14712                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14713                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14714                    handleServiceError();
14715                    return false;
14716                } else {
14717                    handleStartCopy();
14718                    res = true;
14719                }
14720            } catch (RemoteException e) {
14721                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14722                mHandler.sendEmptyMessage(MCS_RECONNECT);
14723                res = false;
14724            }
14725            handleReturnCode();
14726            return res;
14727        }
14728
14729        final void serviceError() {
14730            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14731            handleServiceError();
14732            handleReturnCode();
14733        }
14734
14735        abstract void handleStartCopy() throws RemoteException;
14736        abstract void handleServiceError();
14737        abstract void handleReturnCode();
14738    }
14739
14740    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14741        for (File path : paths) {
14742            try {
14743                mcs.clearDirectory(path.getAbsolutePath());
14744            } catch (RemoteException e) {
14745            }
14746        }
14747    }
14748
14749    static class OriginInfo {
14750        /**
14751         * Location where install is coming from, before it has been
14752         * copied/renamed into place. This could be a single monolithic APK
14753         * file, or a cluster directory. This location may be untrusted.
14754         */
14755        final File file;
14756
14757        /**
14758         * Flag indicating that {@link #file} or {@link #cid} has already been
14759         * staged, meaning downstream users don't need to defensively copy the
14760         * contents.
14761         */
14762        final boolean staged;
14763
14764        /**
14765         * Flag indicating that {@link #file} or {@link #cid} is an already
14766         * installed app that is being moved.
14767         */
14768        final boolean existing;
14769
14770        final String resolvedPath;
14771        final File resolvedFile;
14772
14773        static OriginInfo fromNothing() {
14774            return new OriginInfo(null, false, false);
14775        }
14776
14777        static OriginInfo fromUntrustedFile(File file) {
14778            return new OriginInfo(file, false, false);
14779        }
14780
14781        static OriginInfo fromExistingFile(File file) {
14782            return new OriginInfo(file, false, true);
14783        }
14784
14785        static OriginInfo fromStagedFile(File file) {
14786            return new OriginInfo(file, true, false);
14787        }
14788
14789        private OriginInfo(File file, boolean staged, boolean existing) {
14790            this.file = file;
14791            this.staged = staged;
14792            this.existing = existing;
14793
14794            if (file != null) {
14795                resolvedPath = file.getAbsolutePath();
14796                resolvedFile = file;
14797            } else {
14798                resolvedPath = null;
14799                resolvedFile = null;
14800            }
14801        }
14802    }
14803
14804    static class MoveInfo {
14805        final int moveId;
14806        final String fromUuid;
14807        final String toUuid;
14808        final String packageName;
14809        final String dataAppName;
14810        final int appId;
14811        final String seinfo;
14812        final int targetSdkVersion;
14813
14814        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14815                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14816            this.moveId = moveId;
14817            this.fromUuid = fromUuid;
14818            this.toUuid = toUuid;
14819            this.packageName = packageName;
14820            this.dataAppName = dataAppName;
14821            this.appId = appId;
14822            this.seinfo = seinfo;
14823            this.targetSdkVersion = targetSdkVersion;
14824        }
14825    }
14826
14827    static class VerificationInfo {
14828        /** A constant used to indicate that a uid value is not present. */
14829        public static final int NO_UID = -1;
14830
14831        /** URI referencing where the package was downloaded from. */
14832        final Uri originatingUri;
14833
14834        /** HTTP referrer URI associated with the originatingURI. */
14835        final Uri referrer;
14836
14837        /** UID of the application that the install request originated from. */
14838        final int originatingUid;
14839
14840        /** UID of application requesting the install */
14841        final int installerUid;
14842
14843        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14844            this.originatingUri = originatingUri;
14845            this.referrer = referrer;
14846            this.originatingUid = originatingUid;
14847            this.installerUid = installerUid;
14848        }
14849    }
14850
14851    class InstallParams extends HandlerParams {
14852        final OriginInfo origin;
14853        final MoveInfo move;
14854        final IPackageInstallObserver2 observer;
14855        int installFlags;
14856        final String installerPackageName;
14857        final String volumeUuid;
14858        private InstallArgs mArgs;
14859        private int mRet;
14860        final String packageAbiOverride;
14861        final String[] grantedRuntimePermissions;
14862        final VerificationInfo verificationInfo;
14863        final PackageParser.SigningDetails signingDetails;
14864        final int installReason;
14865
14866        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14867                int installFlags, String installerPackageName, String volumeUuid,
14868                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14869                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
14870            super(user);
14871            this.origin = origin;
14872            this.move = move;
14873            this.observer = observer;
14874            this.installFlags = installFlags;
14875            this.installerPackageName = installerPackageName;
14876            this.volumeUuid = volumeUuid;
14877            this.verificationInfo = verificationInfo;
14878            this.packageAbiOverride = packageAbiOverride;
14879            this.grantedRuntimePermissions = grantedPermissions;
14880            this.signingDetails = signingDetails;
14881            this.installReason = installReason;
14882        }
14883
14884        @Override
14885        public String toString() {
14886            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14887                    + " file=" + origin.file + "}";
14888        }
14889
14890        private int installLocationPolicy(PackageInfoLite pkgLite) {
14891            String packageName = pkgLite.packageName;
14892            int installLocation = pkgLite.installLocation;
14893            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14894            // reader
14895            synchronized (mPackages) {
14896                // Currently installed package which the new package is attempting to replace or
14897                // null if no such package is installed.
14898                PackageParser.Package installedPkg = mPackages.get(packageName);
14899                // Package which currently owns the data which the new package will own if installed.
14900                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14901                // will be null whereas dataOwnerPkg will contain information about the package
14902                // which was uninstalled while keeping its data.
14903                PackageParser.Package dataOwnerPkg = installedPkg;
14904                if (dataOwnerPkg  == null) {
14905                    PackageSetting ps = mSettings.mPackages.get(packageName);
14906                    if (ps != null) {
14907                        dataOwnerPkg = ps.pkg;
14908                    }
14909                }
14910
14911                if (dataOwnerPkg != null) {
14912                    // If installed, the package will get access to data left on the device by its
14913                    // predecessor. As a security measure, this is permited only if this is not a
14914                    // version downgrade or if the predecessor package is marked as debuggable and
14915                    // a downgrade is explicitly requested.
14916                    //
14917                    // On debuggable platform builds, downgrades are permitted even for
14918                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14919                    // not offer security guarantees and thus it's OK to disable some security
14920                    // mechanisms to make debugging/testing easier on those builds. However, even on
14921                    // debuggable builds downgrades of packages are permitted only if requested via
14922                    // installFlags. This is because we aim to keep the behavior of debuggable
14923                    // platform builds as close as possible to the behavior of non-debuggable
14924                    // platform builds.
14925                    final boolean downgradeRequested =
14926                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14927                    final boolean packageDebuggable =
14928                                (dataOwnerPkg.applicationInfo.flags
14929                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14930                    final boolean downgradePermitted =
14931                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14932                    if (!downgradePermitted) {
14933                        try {
14934                            checkDowngrade(dataOwnerPkg, pkgLite);
14935                        } catch (PackageManagerException e) {
14936                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14937                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14938                        }
14939                    }
14940                }
14941
14942                if (installedPkg != null) {
14943                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14944                        // Check for updated system application.
14945                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14946                            if (onSd) {
14947                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14948                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14949                            }
14950                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14951                        } else {
14952                            if (onSd) {
14953                                // Install flag overrides everything.
14954                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14955                            }
14956                            // If current upgrade specifies particular preference
14957                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14958                                // Application explicitly specified internal.
14959                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14960                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14961                                // App explictly prefers external. Let policy decide
14962                            } else {
14963                                // Prefer previous location
14964                                if (isExternal(installedPkg)) {
14965                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14966                                }
14967                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14968                            }
14969                        }
14970                    } else {
14971                        // Invalid install. Return error code
14972                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14973                    }
14974                }
14975            }
14976            // All the special cases have been taken care of.
14977            // Return result based on recommended install location.
14978            if (onSd) {
14979                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14980            }
14981            return pkgLite.recommendedInstallLocation;
14982        }
14983
14984        /*
14985         * Invoke remote method to get package information and install
14986         * location values. Override install location based on default
14987         * policy if needed and then create install arguments based
14988         * on the install location.
14989         */
14990        public void handleStartCopy() throws RemoteException {
14991            int ret = PackageManager.INSTALL_SUCCEEDED;
14992
14993            // If we're already staged, we've firmly committed to an install location
14994            if (origin.staged) {
14995                if (origin.file != null) {
14996                    installFlags |= PackageManager.INSTALL_INTERNAL;
14997                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14998                } else {
14999                    throw new IllegalStateException("Invalid stage location");
15000                }
15001            }
15002
15003            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15004            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15005            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15006            PackageInfoLite pkgLite = null;
15007
15008            if (onInt && onSd) {
15009                // Check if both bits are set.
15010                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15011                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15012            } else if (onSd && ephemeral) {
15013                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15014                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15015            } else {
15016                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15017                        packageAbiOverride);
15018
15019                if (DEBUG_INSTANT && ephemeral) {
15020                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15021                }
15022
15023                /*
15024                 * If we have too little free space, try to free cache
15025                 * before giving up.
15026                 */
15027                if (!origin.staged && pkgLite.recommendedInstallLocation
15028                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15029                    // TODO: focus freeing disk space on the target device
15030                    final StorageManager storage = StorageManager.from(mContext);
15031                    final long lowThreshold = storage.getStorageLowBytes(
15032                            Environment.getDataDirectory());
15033
15034                    final long sizeBytes = mContainerService.calculateInstalledSize(
15035                            origin.resolvedPath, packageAbiOverride);
15036
15037                    try {
15038                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15039                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15040                                installFlags, packageAbiOverride);
15041                    } catch (InstallerException e) {
15042                        Slog.w(TAG, "Failed to free cache", e);
15043                    }
15044
15045                    /*
15046                     * The cache free must have deleted the file we
15047                     * downloaded to install.
15048                     *
15049                     * TODO: fix the "freeCache" call to not delete
15050                     *       the file we care about.
15051                     */
15052                    if (pkgLite.recommendedInstallLocation
15053                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15054                        pkgLite.recommendedInstallLocation
15055                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15056                    }
15057                }
15058            }
15059
15060            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15061                int loc = pkgLite.recommendedInstallLocation;
15062                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15063                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15064                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15065                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15066                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15067                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15068                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15069                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15070                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15071                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15072                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15073                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15074                } else {
15075                    // Override with defaults if needed.
15076                    loc = installLocationPolicy(pkgLite);
15077                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15078                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15079                    } else if (!onSd && !onInt) {
15080                        // Override install location with flags
15081                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15082                            // Set the flag to install on external media.
15083                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15084                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15085                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15086                            if (DEBUG_INSTANT) {
15087                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15088                            }
15089                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15090                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15091                                    |PackageManager.INSTALL_INTERNAL);
15092                        } else {
15093                            // Make sure the flag for installing on external
15094                            // media is unset
15095                            installFlags |= PackageManager.INSTALL_INTERNAL;
15096                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15097                        }
15098                    }
15099                }
15100            }
15101
15102            final InstallArgs args = createInstallArgs(this);
15103            mArgs = args;
15104
15105            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15106                // TODO: http://b/22976637
15107                // Apps installed for "all" users use the device owner to verify the app
15108                UserHandle verifierUser = getUser();
15109                if (verifierUser == UserHandle.ALL) {
15110                    verifierUser = UserHandle.SYSTEM;
15111                }
15112
15113                /*
15114                 * Determine if we have any installed package verifiers. If we
15115                 * do, then we'll defer to them to verify the packages.
15116                 */
15117                final int requiredUid = mRequiredVerifierPackage == null ? -1
15118                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15119                                verifierUser.getIdentifier());
15120                final int installerUid =
15121                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15122                if (!origin.existing && requiredUid != -1
15123                        && isVerificationEnabled(
15124                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15125                    final Intent verification = new Intent(
15126                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15127                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15128                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15129                            PACKAGE_MIME_TYPE);
15130                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15131
15132                    // Query all live verifiers based on current user state
15133                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15134                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15135                            false /*allowDynamicSplits*/);
15136
15137                    if (DEBUG_VERIFY) {
15138                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15139                                + verification.toString() + " with " + pkgLite.verifiers.length
15140                                + " optional verifiers");
15141                    }
15142
15143                    final int verificationId = mPendingVerificationToken++;
15144
15145                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15146
15147                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15148                            installerPackageName);
15149
15150                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15151                            installFlags);
15152
15153                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15154                            pkgLite.packageName);
15155
15156                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15157                            pkgLite.versionCode);
15158
15159                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15160                            pkgLite.getLongVersionCode());
15161
15162                    if (verificationInfo != null) {
15163                        if (verificationInfo.originatingUri != null) {
15164                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15165                                    verificationInfo.originatingUri);
15166                        }
15167                        if (verificationInfo.referrer != null) {
15168                            verification.putExtra(Intent.EXTRA_REFERRER,
15169                                    verificationInfo.referrer);
15170                        }
15171                        if (verificationInfo.originatingUid >= 0) {
15172                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15173                                    verificationInfo.originatingUid);
15174                        }
15175                        if (verificationInfo.installerUid >= 0) {
15176                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15177                                    verificationInfo.installerUid);
15178                        }
15179                    }
15180
15181                    final PackageVerificationState verificationState = new PackageVerificationState(
15182                            requiredUid, args);
15183
15184                    mPendingVerification.append(verificationId, verificationState);
15185
15186                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15187                            receivers, verificationState);
15188
15189                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15190                    final long idleDuration = getVerificationTimeout();
15191
15192                    /*
15193                     * If any sufficient verifiers were listed in the package
15194                     * manifest, attempt to ask them.
15195                     */
15196                    if (sufficientVerifiers != null) {
15197                        final int N = sufficientVerifiers.size();
15198                        if (N == 0) {
15199                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15200                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15201                        } else {
15202                            for (int i = 0; i < N; i++) {
15203                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15204                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15205                                        verifierComponent.getPackageName(), idleDuration,
15206                                        verifierUser.getIdentifier(), false, "package verifier");
15207
15208                                final Intent sufficientIntent = new Intent(verification);
15209                                sufficientIntent.setComponent(verifierComponent);
15210                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15211                            }
15212                        }
15213                    }
15214
15215                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15216                            mRequiredVerifierPackage, receivers);
15217                    if (ret == PackageManager.INSTALL_SUCCEEDED
15218                            && mRequiredVerifierPackage != null) {
15219                        Trace.asyncTraceBegin(
15220                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15221                        /*
15222                         * Send the intent to the required verification agent,
15223                         * but only start the verification timeout after the
15224                         * target BroadcastReceivers have run.
15225                         */
15226                        verification.setComponent(requiredVerifierComponent);
15227                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15228                                mRequiredVerifierPackage, idleDuration,
15229                                verifierUser.getIdentifier(), false, "package verifier");
15230                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15231                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15232                                new BroadcastReceiver() {
15233                                    @Override
15234                                    public void onReceive(Context context, Intent intent) {
15235                                        final Message msg = mHandler
15236                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15237                                        msg.arg1 = verificationId;
15238                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15239                                    }
15240                                }, null, 0, null, null);
15241
15242                        /*
15243                         * We don't want the copy to proceed until verification
15244                         * succeeds, so null out this field.
15245                         */
15246                        mArgs = null;
15247                    }
15248                } else {
15249                    /*
15250                     * No package verification is enabled, so immediately start
15251                     * the remote call to initiate copy using temporary file.
15252                     */
15253                    ret = args.copyApk(mContainerService, true);
15254                }
15255            }
15256
15257            mRet = ret;
15258        }
15259
15260        @Override
15261        void handleReturnCode() {
15262            // If mArgs is null, then MCS couldn't be reached. When it
15263            // reconnects, it will try again to install. At that point, this
15264            // will succeed.
15265            if (mArgs != null) {
15266                processPendingInstall(mArgs, mRet);
15267            }
15268        }
15269
15270        @Override
15271        void handleServiceError() {
15272            mArgs = createInstallArgs(this);
15273            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15274        }
15275    }
15276
15277    private InstallArgs createInstallArgs(InstallParams params) {
15278        if (params.move != null) {
15279            return new MoveInstallArgs(params);
15280        } else {
15281            return new FileInstallArgs(params);
15282        }
15283    }
15284
15285    /**
15286     * Create args that describe an existing installed package. Typically used
15287     * when cleaning up old installs, or used as a move source.
15288     */
15289    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15290            String resourcePath, String[] instructionSets) {
15291        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15292    }
15293
15294    static abstract class InstallArgs {
15295        /** @see InstallParams#origin */
15296        final OriginInfo origin;
15297        /** @see InstallParams#move */
15298        final MoveInfo move;
15299
15300        final IPackageInstallObserver2 observer;
15301        // Always refers to PackageManager flags only
15302        final int installFlags;
15303        final String installerPackageName;
15304        final String volumeUuid;
15305        final UserHandle user;
15306        final String abiOverride;
15307        final String[] installGrantPermissions;
15308        /** If non-null, drop an async trace when the install completes */
15309        final String traceMethod;
15310        final int traceCookie;
15311        final PackageParser.SigningDetails signingDetails;
15312        final int installReason;
15313
15314        // The list of instruction sets supported by this app. This is currently
15315        // only used during the rmdex() phase to clean up resources. We can get rid of this
15316        // if we move dex files under the common app path.
15317        /* nullable */ String[] instructionSets;
15318
15319        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15320                int installFlags, String installerPackageName, String volumeUuid,
15321                UserHandle user, String[] instructionSets,
15322                String abiOverride, String[] installGrantPermissions,
15323                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15324                int installReason) {
15325            this.origin = origin;
15326            this.move = move;
15327            this.installFlags = installFlags;
15328            this.observer = observer;
15329            this.installerPackageName = installerPackageName;
15330            this.volumeUuid = volumeUuid;
15331            this.user = user;
15332            this.instructionSets = instructionSets;
15333            this.abiOverride = abiOverride;
15334            this.installGrantPermissions = installGrantPermissions;
15335            this.traceMethod = traceMethod;
15336            this.traceCookie = traceCookie;
15337            this.signingDetails = signingDetails;
15338            this.installReason = installReason;
15339        }
15340
15341        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15342        abstract int doPreInstall(int status);
15343
15344        /**
15345         * Rename package into final resting place. All paths on the given
15346         * scanned package should be updated to reflect the rename.
15347         */
15348        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15349        abstract int doPostInstall(int status, int uid);
15350
15351        /** @see PackageSettingBase#codePathString */
15352        abstract String getCodePath();
15353        /** @see PackageSettingBase#resourcePathString */
15354        abstract String getResourcePath();
15355
15356        // Need installer lock especially for dex file removal.
15357        abstract void cleanUpResourcesLI();
15358        abstract boolean doPostDeleteLI(boolean delete);
15359
15360        /**
15361         * Called before the source arguments are copied. This is used mostly
15362         * for MoveParams when it needs to read the source file to put it in the
15363         * destination.
15364         */
15365        int doPreCopy() {
15366            return PackageManager.INSTALL_SUCCEEDED;
15367        }
15368
15369        /**
15370         * Called after the source arguments are copied. This is used mostly for
15371         * MoveParams when it needs to read the source file to put it in the
15372         * destination.
15373         */
15374        int doPostCopy(int uid) {
15375            return PackageManager.INSTALL_SUCCEEDED;
15376        }
15377
15378        protected boolean isFwdLocked() {
15379            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15380        }
15381
15382        protected boolean isExternalAsec() {
15383            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15384        }
15385
15386        protected boolean isEphemeral() {
15387            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15388        }
15389
15390        UserHandle getUser() {
15391            return user;
15392        }
15393    }
15394
15395    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15396        if (!allCodePaths.isEmpty()) {
15397            if (instructionSets == null) {
15398                throw new IllegalStateException("instructionSet == null");
15399            }
15400            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15401            for (String codePath : allCodePaths) {
15402                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15403                    try {
15404                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15405                    } catch (InstallerException ignored) {
15406                    }
15407                }
15408            }
15409        }
15410    }
15411
15412    /**
15413     * Logic to handle installation of non-ASEC applications, including copying
15414     * and renaming logic.
15415     */
15416    class FileInstallArgs extends InstallArgs {
15417        private File codeFile;
15418        private File resourceFile;
15419
15420        // Example topology:
15421        // /data/app/com.example/base.apk
15422        // /data/app/com.example/split_foo.apk
15423        // /data/app/com.example/lib/arm/libfoo.so
15424        // /data/app/com.example/lib/arm64/libfoo.so
15425        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15426
15427        /** New install */
15428        FileInstallArgs(InstallParams params) {
15429            super(params.origin, params.move, params.observer, params.installFlags,
15430                    params.installerPackageName, params.volumeUuid,
15431                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15432                    params.grantedRuntimePermissions,
15433                    params.traceMethod, params.traceCookie, params.signingDetails,
15434                    params.installReason);
15435            if (isFwdLocked()) {
15436                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15437            }
15438        }
15439
15440        /** Existing install */
15441        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15442            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15443                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15444                    PackageManager.INSTALL_REASON_UNKNOWN);
15445            this.codeFile = (codePath != null) ? new File(codePath) : null;
15446            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15447        }
15448
15449        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15450            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15451            try {
15452                return doCopyApk(imcs, temp);
15453            } finally {
15454                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15455            }
15456        }
15457
15458        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15459            if (origin.staged) {
15460                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15461                codeFile = origin.file;
15462                resourceFile = origin.file;
15463                return PackageManager.INSTALL_SUCCEEDED;
15464            }
15465
15466            try {
15467                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15468                final File tempDir =
15469                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15470                codeFile = tempDir;
15471                resourceFile = tempDir;
15472            } catch (IOException e) {
15473                Slog.w(TAG, "Failed to create copy file: " + e);
15474                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15475            }
15476
15477            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15478                @Override
15479                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15480                    if (!FileUtils.isValidExtFilename(name)) {
15481                        throw new IllegalArgumentException("Invalid filename: " + name);
15482                    }
15483                    try {
15484                        final File file = new File(codeFile, name);
15485                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15486                                O_RDWR | O_CREAT, 0644);
15487                        Os.chmod(file.getAbsolutePath(), 0644);
15488                        return new ParcelFileDescriptor(fd);
15489                    } catch (ErrnoException e) {
15490                        throw new RemoteException("Failed to open: " + e.getMessage());
15491                    }
15492                }
15493            };
15494
15495            int ret = PackageManager.INSTALL_SUCCEEDED;
15496            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15497            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15498                Slog.e(TAG, "Failed to copy package");
15499                return ret;
15500            }
15501
15502            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15503            NativeLibraryHelper.Handle handle = null;
15504            try {
15505                handle = NativeLibraryHelper.Handle.create(codeFile);
15506                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15507                        abiOverride);
15508            } catch (IOException e) {
15509                Slog.e(TAG, "Copying native libraries failed", e);
15510                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15511            } finally {
15512                IoUtils.closeQuietly(handle);
15513            }
15514
15515            return ret;
15516        }
15517
15518        int doPreInstall(int status) {
15519            if (status != PackageManager.INSTALL_SUCCEEDED) {
15520                cleanUp();
15521            }
15522            return status;
15523        }
15524
15525        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15526            if (status != PackageManager.INSTALL_SUCCEEDED) {
15527                cleanUp();
15528                return false;
15529            }
15530
15531            final File targetDir = codeFile.getParentFile();
15532            final File beforeCodeFile = codeFile;
15533            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15534
15535            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15536            try {
15537                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15538            } catch (ErrnoException e) {
15539                Slog.w(TAG, "Failed to rename", e);
15540                return false;
15541            }
15542
15543            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15544                Slog.w(TAG, "Failed to restorecon");
15545                return false;
15546            }
15547
15548            // Reflect the rename internally
15549            codeFile = afterCodeFile;
15550            resourceFile = afterCodeFile;
15551
15552            // Reflect the rename in scanned details
15553            try {
15554                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15555            } catch (IOException e) {
15556                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15557                return false;
15558            }
15559            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15560                    afterCodeFile, pkg.baseCodePath));
15561            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15562                    afterCodeFile, pkg.splitCodePaths));
15563
15564            // Reflect the rename in app info
15565            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15566            pkg.setApplicationInfoCodePath(pkg.codePath);
15567            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15568            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15569            pkg.setApplicationInfoResourcePath(pkg.codePath);
15570            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15571            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15572
15573            return true;
15574        }
15575
15576        int doPostInstall(int status, int uid) {
15577            if (status != PackageManager.INSTALL_SUCCEEDED) {
15578                cleanUp();
15579            }
15580            return status;
15581        }
15582
15583        @Override
15584        String getCodePath() {
15585            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15586        }
15587
15588        @Override
15589        String getResourcePath() {
15590            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15591        }
15592
15593        private boolean cleanUp() {
15594            if (codeFile == null || !codeFile.exists()) {
15595                return false;
15596            }
15597
15598            removeCodePathLI(codeFile);
15599
15600            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15601                resourceFile.delete();
15602            }
15603
15604            return true;
15605        }
15606
15607        void cleanUpResourcesLI() {
15608            // Try enumerating all code paths before deleting
15609            List<String> allCodePaths = Collections.EMPTY_LIST;
15610            if (codeFile != null && codeFile.exists()) {
15611                try {
15612                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15613                    allCodePaths = pkg.getAllCodePaths();
15614                } catch (PackageParserException e) {
15615                    // Ignored; we tried our best
15616                }
15617            }
15618
15619            cleanUp();
15620            removeDexFiles(allCodePaths, instructionSets);
15621        }
15622
15623        boolean doPostDeleteLI(boolean delete) {
15624            // XXX err, shouldn't we respect the delete flag?
15625            cleanUpResourcesLI();
15626            return true;
15627        }
15628    }
15629
15630    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15631            PackageManagerException {
15632        if (copyRet < 0) {
15633            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15634                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15635                throw new PackageManagerException(copyRet, message);
15636            }
15637        }
15638    }
15639
15640    /**
15641     * Extract the StorageManagerService "container ID" from the full code path of an
15642     * .apk.
15643     */
15644    static String cidFromCodePath(String fullCodePath) {
15645        int eidx = fullCodePath.lastIndexOf("/");
15646        String subStr1 = fullCodePath.substring(0, eidx);
15647        int sidx = subStr1.lastIndexOf("/");
15648        return subStr1.substring(sidx+1, eidx);
15649    }
15650
15651    /**
15652     * Logic to handle movement of existing installed applications.
15653     */
15654    class MoveInstallArgs extends InstallArgs {
15655        private File codeFile;
15656        private File resourceFile;
15657
15658        /** New install */
15659        MoveInstallArgs(InstallParams params) {
15660            super(params.origin, params.move, params.observer, params.installFlags,
15661                    params.installerPackageName, params.volumeUuid,
15662                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15663                    params.grantedRuntimePermissions,
15664                    params.traceMethod, params.traceCookie, params.signingDetails,
15665                    params.installReason);
15666        }
15667
15668        int copyApk(IMediaContainerService imcs, boolean temp) {
15669            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15670                    + move.fromUuid + " to " + move.toUuid);
15671            synchronized (mInstaller) {
15672                try {
15673                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15674                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15675                } catch (InstallerException e) {
15676                    Slog.w(TAG, "Failed to move app", e);
15677                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15678                }
15679            }
15680
15681            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15682            resourceFile = codeFile;
15683            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15684
15685            return PackageManager.INSTALL_SUCCEEDED;
15686        }
15687
15688        int doPreInstall(int status) {
15689            if (status != PackageManager.INSTALL_SUCCEEDED) {
15690                cleanUp(move.toUuid);
15691            }
15692            return status;
15693        }
15694
15695        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15696            if (status != PackageManager.INSTALL_SUCCEEDED) {
15697                cleanUp(move.toUuid);
15698                return false;
15699            }
15700
15701            // Reflect the move in app info
15702            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15703            pkg.setApplicationInfoCodePath(pkg.codePath);
15704            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15705            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15706            pkg.setApplicationInfoResourcePath(pkg.codePath);
15707            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15708            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15709
15710            return true;
15711        }
15712
15713        int doPostInstall(int status, int uid) {
15714            if (status == PackageManager.INSTALL_SUCCEEDED) {
15715                cleanUp(move.fromUuid);
15716            } else {
15717                cleanUp(move.toUuid);
15718            }
15719            return status;
15720        }
15721
15722        @Override
15723        String getCodePath() {
15724            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15725        }
15726
15727        @Override
15728        String getResourcePath() {
15729            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15730        }
15731
15732        private boolean cleanUp(String volumeUuid) {
15733            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15734                    move.dataAppName);
15735            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15736            final int[] userIds = sUserManager.getUserIds();
15737            synchronized (mInstallLock) {
15738                // Clean up both app data and code
15739                // All package moves are frozen until finished
15740                for (int userId : userIds) {
15741                    try {
15742                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15743                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15744                    } catch (InstallerException e) {
15745                        Slog.w(TAG, String.valueOf(e));
15746                    }
15747                }
15748                removeCodePathLI(codeFile);
15749            }
15750            return true;
15751        }
15752
15753        void cleanUpResourcesLI() {
15754            throw new UnsupportedOperationException();
15755        }
15756
15757        boolean doPostDeleteLI(boolean delete) {
15758            throw new UnsupportedOperationException();
15759        }
15760    }
15761
15762    static String getAsecPackageName(String packageCid) {
15763        int idx = packageCid.lastIndexOf("-");
15764        if (idx == -1) {
15765            return packageCid;
15766        }
15767        return packageCid.substring(0, idx);
15768    }
15769
15770    // Utility method used to create code paths based on package name and available index.
15771    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15772        String idxStr = "";
15773        int idx = 1;
15774        // Fall back to default value of idx=1 if prefix is not
15775        // part of oldCodePath
15776        if (oldCodePath != null) {
15777            String subStr = oldCodePath;
15778            // Drop the suffix right away
15779            if (suffix != null && subStr.endsWith(suffix)) {
15780                subStr = subStr.substring(0, subStr.length() - suffix.length());
15781            }
15782            // If oldCodePath already contains prefix find out the
15783            // ending index to either increment or decrement.
15784            int sidx = subStr.lastIndexOf(prefix);
15785            if (sidx != -1) {
15786                subStr = subStr.substring(sidx + prefix.length());
15787                if (subStr != null) {
15788                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15789                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15790                    }
15791                    try {
15792                        idx = Integer.parseInt(subStr);
15793                        if (idx <= 1) {
15794                            idx++;
15795                        } else {
15796                            idx--;
15797                        }
15798                    } catch(NumberFormatException e) {
15799                    }
15800                }
15801            }
15802        }
15803        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15804        return prefix + idxStr;
15805    }
15806
15807    private File getNextCodePath(File targetDir, String packageName) {
15808        File result;
15809        SecureRandom random = new SecureRandom();
15810        byte[] bytes = new byte[16];
15811        do {
15812            random.nextBytes(bytes);
15813            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15814            result = new File(targetDir, packageName + "-" + suffix);
15815        } while (result.exists());
15816        return result;
15817    }
15818
15819    // Utility method that returns the relative package path with respect
15820    // to the installation directory. Like say for /data/data/com.test-1.apk
15821    // string com.test-1 is returned.
15822    static String deriveCodePathName(String codePath) {
15823        if (codePath == null) {
15824            return null;
15825        }
15826        final File codeFile = new File(codePath);
15827        final String name = codeFile.getName();
15828        if (codeFile.isDirectory()) {
15829            return name;
15830        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15831            final int lastDot = name.lastIndexOf('.');
15832            return name.substring(0, lastDot);
15833        } else {
15834            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15835            return null;
15836        }
15837    }
15838
15839    static class PackageInstalledInfo {
15840        String name;
15841        int uid;
15842        // The set of users that originally had this package installed.
15843        int[] origUsers;
15844        // The set of users that now have this package installed.
15845        int[] newUsers;
15846        PackageParser.Package pkg;
15847        int returnCode;
15848        String returnMsg;
15849        String installerPackageName;
15850        PackageRemovedInfo removedInfo;
15851        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15852
15853        public void setError(int code, String msg) {
15854            setReturnCode(code);
15855            setReturnMessage(msg);
15856            Slog.w(TAG, msg);
15857        }
15858
15859        public void setError(String msg, PackageParserException e) {
15860            setReturnCode(e.error);
15861            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15862            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15863            for (int i = 0; i < childCount; i++) {
15864                addedChildPackages.valueAt(i).setError(msg, e);
15865            }
15866            Slog.w(TAG, msg, e);
15867        }
15868
15869        public void setError(String msg, PackageManagerException e) {
15870            returnCode = e.error;
15871            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15872            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15873            for (int i = 0; i < childCount; i++) {
15874                addedChildPackages.valueAt(i).setError(msg, e);
15875            }
15876            Slog.w(TAG, msg, e);
15877        }
15878
15879        public void setReturnCode(int returnCode) {
15880            this.returnCode = returnCode;
15881            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15882            for (int i = 0; i < childCount; i++) {
15883                addedChildPackages.valueAt(i).returnCode = returnCode;
15884            }
15885        }
15886
15887        private void setReturnMessage(String returnMsg) {
15888            this.returnMsg = returnMsg;
15889            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15890            for (int i = 0; i < childCount; i++) {
15891                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15892            }
15893        }
15894
15895        // In some error cases we want to convey more info back to the observer
15896        String origPackage;
15897        String origPermission;
15898    }
15899
15900    /*
15901     * Install a non-existing package.
15902     */
15903    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15904            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15905            String volumeUuid, PackageInstalledInfo res, int installReason) {
15906        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15907
15908        // Remember this for later, in case we need to rollback this install
15909        String pkgName = pkg.packageName;
15910
15911        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15912
15913        synchronized(mPackages) {
15914            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15915            if (renamedPackage != null) {
15916                // A package with the same name is already installed, though
15917                // it has been renamed to an older name.  The package we
15918                // are trying to install should be installed as an update to
15919                // the existing one, but that has not been requested, so bail.
15920                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15921                        + " without first uninstalling package running as "
15922                        + renamedPackage);
15923                return;
15924            }
15925            if (mPackages.containsKey(pkgName)) {
15926                // Don't allow installation over an existing package with the same name.
15927                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15928                        + " without first uninstalling.");
15929                return;
15930            }
15931        }
15932
15933        try {
15934            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
15935                    System.currentTimeMillis(), user);
15936
15937            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15938
15939            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15940                prepareAppDataAfterInstallLIF(newPackage);
15941
15942            } else {
15943                // Remove package from internal structures, but keep around any
15944                // data that might have already existed
15945                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15946                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15947            }
15948        } catch (PackageManagerException e) {
15949            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15950        }
15951
15952        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15953    }
15954
15955    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15956        try (DigestInputStream digestStream =
15957                new DigestInputStream(new FileInputStream(file), digest)) {
15958            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15959        }
15960    }
15961
15962    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15963            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15964            PackageInstalledInfo res, int installReason) {
15965        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15966
15967        final PackageParser.Package oldPackage;
15968        final PackageSetting ps;
15969        final String pkgName = pkg.packageName;
15970        final int[] allUsers;
15971        final int[] installedUsers;
15972
15973        synchronized(mPackages) {
15974            oldPackage = mPackages.get(pkgName);
15975            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15976
15977            // don't allow upgrade to target a release SDK from a pre-release SDK
15978            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15979                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15980            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15981                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15982            if (oldTargetsPreRelease
15983                    && !newTargetsPreRelease
15984                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15985                Slog.w(TAG, "Can't install package targeting released sdk");
15986                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15987                return;
15988            }
15989
15990            ps = mSettings.mPackages.get(pkgName);
15991
15992            // verify signatures are valid
15993            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
15994            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
15995                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
15996                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15997                            "New package not signed by keys specified by upgrade-keysets: "
15998                                    + pkgName);
15999                    return;
16000                }
16001            } else {
16002
16003                // default to original signature matching
16004                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16005                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
16006                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16007                            "New package has a different signature: " + pkgName);
16008                    return;
16009                }
16010            }
16011
16012            // don't allow a system upgrade unless the upgrade hash matches
16013            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16014                byte[] digestBytes = null;
16015                try {
16016                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16017                    updateDigest(digest, new File(pkg.baseCodePath));
16018                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16019                        for (String path : pkg.splitCodePaths) {
16020                            updateDigest(digest, new File(path));
16021                        }
16022                    }
16023                    digestBytes = digest.digest();
16024                } catch (NoSuchAlgorithmException | IOException e) {
16025                    res.setError(INSTALL_FAILED_INVALID_APK,
16026                            "Could not compute hash: " + pkgName);
16027                    return;
16028                }
16029                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16030                    res.setError(INSTALL_FAILED_INVALID_APK,
16031                            "New package fails restrict-update check: " + pkgName);
16032                    return;
16033                }
16034                // retain upgrade restriction
16035                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16036            }
16037
16038            // Check for shared user id changes
16039            String invalidPackageName =
16040                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16041            if (invalidPackageName != null) {
16042                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16043                        "Package " + invalidPackageName + " tried to change user "
16044                                + oldPackage.mSharedUserId);
16045                return;
16046            }
16047
16048            // check if the new package supports all of the abis which the old package supports
16049            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16050            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16051            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16052                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16053                        "Update to package " + pkgName + " doesn't support multi arch");
16054                return;
16055            }
16056
16057            // In case of rollback, remember per-user/profile install state
16058            allUsers = sUserManager.getUserIds();
16059            installedUsers = ps.queryInstalledUsers(allUsers, true);
16060
16061            // don't allow an upgrade from full to ephemeral
16062            if (isInstantApp) {
16063                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16064                    for (int currentUser : allUsers) {
16065                        if (!ps.getInstantApp(currentUser)) {
16066                            // can't downgrade from full to instant
16067                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16068                                    + " for user: " + currentUser);
16069                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16070                            return;
16071                        }
16072                    }
16073                } else if (!ps.getInstantApp(user.getIdentifier())) {
16074                    // can't downgrade from full to instant
16075                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16076                            + " for user: " + user.getIdentifier());
16077                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16078                    return;
16079                }
16080            }
16081        }
16082
16083        // Update what is removed
16084        res.removedInfo = new PackageRemovedInfo(this);
16085        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16086        res.removedInfo.removedPackage = oldPackage.packageName;
16087        res.removedInfo.installerPackageName = ps.installerPackageName;
16088        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16089        res.removedInfo.isUpdate = true;
16090        res.removedInfo.origUsers = installedUsers;
16091        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16092        for (int i = 0; i < installedUsers.length; i++) {
16093            final int userId = installedUsers[i];
16094            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16095        }
16096
16097        final int childCount = (oldPackage.childPackages != null)
16098                ? oldPackage.childPackages.size() : 0;
16099        for (int i = 0; i < childCount; i++) {
16100            boolean childPackageUpdated = false;
16101            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16102            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16103            if (res.addedChildPackages != null) {
16104                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16105                if (childRes != null) {
16106                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16107                    childRes.removedInfo.removedPackage = childPkg.packageName;
16108                    if (childPs != null) {
16109                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16110                    }
16111                    childRes.removedInfo.isUpdate = true;
16112                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16113                    childPackageUpdated = true;
16114                }
16115            }
16116            if (!childPackageUpdated) {
16117                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16118                childRemovedRes.removedPackage = childPkg.packageName;
16119                if (childPs != null) {
16120                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16121                }
16122                childRemovedRes.isUpdate = false;
16123                childRemovedRes.dataRemoved = true;
16124                synchronized (mPackages) {
16125                    if (childPs != null) {
16126                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16127                    }
16128                }
16129                if (res.removedInfo.removedChildPackages == null) {
16130                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16131                }
16132                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16133            }
16134        }
16135
16136        boolean sysPkg = (isSystemApp(oldPackage));
16137        if (sysPkg) {
16138            // Set the system/privileged/oem/vendor/product flags as needed
16139            final boolean privileged =
16140                    (oldPackage.applicationInfo.privateFlags
16141                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16142            final boolean oem =
16143                    (oldPackage.applicationInfo.privateFlags
16144                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16145            final boolean vendor =
16146                    (oldPackage.applicationInfo.privateFlags
16147                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16148            final boolean product =
16149                    (oldPackage.applicationInfo.privateFlags
16150                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16151            final @ParseFlags int systemParseFlags = parseFlags;
16152            final @ScanFlags int systemScanFlags = scanFlags
16153                    | SCAN_AS_SYSTEM
16154                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16155                    | (oem ? SCAN_AS_OEM : 0)
16156                    | (vendor ? SCAN_AS_VENDOR : 0)
16157                    | (product ? SCAN_AS_PRODUCT : 0);
16158
16159            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16160                    user, allUsers, installerPackageName, res, installReason);
16161        } else {
16162            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16163                    user, allUsers, installerPackageName, res, installReason);
16164        }
16165    }
16166
16167    @Override
16168    public List<String> getPreviousCodePaths(String packageName) {
16169        final int callingUid = Binder.getCallingUid();
16170        final List<String> result = new ArrayList<>();
16171        if (getInstantAppPackageName(callingUid) != null) {
16172            return result;
16173        }
16174        final PackageSetting ps = mSettings.mPackages.get(packageName);
16175        if (ps != null
16176                && ps.oldCodePaths != null
16177                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16178            result.addAll(ps.oldCodePaths);
16179        }
16180        return result;
16181    }
16182
16183    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16184            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16185            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16186            String installerPackageName, PackageInstalledInfo res, int installReason) {
16187        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16188                + deletedPackage);
16189
16190        String pkgName = deletedPackage.packageName;
16191        boolean deletedPkg = true;
16192        boolean addedPkg = false;
16193        boolean updatedSettings = false;
16194        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16195        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16196                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16197
16198        final long origUpdateTime = (pkg.mExtras != null)
16199                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16200
16201        // First delete the existing package while retaining the data directory
16202        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16203                res.removedInfo, true, pkg)) {
16204            // If the existing package wasn't successfully deleted
16205            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16206            deletedPkg = false;
16207        } else {
16208            // Successfully deleted the old package; proceed with replace.
16209
16210            // If deleted package lived in a container, give users a chance to
16211            // relinquish resources before killing.
16212            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16213                if (DEBUG_INSTALL) {
16214                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16215                }
16216                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16217                final ArrayList<String> pkgList = new ArrayList<String>(1);
16218                pkgList.add(deletedPackage.applicationInfo.packageName);
16219                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16220            }
16221
16222            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16223                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16224
16225            try {
16226                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16227                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16228                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16229                        installReason);
16230
16231                // Update the in-memory copy of the previous code paths.
16232                PackageSetting ps = mSettings.mPackages.get(pkgName);
16233                if (!killApp) {
16234                    if (ps.oldCodePaths == null) {
16235                        ps.oldCodePaths = new ArraySet<>();
16236                    }
16237                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16238                    if (deletedPackage.splitCodePaths != null) {
16239                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16240                    }
16241                } else {
16242                    ps.oldCodePaths = null;
16243                }
16244                if (ps.childPackageNames != null) {
16245                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16246                        final String childPkgName = ps.childPackageNames.get(i);
16247                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16248                        childPs.oldCodePaths = ps.oldCodePaths;
16249                    }
16250                }
16251                // set instant app status, but, only if it's explicitly specified
16252                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16253                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16254                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16255                prepareAppDataAfterInstallLIF(newPackage);
16256                addedPkg = true;
16257                mDexManager.notifyPackageUpdated(newPackage.packageName,
16258                        newPackage.baseCodePath, newPackage.splitCodePaths);
16259            } catch (PackageManagerException e) {
16260                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16261            }
16262        }
16263
16264        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16265            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16266
16267            // Revert all internal state mutations and added folders for the failed install
16268            if (addedPkg) {
16269                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16270                        res.removedInfo, true, null);
16271            }
16272
16273            // Restore the old package
16274            if (deletedPkg) {
16275                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16276                File restoreFile = new File(deletedPackage.codePath);
16277                // Parse old package
16278                boolean oldExternal = isExternal(deletedPackage);
16279                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16280                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16281                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16282                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16283                try {
16284                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16285                            null);
16286                } catch (PackageManagerException e) {
16287                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16288                            + e.getMessage());
16289                    return;
16290                }
16291
16292                synchronized (mPackages) {
16293                    // Ensure the installer package name up to date
16294                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16295
16296                    // Update permissions for restored package
16297                    mPermissionManager.updatePermissions(
16298                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16299                            mPermissionCallback);
16300
16301                    mSettings.writeLPr();
16302                }
16303
16304                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16305            }
16306        } else {
16307            synchronized (mPackages) {
16308                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16309                if (ps != null) {
16310                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16311                    if (res.removedInfo.removedChildPackages != null) {
16312                        final int childCount = res.removedInfo.removedChildPackages.size();
16313                        // Iterate in reverse as we may modify the collection
16314                        for (int i = childCount - 1; i >= 0; i--) {
16315                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16316                            if (res.addedChildPackages.containsKey(childPackageName)) {
16317                                res.removedInfo.removedChildPackages.removeAt(i);
16318                            } else {
16319                                PackageRemovedInfo childInfo = res.removedInfo
16320                                        .removedChildPackages.valueAt(i);
16321                                childInfo.removedForAllUsers = mPackages.get(
16322                                        childInfo.removedPackage) == null;
16323                            }
16324                        }
16325                    }
16326                }
16327            }
16328        }
16329    }
16330
16331    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16332            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16333            final @ScanFlags int scanFlags, UserHandle user,
16334            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16335            int installReason) {
16336        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16337                + ", old=" + deletedPackage);
16338
16339        final boolean disabledSystem;
16340
16341        // Remove existing system package
16342        removePackageLI(deletedPackage, true);
16343
16344        synchronized (mPackages) {
16345            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16346        }
16347        if (!disabledSystem) {
16348            // We didn't need to disable the .apk as a current system package,
16349            // which means we are replacing another update that is already
16350            // installed.  We need to make sure to delete the older one's .apk.
16351            res.removedInfo.args = createInstallArgsForExisting(0,
16352                    deletedPackage.applicationInfo.getCodePath(),
16353                    deletedPackage.applicationInfo.getResourcePath(),
16354                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16355        } else {
16356            res.removedInfo.args = null;
16357        }
16358
16359        // Successfully disabled the old package. Now proceed with re-installation
16360        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16361                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16362
16363        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16364        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16365                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16366
16367        PackageParser.Package newPackage = null;
16368        try {
16369            // Add the package to the internal data structures
16370            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16371
16372            // Set the update and install times
16373            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16374            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16375                    System.currentTimeMillis());
16376
16377            // Update the package dynamic state if succeeded
16378            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16379                // Now that the install succeeded make sure we remove data
16380                // directories for any child package the update removed.
16381                final int deletedChildCount = (deletedPackage.childPackages != null)
16382                        ? deletedPackage.childPackages.size() : 0;
16383                final int newChildCount = (newPackage.childPackages != null)
16384                        ? newPackage.childPackages.size() : 0;
16385                for (int i = 0; i < deletedChildCount; i++) {
16386                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16387                    boolean childPackageDeleted = true;
16388                    for (int j = 0; j < newChildCount; j++) {
16389                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16390                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16391                            childPackageDeleted = false;
16392                            break;
16393                        }
16394                    }
16395                    if (childPackageDeleted) {
16396                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16397                                deletedChildPkg.packageName);
16398                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16399                            PackageRemovedInfo removedChildRes = res.removedInfo
16400                                    .removedChildPackages.get(deletedChildPkg.packageName);
16401                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16402                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16403                        }
16404                    }
16405                }
16406
16407                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16408                        installReason);
16409                prepareAppDataAfterInstallLIF(newPackage);
16410
16411                mDexManager.notifyPackageUpdated(newPackage.packageName,
16412                            newPackage.baseCodePath, newPackage.splitCodePaths);
16413            }
16414        } catch (PackageManagerException e) {
16415            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16416            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16417        }
16418
16419        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16420            // Re installation failed. Restore old information
16421            // Remove new pkg information
16422            if (newPackage != null) {
16423                removeInstalledPackageLI(newPackage, true);
16424            }
16425            // Add back the old system package
16426            try {
16427                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16428            } catch (PackageManagerException e) {
16429                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16430            }
16431
16432            synchronized (mPackages) {
16433                if (disabledSystem) {
16434                    enableSystemPackageLPw(deletedPackage);
16435                }
16436
16437                // Ensure the installer package name up to date
16438                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16439
16440                // Update permissions for restored package
16441                mPermissionManager.updatePermissions(
16442                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16443                        mPermissionCallback);
16444
16445                mSettings.writeLPr();
16446            }
16447
16448            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16449                    + " after failed upgrade");
16450        }
16451    }
16452
16453    /**
16454     * Checks whether the parent or any of the child packages have a change shared
16455     * user. For a package to be a valid update the shred users of the parent and
16456     * the children should match. We may later support changing child shared users.
16457     * @param oldPkg The updated package.
16458     * @param newPkg The update package.
16459     * @return The shared user that change between the versions.
16460     */
16461    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16462            PackageParser.Package newPkg) {
16463        // Check parent shared user
16464        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16465            return newPkg.packageName;
16466        }
16467        // Check child shared users
16468        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16469        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16470        for (int i = 0; i < newChildCount; i++) {
16471            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16472            // If this child was present, did it have the same shared user?
16473            for (int j = 0; j < oldChildCount; j++) {
16474                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16475                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16476                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16477                    return newChildPkg.packageName;
16478                }
16479            }
16480        }
16481        return null;
16482    }
16483
16484    private void removeNativeBinariesLI(PackageSetting ps) {
16485        // Remove the lib path for the parent package
16486        if (ps != null) {
16487            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16488            // Remove the lib path for the child packages
16489            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16490            for (int i = 0; i < childCount; i++) {
16491                PackageSetting childPs = null;
16492                synchronized (mPackages) {
16493                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16494                }
16495                if (childPs != null) {
16496                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16497                            .legacyNativeLibraryPathString);
16498                }
16499            }
16500        }
16501    }
16502
16503    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16504        // Enable the parent package
16505        mSettings.enableSystemPackageLPw(pkg.packageName);
16506        // Enable the child packages
16507        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16508        for (int i = 0; i < childCount; i++) {
16509            PackageParser.Package childPkg = pkg.childPackages.get(i);
16510            mSettings.enableSystemPackageLPw(childPkg.packageName);
16511        }
16512    }
16513
16514    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16515            PackageParser.Package newPkg) {
16516        // Disable the parent package (parent always replaced)
16517        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16518        // Disable the child packages
16519        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16520        for (int i = 0; i < childCount; i++) {
16521            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16522            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16523            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16524        }
16525        return disabled;
16526    }
16527
16528    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16529            String installerPackageName) {
16530        // Enable the parent package
16531        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16532        // Enable the child packages
16533        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16534        for (int i = 0; i < childCount; i++) {
16535            PackageParser.Package childPkg = pkg.childPackages.get(i);
16536            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16537        }
16538    }
16539
16540    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16541            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16542        // Update the parent package setting
16543        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16544                res, user, installReason);
16545        // Update the child packages setting
16546        final int childCount = (newPackage.childPackages != null)
16547                ? newPackage.childPackages.size() : 0;
16548        for (int i = 0; i < childCount; i++) {
16549            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16550            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16551            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16552                    childRes.origUsers, childRes, user, installReason);
16553        }
16554    }
16555
16556    private void updateSettingsInternalLI(PackageParser.Package pkg,
16557            String installerPackageName, int[] allUsers, int[] installedForUsers,
16558            PackageInstalledInfo res, UserHandle user, int installReason) {
16559        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16560
16561        String pkgName = pkg.packageName;
16562        synchronized (mPackages) {
16563            //write settings. the installStatus will be incomplete at this stage.
16564            //note that the new package setting would have already been
16565            //added to mPackages. It hasn't been persisted yet.
16566            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16567            // TODO: Remove this write? It's also written at the end of this method
16568            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16569            mSettings.writeLPr();
16570            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16571        }
16572
16573        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16574        synchronized (mPackages) {
16575// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16576            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16577                    mPermissionCallback);
16578            // For system-bundled packages, we assume that installing an upgraded version
16579            // of the package implies that the user actually wants to run that new code,
16580            // so we enable the package.
16581            PackageSetting ps = mSettings.mPackages.get(pkgName);
16582            final int userId = user.getIdentifier();
16583            if (ps != null) {
16584                if (isSystemApp(pkg)) {
16585                    if (DEBUG_INSTALL) {
16586                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16587                    }
16588                    // Enable system package for requested users
16589                    if (res.origUsers != null) {
16590                        for (int origUserId : res.origUsers) {
16591                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16592                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16593                                        origUserId, installerPackageName);
16594                            }
16595                        }
16596                    }
16597                    // Also convey the prior install/uninstall state
16598                    if (allUsers != null && installedForUsers != null) {
16599                        for (int currentUserId : allUsers) {
16600                            final boolean installed = ArrayUtils.contains(
16601                                    installedForUsers, currentUserId);
16602                            if (DEBUG_INSTALL) {
16603                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16604                            }
16605                            ps.setInstalled(installed, currentUserId);
16606                        }
16607                        // these install state changes will be persisted in the
16608                        // upcoming call to mSettings.writeLPr().
16609                    }
16610                }
16611                // It's implied that when a user requests installation, they want the app to be
16612                // installed and enabled.
16613                if (userId != UserHandle.USER_ALL) {
16614                    ps.setInstalled(true, userId);
16615                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16616                } else {
16617                    for (int currentUserId : sUserManager.getUserIds()) {
16618                        ps.setInstalled(true, currentUserId);
16619                        ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, currentUserId,
16620                                installerPackageName);
16621                    }
16622                }
16623
16624                // When replacing an existing package, preserve the original install reason for all
16625                // users that had the package installed before.
16626                final Set<Integer> previousUserIds = new ArraySet<>();
16627                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16628                    final int installReasonCount = res.removedInfo.installReasons.size();
16629                    for (int i = 0; i < installReasonCount; i++) {
16630                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16631                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16632                        ps.setInstallReason(previousInstallReason, previousUserId);
16633                        previousUserIds.add(previousUserId);
16634                    }
16635                }
16636
16637                // Set install reason for users that are having the package newly installed.
16638                if (userId == UserHandle.USER_ALL) {
16639                    for (int currentUserId : sUserManager.getUserIds()) {
16640                        if (!previousUserIds.contains(currentUserId)) {
16641                            ps.setInstallReason(installReason, currentUserId);
16642                        }
16643                    }
16644                } else if (!previousUserIds.contains(userId)) {
16645                    ps.setInstallReason(installReason, userId);
16646                }
16647                mSettings.writeKernelMappingLPr(ps);
16648            }
16649            res.name = pkgName;
16650            res.uid = pkg.applicationInfo.uid;
16651            res.pkg = pkg;
16652            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16653            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16654            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16655            //to update install status
16656            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16657            mSettings.writeLPr();
16658            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16659        }
16660
16661        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16662    }
16663
16664    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16665        try {
16666            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16667            installPackageLI(args, res);
16668        } finally {
16669            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16670        }
16671    }
16672
16673    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16674        final int installFlags = args.installFlags;
16675        final String installerPackageName = args.installerPackageName;
16676        final String volumeUuid = args.volumeUuid;
16677        final File tmpPackageFile = new File(args.getCodePath());
16678        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16679        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16680                || (args.volumeUuid != null));
16681        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16682        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16683        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16684        final boolean virtualPreload =
16685                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16686        boolean replace = false;
16687        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16688        if (args.move != null) {
16689            // moving a complete application; perform an initial scan on the new install location
16690            scanFlags |= SCAN_INITIAL;
16691        }
16692        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16693            scanFlags |= SCAN_DONT_KILL_APP;
16694        }
16695        if (instantApp) {
16696            scanFlags |= SCAN_AS_INSTANT_APP;
16697        }
16698        if (fullApp) {
16699            scanFlags |= SCAN_AS_FULL_APP;
16700        }
16701        if (virtualPreload) {
16702            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16703        }
16704
16705        // Result object to be returned
16706        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16707        res.installerPackageName = installerPackageName;
16708
16709        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16710
16711        // Sanity check
16712        if (instantApp && (forwardLocked || onExternal)) {
16713            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16714                    + " external=" + onExternal);
16715            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16716            return;
16717        }
16718
16719        // Retrieve PackageSettings and parse package
16720        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16721                | PackageParser.PARSE_ENFORCE_CODE
16722                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16723                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16724                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16725        PackageParser pp = new PackageParser();
16726        pp.setSeparateProcesses(mSeparateProcesses);
16727        pp.setDisplayMetrics(mMetrics);
16728        pp.setCallback(mPackageParserCallback);
16729
16730        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16731        final PackageParser.Package pkg;
16732        try {
16733            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16734            DexMetadataHelper.validatePackageDexMetadata(pkg);
16735        } catch (PackageParserException e) {
16736            res.setError("Failed parse during installPackageLI", e);
16737            return;
16738        } finally {
16739            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16740        }
16741
16742        // Instant apps have several additional install-time checks.
16743        if (instantApp) {
16744            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16745                Slog.w(TAG,
16746                        "Instant app package " + pkg.packageName + " does not target at least O");
16747                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16748                        "Instant app package must target at least O");
16749                return;
16750            }
16751            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16752                Slog.w(TAG, "Instant app package " + pkg.packageName
16753                        + " does not target targetSandboxVersion 2");
16754                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16755                        "Instant app package must use targetSandboxVersion 2");
16756                return;
16757            }
16758            if (pkg.mSharedUserId != null) {
16759                Slog.w(TAG, "Instant app package " + pkg.packageName
16760                        + " may not declare sharedUserId.");
16761                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16762                        "Instant app package may not declare a sharedUserId");
16763                return;
16764            }
16765        }
16766
16767        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16768            // Static shared libraries have synthetic package names
16769            renameStaticSharedLibraryPackage(pkg);
16770
16771            // No static shared libs on external storage
16772            if (onExternal) {
16773                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16774                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16775                        "Packages declaring static-shared libs cannot be updated");
16776                return;
16777            }
16778        }
16779
16780        // If we are installing a clustered package add results for the children
16781        if (pkg.childPackages != null) {
16782            synchronized (mPackages) {
16783                final int childCount = pkg.childPackages.size();
16784                for (int i = 0; i < childCount; i++) {
16785                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16786                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16787                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16788                    childRes.pkg = childPkg;
16789                    childRes.name = childPkg.packageName;
16790                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16791                    if (childPs != null) {
16792                        childRes.origUsers = childPs.queryInstalledUsers(
16793                                sUserManager.getUserIds(), true);
16794                    }
16795                    if ((mPackages.containsKey(childPkg.packageName))) {
16796                        childRes.removedInfo = new PackageRemovedInfo(this);
16797                        childRes.removedInfo.removedPackage = childPkg.packageName;
16798                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16799                    }
16800                    if (res.addedChildPackages == null) {
16801                        res.addedChildPackages = new ArrayMap<>();
16802                    }
16803                    res.addedChildPackages.put(childPkg.packageName, childRes);
16804                }
16805            }
16806        }
16807
16808        // If package doesn't declare API override, mark that we have an install
16809        // time CPU ABI override.
16810        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16811            pkg.cpuAbiOverride = args.abiOverride;
16812        }
16813
16814        String pkgName = res.name = pkg.packageName;
16815        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16816            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16817                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16818                return;
16819            }
16820        }
16821
16822        try {
16823            // either use what we've been given or parse directly from the APK
16824            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
16825                pkg.setSigningDetails(args.signingDetails);
16826            } else {
16827                PackageParser.collectCertificates(pkg, false /* skipVerify */);
16828            }
16829        } catch (PackageParserException e) {
16830            res.setError("Failed collect during installPackageLI", e);
16831            return;
16832        }
16833
16834        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
16835                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
16836            Slog.w(TAG, "Instant app package " + pkg.packageName
16837                    + " is not signed with at least APK Signature Scheme v2");
16838            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16839                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
16840            return;
16841        }
16842
16843        // Get rid of all references to package scan path via parser.
16844        pp = null;
16845        String oldCodePath = null;
16846        boolean systemApp = false;
16847        synchronized (mPackages) {
16848            // Check if installing already existing package
16849            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16850                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16851                if (pkg.mOriginalPackages != null
16852                        && pkg.mOriginalPackages.contains(oldName)
16853                        && mPackages.containsKey(oldName)) {
16854                    // This package is derived from an original package,
16855                    // and this device has been updating from that original
16856                    // name.  We must continue using the original name, so
16857                    // rename the new package here.
16858                    pkg.setPackageName(oldName);
16859                    pkgName = pkg.packageName;
16860                    replace = true;
16861                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16862                            + oldName + " pkgName=" + pkgName);
16863                } else if (mPackages.containsKey(pkgName)) {
16864                    // This package, under its official name, already exists
16865                    // on the device; we should replace it.
16866                    replace = true;
16867                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16868                }
16869
16870                // Child packages are installed through the parent package
16871                if (pkg.parentPackage != null) {
16872                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16873                            "Package " + pkg.packageName + " is child of package "
16874                                    + pkg.parentPackage.parentPackage + ". Child packages "
16875                                    + "can be updated only through the parent package.");
16876                    return;
16877                }
16878
16879                if (replace) {
16880                    // Prevent apps opting out from runtime permissions
16881                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16882                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16883                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16884                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16885                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16886                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16887                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16888                                        + " doesn't support runtime permissions but the old"
16889                                        + " target SDK " + oldTargetSdk + " does.");
16890                        return;
16891                    }
16892                    // Prevent persistent apps from being updated
16893                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
16894                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
16895                                "Package " + oldPackage.packageName + " is a persistent app. "
16896                                        + "Persistent apps are not updateable.");
16897                        return;
16898                    }
16899                    // Prevent apps from downgrading their targetSandbox.
16900                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16901                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16902                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16903                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16904                                "Package " + pkg.packageName + " new target sandbox "
16905                                + newTargetSandbox + " is incompatible with the previous value of"
16906                                + oldTargetSandbox + ".");
16907                        return;
16908                    }
16909
16910                    // Prevent installing of child packages
16911                    if (oldPackage.parentPackage != null) {
16912                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16913                                "Package " + pkg.packageName + " is child of package "
16914                                        + oldPackage.parentPackage + ". Child packages "
16915                                        + "can be updated only through the parent package.");
16916                        return;
16917                    }
16918                }
16919            }
16920
16921            PackageSetting ps = mSettings.mPackages.get(pkgName);
16922            if (ps != null) {
16923                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16924
16925                // Static shared libs have same package with different versions where
16926                // we internally use a synthetic package name to allow multiple versions
16927                // of the same package, therefore we need to compare signatures against
16928                // the package setting for the latest library version.
16929                PackageSetting signatureCheckPs = ps;
16930                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16931                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16932                    if (libraryEntry != null) {
16933                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16934                    }
16935                }
16936
16937                // Quick sanity check that we're signed correctly if updating;
16938                // we'll check this again later when scanning, but we want to
16939                // bail early here before tripping over redefined permissions.
16940                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16941                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
16942                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
16943                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16944                                + pkg.packageName + " upgrade keys do not match the "
16945                                + "previously installed version");
16946                        return;
16947                    }
16948                } else {
16949                    try {
16950                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
16951                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
16952                        // We don't care about disabledPkgSetting on install for now.
16953                        final boolean compatMatch = verifySignatures(
16954                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
16955                                compareRecover);
16956                        // The new KeySets will be re-added later in the scanning process.
16957                        if (compatMatch) {
16958                            synchronized (mPackages) {
16959                                ksms.removeAppKeySetDataLPw(pkg.packageName);
16960                            }
16961                        }
16962                    } catch (PackageManagerException e) {
16963                        res.setError(e.error, e.getMessage());
16964                        return;
16965                    }
16966                }
16967
16968                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16969                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16970                    systemApp = (ps.pkg.applicationInfo.flags &
16971                            ApplicationInfo.FLAG_SYSTEM) != 0;
16972                }
16973                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16974            }
16975
16976            int N = pkg.permissions.size();
16977            for (int i = N-1; i >= 0; i--) {
16978                final PackageParser.Permission perm = pkg.permissions.get(i);
16979                final BasePermission bp =
16980                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
16981
16982                // Don't allow anyone but the system to define ephemeral permissions.
16983                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
16984                        && !systemApp) {
16985                    Slog.w(TAG, "Non-System package " + pkg.packageName
16986                            + " attempting to delcare ephemeral permission "
16987                            + perm.info.name + "; Removing ephemeral.");
16988                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
16989                }
16990
16991                // Check whether the newly-scanned package wants to define an already-defined perm
16992                if (bp != null) {
16993                    // If the defining package is signed with our cert, it's okay.  This
16994                    // also includes the "updating the same package" case, of course.
16995                    // "updating same package" could also involve key-rotation.
16996                    final boolean sigsOk;
16997                    final String sourcePackageName = bp.getSourcePackageName();
16998                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
16999                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17000                    if (sourcePackageName.equals(pkg.packageName)
17001                            && (ksms.shouldCheckUpgradeKeySetLocked(
17002                                    sourcePackageSetting, scanFlags))) {
17003                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17004                    } else {
17005
17006                        // in the event of signing certificate rotation, we need to see if the
17007                        // package's certificate has rotated from the current one, or if it is an
17008                        // older certificate with which the current is ok with sharing permissions
17009                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17010                                        pkg.mSigningDetails,
17011                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17012                            sigsOk = true;
17013                        } else if (pkg.mSigningDetails.checkCapability(
17014                                        sourcePackageSetting.signatures.mSigningDetails,
17015                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17016
17017                            // the scanned package checks out, has signing certificate rotation
17018                            // history, and is newer; bring it over
17019                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17020                            sigsOk = true;
17021                        } else {
17022                            sigsOk = false;
17023                        }
17024                    }
17025                    if (!sigsOk) {
17026                        // If the owning package is the system itself, we log but allow
17027                        // install to proceed; we fail the install on all other permission
17028                        // redefinitions.
17029                        if (!sourcePackageName.equals("android")) {
17030                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17031                                    + pkg.packageName + " attempting to redeclare permission "
17032                                    + perm.info.name + " already owned by " + sourcePackageName);
17033                            res.origPermission = perm.info.name;
17034                            res.origPackage = sourcePackageName;
17035                            return;
17036                        } else {
17037                            Slog.w(TAG, "Package " + pkg.packageName
17038                                    + " attempting to redeclare system permission "
17039                                    + perm.info.name + "; ignoring new declaration");
17040                            pkg.permissions.remove(i);
17041                        }
17042                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17043                        // Prevent apps to change protection level to dangerous from any other
17044                        // type as this would allow a privilege escalation where an app adds a
17045                        // normal/signature permission in other app's group and later redefines
17046                        // it as dangerous leading to the group auto-grant.
17047                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17048                                == PermissionInfo.PROTECTION_DANGEROUS) {
17049                            if (bp != null && !bp.isRuntime()) {
17050                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17051                                        + "non-runtime permission " + perm.info.name
17052                                        + " to runtime; keeping old protection level");
17053                                perm.info.protectionLevel = bp.getProtectionLevel();
17054                            }
17055                        }
17056                    }
17057                }
17058            }
17059        }
17060
17061        if (systemApp) {
17062            if (onExternal) {
17063                // Abort update; system app can't be replaced with app on sdcard
17064                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17065                        "Cannot install updates to system apps on sdcard");
17066                return;
17067            } else if (instantApp) {
17068                // Abort update; system app can't be replaced with an instant app
17069                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17070                        "Cannot update a system app with an instant app");
17071                return;
17072            }
17073        }
17074
17075        if (args.move != null) {
17076            // We did an in-place move, so dex is ready to roll
17077            scanFlags |= SCAN_NO_DEX;
17078            scanFlags |= SCAN_MOVE;
17079
17080            synchronized (mPackages) {
17081                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17082                if (ps == null) {
17083                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17084                            "Missing settings for moved package " + pkgName);
17085                }
17086
17087                // We moved the entire application as-is, so bring over the
17088                // previously derived ABI information.
17089                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17090                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17091            }
17092
17093        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17094            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17095            scanFlags |= SCAN_NO_DEX;
17096
17097            try {
17098                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17099                    args.abiOverride : pkg.cpuAbiOverride);
17100                final boolean extractNativeLibs = !pkg.isLibrary();
17101                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17102            } catch (PackageManagerException pme) {
17103                Slog.e(TAG, "Error deriving application ABI", pme);
17104                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17105                return;
17106            }
17107
17108            // Shared libraries for the package need to be updated.
17109            synchronized (mPackages) {
17110                try {
17111                    updateSharedLibrariesLPr(pkg, null);
17112                } catch (PackageManagerException e) {
17113                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17114                }
17115            }
17116        }
17117
17118        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17119            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17120            return;
17121        }
17122
17123        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17124            String apkPath = null;
17125            synchronized (mPackages) {
17126                // Note that if the attacker managed to skip verify setup, for example by tampering
17127                // with the package settings, upon reboot we will do full apk verification when
17128                // verity is not detected.
17129                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17130                if (ps != null && ps.isPrivileged()) {
17131                    apkPath = pkg.baseCodePath;
17132                }
17133            }
17134
17135            if (apkPath != null) {
17136                final VerityUtils.SetupResult result =
17137                        VerityUtils.generateApkVeritySetupData(apkPath);
17138                if (result.isOk()) {
17139                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17140                    FileDescriptor fd = result.getUnownedFileDescriptor();
17141                    try {
17142                        mInstaller.installApkVerity(apkPath, fd);
17143                    } catch (InstallerException e) {
17144                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17145                                "Failed to set up verity: " + e);
17146                        return;
17147                    } finally {
17148                        IoUtils.closeQuietly(fd);
17149                    }
17150                } else if (result.isFailed()) {
17151                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17152                    return;
17153                } else {
17154                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17155                    // reboot.
17156                }
17157            }
17158        }
17159
17160        if (!instantApp) {
17161            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17162        } else {
17163            if (DEBUG_DOMAIN_VERIFICATION) {
17164                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17165            }
17166        }
17167
17168        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17169                "installPackageLI")) {
17170            if (replace) {
17171                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17172                    // Static libs have a synthetic package name containing the version
17173                    // and cannot be updated as an update would get a new package name,
17174                    // unless this is the exact same version code which is useful for
17175                    // development.
17176                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17177                    if (existingPkg != null &&
17178                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17179                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17180                                + "static-shared libs cannot be updated");
17181                        return;
17182                    }
17183                }
17184                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17185                        installerPackageName, res, args.installReason);
17186            } else {
17187                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17188                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17189            }
17190        }
17191
17192        // Prepare the application profiles for the new code paths.
17193        // This needs to be done before invoking dexopt so that any install-time profile
17194        // can be used for optimizations.
17195        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17196
17197        // Check whether we need to dexopt the app.
17198        //
17199        // NOTE: it is IMPORTANT to call dexopt:
17200        //   - after doRename which will sync the package data from PackageParser.Package and its
17201        //     corresponding ApplicationInfo.
17202        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17203        //     uid of the application (pkg.applicationInfo.uid).
17204        //     This update happens in place!
17205        //
17206        // We only need to dexopt if the package meets ALL of the following conditions:
17207        //   1) it is not forward locked.
17208        //   2) it is not on on an external ASEC container.
17209        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17210        //
17211        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17212        // complete, so we skip this step during installation. Instead, we'll take extra time
17213        // the first time the instant app starts. It's preferred to do it this way to provide
17214        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17215        // middle of running an instant app. The default behaviour can be overridden
17216        // via gservices.
17217        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17218                && !forwardLocked
17219                && !pkg.applicationInfo.isExternalAsec()
17220                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17221                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17222
17223        if (performDexopt) {
17224            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17225            // Do not run PackageDexOptimizer through the local performDexOpt
17226            // method because `pkg` may not be in `mPackages` yet.
17227            //
17228            // Also, don't fail application installs if the dexopt step fails.
17229            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17230                    REASON_INSTALL,
17231                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17232                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17233            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17234                    null /* instructionSets */,
17235                    getOrCreateCompilerPackageStats(pkg),
17236                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17237                    dexoptOptions);
17238            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17239        }
17240
17241        // Notify BackgroundDexOptService that the package has been changed.
17242        // If this is an update of a package which used to fail to compile,
17243        // BackgroundDexOptService will remove it from its blacklist.
17244        // TODO: Layering violation
17245        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17246
17247        synchronized (mPackages) {
17248            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17249            if (ps != null) {
17250                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17251                ps.setUpdateAvailable(false /*updateAvailable*/);
17252            }
17253
17254            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17255            for (int i = 0; i < childCount; i++) {
17256                PackageParser.Package childPkg = pkg.childPackages.get(i);
17257                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17258                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17259                if (childPs != null) {
17260                    childRes.newUsers = childPs.queryInstalledUsers(
17261                            sUserManager.getUserIds(), true);
17262                }
17263            }
17264
17265            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17266                updateSequenceNumberLP(ps, res.newUsers);
17267                updateInstantAppInstallerLocked(pkgName);
17268            }
17269        }
17270    }
17271
17272    private void startIntentFilterVerifications(int userId, boolean replacing,
17273            PackageParser.Package pkg) {
17274        if (mIntentFilterVerifierComponent == null) {
17275            Slog.w(TAG, "No IntentFilter verification will not be done as "
17276                    + "there is no IntentFilterVerifier available!");
17277            return;
17278        }
17279
17280        final int verifierUid = getPackageUid(
17281                mIntentFilterVerifierComponent.getPackageName(),
17282                MATCH_DEBUG_TRIAGED_MISSING,
17283                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17284
17285        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17286        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17287        mHandler.sendMessage(msg);
17288
17289        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17290        for (int i = 0; i < childCount; i++) {
17291            PackageParser.Package childPkg = pkg.childPackages.get(i);
17292            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17293            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17294            mHandler.sendMessage(msg);
17295        }
17296    }
17297
17298    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17299            PackageParser.Package pkg) {
17300        int size = pkg.activities.size();
17301        if (size == 0) {
17302            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17303                    "No activity, so no need to verify any IntentFilter!");
17304            return;
17305        }
17306
17307        final boolean hasDomainURLs = hasDomainURLs(pkg);
17308        if (!hasDomainURLs) {
17309            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17310                    "No domain URLs, so no need to verify any IntentFilter!");
17311            return;
17312        }
17313
17314        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17315                + " if any IntentFilter from the " + size
17316                + " Activities needs verification ...");
17317
17318        int count = 0;
17319        final String packageName = pkg.packageName;
17320
17321        synchronized (mPackages) {
17322            // If this is a new install and we see that we've already run verification for this
17323            // package, we have nothing to do: it means the state was restored from backup.
17324            if (!replacing) {
17325                IntentFilterVerificationInfo ivi =
17326                        mSettings.getIntentFilterVerificationLPr(packageName);
17327                if (ivi != null) {
17328                    if (DEBUG_DOMAIN_VERIFICATION) {
17329                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17330                                + ivi.getStatusString());
17331                    }
17332                    return;
17333                }
17334            }
17335
17336            // If any filters need to be verified, then all need to be.
17337            boolean needToVerify = false;
17338            for (PackageParser.Activity a : pkg.activities) {
17339                for (ActivityIntentInfo filter : a.intents) {
17340                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17341                        if (DEBUG_DOMAIN_VERIFICATION) {
17342                            Slog.d(TAG,
17343                                    "Intent filter needs verification, so processing all filters");
17344                        }
17345                        needToVerify = true;
17346                        break;
17347                    }
17348                }
17349            }
17350
17351            if (needToVerify) {
17352                final int verificationId = mIntentFilterVerificationToken++;
17353                for (PackageParser.Activity a : pkg.activities) {
17354                    for (ActivityIntentInfo filter : a.intents) {
17355                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17356                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17357                                    "Verification needed for IntentFilter:" + filter.toString());
17358                            mIntentFilterVerifier.addOneIntentFilterVerification(
17359                                    verifierUid, userId, verificationId, filter, packageName);
17360                            count++;
17361                        }
17362                    }
17363                }
17364            }
17365        }
17366
17367        if (count > 0) {
17368            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17369                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17370                    +  " for userId:" + userId);
17371            mIntentFilterVerifier.startVerifications(userId);
17372        } else {
17373            if (DEBUG_DOMAIN_VERIFICATION) {
17374                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17375            }
17376        }
17377    }
17378
17379    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17380        final ComponentName cn  = filter.activity.getComponentName();
17381        final String packageName = cn.getPackageName();
17382
17383        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17384                packageName);
17385        if (ivi == null) {
17386            return true;
17387        }
17388        int status = ivi.getStatus();
17389        switch (status) {
17390            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17391            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17392                return true;
17393
17394            default:
17395                // Nothing to do
17396                return false;
17397        }
17398    }
17399
17400    private static boolean isMultiArch(ApplicationInfo info) {
17401        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17402    }
17403
17404    private static boolean isExternal(PackageParser.Package pkg) {
17405        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17406    }
17407
17408    private static boolean isExternal(PackageSetting ps) {
17409        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17410    }
17411
17412    private static boolean isSystemApp(PackageParser.Package pkg) {
17413        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17414    }
17415
17416    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17417        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17418    }
17419
17420    private static boolean isOemApp(PackageParser.Package pkg) {
17421        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17422    }
17423
17424    private static boolean isVendorApp(PackageParser.Package pkg) {
17425        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17426    }
17427
17428    private static boolean isProductApp(PackageParser.Package pkg) {
17429        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17430    }
17431
17432    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17433        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17434    }
17435
17436    private static boolean isSystemApp(PackageSetting ps) {
17437        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17438    }
17439
17440    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17441        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17442    }
17443
17444    private int packageFlagsToInstallFlags(PackageSetting ps) {
17445        int installFlags = 0;
17446        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17447            // This existing package was an external ASEC install when we have
17448            // the external flag without a UUID
17449            installFlags |= PackageManager.INSTALL_EXTERNAL;
17450        }
17451        if (ps.isForwardLocked()) {
17452            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17453        }
17454        return installFlags;
17455    }
17456
17457    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17458        if (isExternal(pkg)) {
17459            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17460                return mSettings.getExternalVersion();
17461            } else {
17462                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17463            }
17464        } else {
17465            return mSettings.getInternalVersion();
17466        }
17467    }
17468
17469    private void deleteTempPackageFiles() {
17470        final FilenameFilter filter = new FilenameFilter() {
17471            public boolean accept(File dir, String name) {
17472                return name.startsWith("vmdl") && name.endsWith(".tmp");
17473            }
17474        };
17475        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17476            file.delete();
17477        }
17478    }
17479
17480    @Override
17481    public void deletePackageAsUser(String packageName, int versionCode,
17482            IPackageDeleteObserver observer, int userId, int flags) {
17483        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17484                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17485    }
17486
17487    @Override
17488    public void deletePackageVersioned(VersionedPackage versionedPackage,
17489            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17490        final int callingUid = Binder.getCallingUid();
17491        mContext.enforceCallingOrSelfPermission(
17492                android.Manifest.permission.DELETE_PACKAGES, null);
17493        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17494        Preconditions.checkNotNull(versionedPackage);
17495        Preconditions.checkNotNull(observer);
17496        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17497                PackageManager.VERSION_CODE_HIGHEST,
17498                Long.MAX_VALUE, "versionCode must be >= -1");
17499
17500        final String packageName = versionedPackage.getPackageName();
17501        final long versionCode = versionedPackage.getLongVersionCode();
17502        final String internalPackageName;
17503        synchronized (mPackages) {
17504            // Normalize package name to handle renamed packages and static libs
17505            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17506        }
17507
17508        final int uid = Binder.getCallingUid();
17509        if (!isOrphaned(internalPackageName)
17510                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17511            try {
17512                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17513                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17514                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17515                observer.onUserActionRequired(intent);
17516            } catch (RemoteException re) {
17517            }
17518            return;
17519        }
17520        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17521        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17522        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17523            mContext.enforceCallingOrSelfPermission(
17524                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17525                    "deletePackage for user " + userId);
17526        }
17527
17528        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17529            try {
17530                observer.onPackageDeleted(packageName,
17531                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17532            } catch (RemoteException re) {
17533            }
17534            return;
17535        }
17536
17537        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17538            try {
17539                observer.onPackageDeleted(packageName,
17540                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17541            } catch (RemoteException re) {
17542            }
17543            return;
17544        }
17545
17546        if (DEBUG_REMOVE) {
17547            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17548                    + " deleteAllUsers: " + deleteAllUsers + " version="
17549                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17550                    ? "VERSION_CODE_HIGHEST" : versionCode));
17551        }
17552        // Queue up an async operation since the package deletion may take a little while.
17553        mHandler.post(new Runnable() {
17554            public void run() {
17555                mHandler.removeCallbacks(this);
17556                int returnCode;
17557                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17558                boolean doDeletePackage = true;
17559                if (ps != null) {
17560                    final boolean targetIsInstantApp =
17561                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17562                    doDeletePackage = !targetIsInstantApp
17563                            || canViewInstantApps;
17564                }
17565                if (doDeletePackage) {
17566                    if (!deleteAllUsers) {
17567                        returnCode = deletePackageX(internalPackageName, versionCode,
17568                                userId, deleteFlags);
17569                    } else {
17570                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17571                                internalPackageName, users);
17572                        // If nobody is blocking uninstall, proceed with delete for all users
17573                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17574                            returnCode = deletePackageX(internalPackageName, versionCode,
17575                                    userId, deleteFlags);
17576                        } else {
17577                            // Otherwise uninstall individually for users with blockUninstalls=false
17578                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17579                            for (int userId : users) {
17580                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17581                                    returnCode = deletePackageX(internalPackageName, versionCode,
17582                                            userId, userFlags);
17583                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17584                                        Slog.w(TAG, "Package delete failed for user " + userId
17585                                                + ", returnCode " + returnCode);
17586                                    }
17587                                }
17588                            }
17589                            // The app has only been marked uninstalled for certain users.
17590                            // We still need to report that delete was blocked
17591                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17592                        }
17593                    }
17594                } else {
17595                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17596                }
17597                try {
17598                    observer.onPackageDeleted(packageName, returnCode, null);
17599                } catch (RemoteException e) {
17600                    Log.i(TAG, "Observer no longer exists.");
17601                } //end catch
17602            } //end run
17603        });
17604    }
17605
17606    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17607        if (pkg.staticSharedLibName != null) {
17608            return pkg.manifestPackageName;
17609        }
17610        return pkg.packageName;
17611    }
17612
17613    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17614        // Handle renamed packages
17615        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17616        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17617
17618        // Is this a static library?
17619        LongSparseArray<SharedLibraryEntry> versionedLib =
17620                mStaticLibsByDeclaringPackage.get(packageName);
17621        if (versionedLib == null || versionedLib.size() <= 0) {
17622            return packageName;
17623        }
17624
17625        // Figure out which lib versions the caller can see
17626        LongSparseLongArray versionsCallerCanSee = null;
17627        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17628        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17629                && callingAppId != Process.ROOT_UID) {
17630            versionsCallerCanSee = new LongSparseLongArray();
17631            String libName = versionedLib.valueAt(0).info.getName();
17632            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17633            if (uidPackages != null) {
17634                for (String uidPackage : uidPackages) {
17635                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17636                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17637                    if (libIdx >= 0) {
17638                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17639                        versionsCallerCanSee.append(libVersion, libVersion);
17640                    }
17641                }
17642            }
17643        }
17644
17645        // Caller can see nothing - done
17646        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17647            return packageName;
17648        }
17649
17650        // Find the version the caller can see and the app version code
17651        SharedLibraryEntry highestVersion = null;
17652        final int versionCount = versionedLib.size();
17653        for (int i = 0; i < versionCount; i++) {
17654            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17655            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17656                    libEntry.info.getLongVersion()) < 0) {
17657                continue;
17658            }
17659            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17660            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17661                if (libVersionCode == versionCode) {
17662                    return libEntry.apk;
17663                }
17664            } else if (highestVersion == null) {
17665                highestVersion = libEntry;
17666            } else if (libVersionCode  > highestVersion.info
17667                    .getDeclaringPackage().getLongVersionCode()) {
17668                highestVersion = libEntry;
17669            }
17670        }
17671
17672        if (highestVersion != null) {
17673            return highestVersion.apk;
17674        }
17675
17676        return packageName;
17677    }
17678
17679    boolean isCallerVerifier(int callingUid) {
17680        final int callingUserId = UserHandle.getUserId(callingUid);
17681        return mRequiredVerifierPackage != null &&
17682                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17683    }
17684
17685    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17686        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17687              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17688            return true;
17689        }
17690        final int callingUserId = UserHandle.getUserId(callingUid);
17691        // If the caller installed the pkgName, then allow it to silently uninstall.
17692        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17693            return true;
17694        }
17695
17696        // Allow package verifier to silently uninstall.
17697        if (mRequiredVerifierPackage != null &&
17698                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17699            return true;
17700        }
17701
17702        // Allow package uninstaller to silently uninstall.
17703        if (mRequiredUninstallerPackage != null &&
17704                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17705            return true;
17706        }
17707
17708        // Allow storage manager to silently uninstall.
17709        if (mStorageManagerPackage != null &&
17710                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17711            return true;
17712        }
17713
17714        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17715        // uninstall for device owner provisioning.
17716        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17717                == PERMISSION_GRANTED) {
17718            return true;
17719        }
17720
17721        return false;
17722    }
17723
17724    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17725        int[] result = EMPTY_INT_ARRAY;
17726        for (int userId : userIds) {
17727            if (getBlockUninstallForUser(packageName, userId)) {
17728                result = ArrayUtils.appendInt(result, userId);
17729            }
17730        }
17731        return result;
17732    }
17733
17734    @Override
17735    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17736        final int callingUid = Binder.getCallingUid();
17737        if (getInstantAppPackageName(callingUid) != null
17738                && !isCallerSameApp(packageName, callingUid)) {
17739            return false;
17740        }
17741        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17742    }
17743
17744    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17745        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17746                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17747        try {
17748            if (dpm != null) {
17749                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17750                        /* callingUserOnly =*/ false);
17751                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17752                        : deviceOwnerComponentName.getPackageName();
17753                // Does the package contains the device owner?
17754                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17755                // this check is probably not needed, since DO should be registered as a device
17756                // admin on some user too. (Original bug for this: b/17657954)
17757                if (packageName.equals(deviceOwnerPackageName)) {
17758                    return true;
17759                }
17760                // Does it contain a device admin for any user?
17761                int[] users;
17762                if (userId == UserHandle.USER_ALL) {
17763                    users = sUserManager.getUserIds();
17764                } else {
17765                    users = new int[]{userId};
17766                }
17767                for (int i = 0; i < users.length; ++i) {
17768                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17769                        return true;
17770                    }
17771                }
17772            }
17773        } catch (RemoteException e) {
17774        }
17775        return false;
17776    }
17777
17778    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17779        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17780    }
17781
17782    /**
17783     *  This method is an internal method that could be get invoked either
17784     *  to delete an installed package or to clean up a failed installation.
17785     *  After deleting an installed package, a broadcast is sent to notify any
17786     *  listeners that the package has been removed. For cleaning up a failed
17787     *  installation, the broadcast is not necessary since the package's
17788     *  installation wouldn't have sent the initial broadcast either
17789     *  The key steps in deleting a package are
17790     *  deleting the package information in internal structures like mPackages,
17791     *  deleting the packages base directories through installd
17792     *  updating mSettings to reflect current status
17793     *  persisting settings for later use
17794     *  sending a broadcast if necessary
17795     */
17796    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17797        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17798        final boolean res;
17799
17800        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17801                ? UserHandle.USER_ALL : userId;
17802
17803        if (isPackageDeviceAdmin(packageName, removeUser)) {
17804            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17805            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17806        }
17807
17808        PackageSetting uninstalledPs = null;
17809        PackageParser.Package pkg = null;
17810
17811        // for the uninstall-updates case and restricted profiles, remember the per-
17812        // user handle installed state
17813        int[] allUsers;
17814        synchronized (mPackages) {
17815            uninstalledPs = mSettings.mPackages.get(packageName);
17816            if (uninstalledPs == null) {
17817                Slog.w(TAG, "Not removing non-existent package " + packageName);
17818                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17819            }
17820
17821            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17822                    && uninstalledPs.versionCode != versionCode) {
17823                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17824                        + uninstalledPs.versionCode + " != " + versionCode);
17825                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17826            }
17827
17828            // Static shared libs can be declared by any package, so let us not
17829            // allow removing a package if it provides a lib others depend on.
17830            pkg = mPackages.get(packageName);
17831
17832            allUsers = sUserManager.getUserIds();
17833
17834            if (pkg != null && pkg.staticSharedLibName != null) {
17835                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17836                        pkg.staticSharedLibVersion);
17837                if (libEntry != null) {
17838                    for (int currUserId : allUsers) {
17839                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17840                            continue;
17841                        }
17842                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17843                                libEntry.info, 0, currUserId);
17844                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17845                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17846                                    + " hosting lib " + libEntry.info.getName() + " version "
17847                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
17848                                    + " for user " + currUserId);
17849                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17850                        }
17851                    }
17852                }
17853            }
17854
17855            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17856        }
17857
17858        final int freezeUser;
17859        if (isUpdatedSystemApp(uninstalledPs)
17860                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17861            // We're downgrading a system app, which will apply to all users, so
17862            // freeze them all during the downgrade
17863            freezeUser = UserHandle.USER_ALL;
17864        } else {
17865            freezeUser = removeUser;
17866        }
17867
17868        synchronized (mInstallLock) {
17869            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17870            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17871                    deleteFlags, "deletePackageX")) {
17872                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17873                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
17874            }
17875            synchronized (mPackages) {
17876                if (res) {
17877                    if (pkg != null) {
17878                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17879                    }
17880                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
17881                    updateInstantAppInstallerLocked(packageName);
17882                }
17883            }
17884        }
17885
17886        if (res) {
17887            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17888            info.sendPackageRemovedBroadcasts(killApp);
17889            info.sendSystemPackageUpdatedBroadcasts();
17890            info.sendSystemPackageAppearedBroadcasts();
17891        }
17892        // Force a gc here.
17893        Runtime.getRuntime().gc();
17894        // Delete the resources here after sending the broadcast to let
17895        // other processes clean up before deleting resources.
17896        if (info.args != null) {
17897            synchronized (mInstallLock) {
17898                info.args.doPostDeleteLI(true);
17899            }
17900        }
17901
17902        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17903    }
17904
17905    static class PackageRemovedInfo {
17906        final PackageSender packageSender;
17907        String removedPackage;
17908        String installerPackageName;
17909        int uid = -1;
17910        int removedAppId = -1;
17911        int[] origUsers;
17912        int[] removedUsers = null;
17913        int[] broadcastUsers = null;
17914        int[] instantUserIds = null;
17915        SparseArray<Integer> installReasons;
17916        boolean isRemovedPackageSystemUpdate = false;
17917        boolean isUpdate;
17918        boolean dataRemoved;
17919        boolean removedForAllUsers;
17920        boolean isStaticSharedLib;
17921        // Clean up resources deleted packages.
17922        InstallArgs args = null;
17923        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17924        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17925
17926        PackageRemovedInfo(PackageSender packageSender) {
17927            this.packageSender = packageSender;
17928        }
17929
17930        void sendPackageRemovedBroadcasts(boolean killApp) {
17931            sendPackageRemovedBroadcastInternal(killApp);
17932            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17933            for (int i = 0; i < childCount; i++) {
17934                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17935                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17936            }
17937        }
17938
17939        void sendSystemPackageUpdatedBroadcasts() {
17940            if (isRemovedPackageSystemUpdate) {
17941                sendSystemPackageUpdatedBroadcastsInternal();
17942                final int childCount = (removedChildPackages != null)
17943                        ? removedChildPackages.size() : 0;
17944                for (int i = 0; i < childCount; i++) {
17945                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17946                    if (childInfo.isRemovedPackageSystemUpdate) {
17947                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17948                    }
17949                }
17950            }
17951        }
17952
17953        void sendSystemPackageAppearedBroadcasts() {
17954            final int packageCount = (appearedChildPackages != null)
17955                    ? appearedChildPackages.size() : 0;
17956            for (int i = 0; i < packageCount; i++) {
17957                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17958                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
17959                    true /*sendBootCompleted*/, false /*startReceiver*/,
17960                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
17961            }
17962        }
17963
17964        private void sendSystemPackageUpdatedBroadcastsInternal() {
17965            Bundle extras = new Bundle(2);
17966            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17967            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17968            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17969                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17970            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17971                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17972            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
17973                null, null, 0, removedPackage, null, null, null);
17974            if (installerPackageName != null) {
17975                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17976                        removedPackage, extras, 0 /*flags*/,
17977                        installerPackageName, null, null, null);
17978                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17979                        removedPackage, extras, 0 /*flags*/,
17980                        installerPackageName, null, null, null);
17981            }
17982        }
17983
17984        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17985            // Don't send static shared library removal broadcasts as these
17986            // libs are visible only the the apps that depend on them an one
17987            // cannot remove the library if it has a dependency.
17988            if (isStaticSharedLib) {
17989                return;
17990            }
17991            Bundle extras = new Bundle(2);
17992            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17993            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17994            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17995            if (isUpdate || isRemovedPackageSystemUpdate) {
17996                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17997            }
17998            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17999            if (removedPackage != null) {
18000                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18001                    removedPackage, extras, 0, null /*targetPackage*/, null,
18002                    broadcastUsers, instantUserIds);
18003                if (installerPackageName != null) {
18004                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18005                            removedPackage, extras, 0 /*flags*/,
18006                            installerPackageName, null, broadcastUsers, instantUserIds);
18007                }
18008                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18009                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18010                        removedPackage, extras,
18011                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18012                        null, null, broadcastUsers, instantUserIds);
18013                    packageSender.notifyPackageRemoved(removedPackage);
18014                }
18015            }
18016            if (removedAppId >= 0) {
18017                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18018                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18019                    null, null, broadcastUsers, instantUserIds);
18020            }
18021        }
18022
18023        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18024            removedUsers = userIds;
18025            if (removedUsers == null) {
18026                broadcastUsers = null;
18027                return;
18028            }
18029
18030            broadcastUsers = EMPTY_INT_ARRAY;
18031            instantUserIds = EMPTY_INT_ARRAY;
18032            for (int i = userIds.length - 1; i >= 0; --i) {
18033                final int userId = userIds[i];
18034                if (deletedPackageSetting.getInstantApp(userId)) {
18035                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18036                } else {
18037                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18038                }
18039            }
18040        }
18041    }
18042
18043    /*
18044     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18045     * flag is not set, the data directory is removed as well.
18046     * make sure this flag is set for partially installed apps. If not its meaningless to
18047     * delete a partially installed application.
18048     */
18049    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18050            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18051        String packageName = ps.name;
18052        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18053        // Retrieve object to delete permissions for shared user later on
18054        final PackageParser.Package deletedPkg;
18055        final PackageSetting deletedPs;
18056        // reader
18057        synchronized (mPackages) {
18058            deletedPkg = mPackages.get(packageName);
18059            deletedPs = mSettings.mPackages.get(packageName);
18060            if (outInfo != null) {
18061                outInfo.removedPackage = packageName;
18062                outInfo.installerPackageName = ps.installerPackageName;
18063                outInfo.isStaticSharedLib = deletedPkg != null
18064                        && deletedPkg.staticSharedLibName != null;
18065                outInfo.populateUsers(deletedPs == null ? null
18066                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18067            }
18068        }
18069
18070        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18071
18072        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18073            final PackageParser.Package resolvedPkg;
18074            if (deletedPkg != null) {
18075                resolvedPkg = deletedPkg;
18076            } else {
18077                // We don't have a parsed package when it lives on an ejected
18078                // adopted storage device, so fake something together
18079                resolvedPkg = new PackageParser.Package(ps.name);
18080                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18081            }
18082            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18083                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18084            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18085            if (outInfo != null) {
18086                outInfo.dataRemoved = true;
18087            }
18088            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18089        }
18090
18091        int removedAppId = -1;
18092
18093        // writer
18094        synchronized (mPackages) {
18095            boolean installedStateChanged = false;
18096            if (deletedPs != null) {
18097                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18098                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18099                    clearDefaultBrowserIfNeeded(packageName);
18100                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18101                    removedAppId = mSettings.removePackageLPw(packageName);
18102                    if (outInfo != null) {
18103                        outInfo.removedAppId = removedAppId;
18104                    }
18105                    mPermissionManager.updatePermissions(
18106                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18107                    if (deletedPs.sharedUser != null) {
18108                        // Remove permissions associated with package. Since runtime
18109                        // permissions are per user we have to kill the removed package
18110                        // or packages running under the shared user of the removed
18111                        // package if revoking the permissions requested only by the removed
18112                        // package is successful and this causes a change in gids.
18113                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18114                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18115                                    userId);
18116                            if (userIdToKill == UserHandle.USER_ALL
18117                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18118                                // If gids changed for this user, kill all affected packages.
18119                                mHandler.post(new Runnable() {
18120                                    @Override
18121                                    public void run() {
18122                                        // This has to happen with no lock held.
18123                                        killApplication(deletedPs.name, deletedPs.appId,
18124                                                KILL_APP_REASON_GIDS_CHANGED);
18125                                    }
18126                                });
18127                                break;
18128                            }
18129                        }
18130                    }
18131                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18132                }
18133                // make sure to preserve per-user disabled state if this removal was just
18134                // a downgrade of a system app to the factory package
18135                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18136                    if (DEBUG_REMOVE) {
18137                        Slog.d(TAG, "Propagating install state across downgrade");
18138                    }
18139                    for (int userId : allUserHandles) {
18140                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18141                        if (DEBUG_REMOVE) {
18142                            Slog.d(TAG, "    user " + userId + " => " + installed);
18143                        }
18144                        if (installed != ps.getInstalled(userId)) {
18145                            installedStateChanged = true;
18146                        }
18147                        ps.setInstalled(installed, userId);
18148                    }
18149                }
18150            }
18151            // can downgrade to reader
18152            if (writeSettings) {
18153                // Save settings now
18154                mSettings.writeLPr();
18155            }
18156            if (installedStateChanged) {
18157                mSettings.writeKernelMappingLPr(ps);
18158            }
18159        }
18160        if (removedAppId != -1) {
18161            // A user ID was deleted here. Go through all users and remove it
18162            // from KeyStore.
18163            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18164        }
18165    }
18166
18167    static boolean locationIsPrivileged(String path) {
18168        try {
18169            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18170            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18171            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18172            return path.startsWith(privilegedAppDir.getCanonicalPath())
18173                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18174                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18175        } catch (IOException e) {
18176            Slog.e(TAG, "Unable to access code path " + path);
18177        }
18178        return false;
18179    }
18180
18181    static boolean locationIsOem(String path) {
18182        try {
18183            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18184        } catch (IOException e) {
18185            Slog.e(TAG, "Unable to access code path " + path);
18186        }
18187        return false;
18188    }
18189
18190    static boolean locationIsVendor(String path) {
18191        try {
18192            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath());
18193        } catch (IOException e) {
18194            Slog.e(TAG, "Unable to access code path " + path);
18195        }
18196        return false;
18197    }
18198
18199    static boolean locationIsProduct(String path) {
18200        try {
18201            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18202        } catch (IOException e) {
18203            Slog.e(TAG, "Unable to access code path " + path);
18204        }
18205        return false;
18206    }
18207
18208    /*
18209     * Tries to delete system package.
18210     */
18211    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18212            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18213            boolean writeSettings) {
18214        if (deletedPs.parentPackageName != null) {
18215            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18216            return false;
18217        }
18218
18219        final boolean applyUserRestrictions
18220                = (allUserHandles != null) && (outInfo.origUsers != null);
18221        final PackageSetting disabledPs;
18222        // Confirm if the system package has been updated
18223        // An updated system app can be deleted. This will also have to restore
18224        // the system pkg from system partition
18225        // reader
18226        synchronized (mPackages) {
18227            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18228        }
18229
18230        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18231                + " disabledPs=" + disabledPs);
18232
18233        if (disabledPs == null) {
18234            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18235            return false;
18236        } else if (DEBUG_REMOVE) {
18237            Slog.d(TAG, "Deleting system pkg from data partition");
18238        }
18239
18240        if (DEBUG_REMOVE) {
18241            if (applyUserRestrictions) {
18242                Slog.d(TAG, "Remembering install states:");
18243                for (int userId : allUserHandles) {
18244                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18245                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18246                }
18247            }
18248        }
18249
18250        // Delete the updated package
18251        outInfo.isRemovedPackageSystemUpdate = true;
18252        if (outInfo.removedChildPackages != null) {
18253            final int childCount = (deletedPs.childPackageNames != null)
18254                    ? deletedPs.childPackageNames.size() : 0;
18255            for (int i = 0; i < childCount; i++) {
18256                String childPackageName = deletedPs.childPackageNames.get(i);
18257                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18258                        .contains(childPackageName)) {
18259                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18260                            childPackageName);
18261                    if (childInfo != null) {
18262                        childInfo.isRemovedPackageSystemUpdate = true;
18263                    }
18264                }
18265            }
18266        }
18267
18268        if (disabledPs.versionCode < deletedPs.versionCode) {
18269            // Delete data for downgrades
18270            flags &= ~PackageManager.DELETE_KEEP_DATA;
18271        } else {
18272            // Preserve data by setting flag
18273            flags |= PackageManager.DELETE_KEEP_DATA;
18274        }
18275
18276        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18277                outInfo, writeSettings, disabledPs.pkg);
18278        if (!ret) {
18279            return false;
18280        }
18281
18282        // writer
18283        synchronized (mPackages) {
18284            // NOTE: The system package always needs to be enabled; even if it's for
18285            // a compressed stub. If we don't, installing the system package fails
18286            // during scan [scanning checks the disabled packages]. We will reverse
18287            // this later, after we've "installed" the stub.
18288            // Reinstate the old system package
18289            enableSystemPackageLPw(disabledPs.pkg);
18290            // Remove any native libraries from the upgraded package.
18291            removeNativeBinariesLI(deletedPs);
18292        }
18293
18294        // Install the system package
18295        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18296        try {
18297            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18298                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18299        } catch (PackageManagerException e) {
18300            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18301                    + e.getMessage());
18302            return false;
18303        } finally {
18304            if (disabledPs.pkg.isStub) {
18305                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18306            }
18307        }
18308        return true;
18309    }
18310
18311    /**
18312     * Installs a package that's already on the system partition.
18313     */
18314    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18315            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18316            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18317                    throws PackageManagerException {
18318        @ParseFlags int parseFlags =
18319                mDefParseFlags
18320                | PackageParser.PARSE_MUST_BE_APK
18321                | PackageParser.PARSE_IS_SYSTEM_DIR;
18322        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18323        if (isPrivileged || locationIsPrivileged(codePathString)) {
18324            scanFlags |= SCAN_AS_PRIVILEGED;
18325        }
18326        if (locationIsOem(codePathString)) {
18327            scanFlags |= SCAN_AS_OEM;
18328        }
18329        if (locationIsVendor(codePathString)) {
18330            scanFlags |= SCAN_AS_VENDOR;
18331        }
18332        if (locationIsProduct(codePathString)) {
18333            scanFlags |= SCAN_AS_PRODUCT;
18334        }
18335
18336        final File codePath = new File(codePathString);
18337        final PackageParser.Package pkg =
18338                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18339
18340        try {
18341            // update shared libraries for the newly re-installed system package
18342            updateSharedLibrariesLPr(pkg, null);
18343        } catch (PackageManagerException e) {
18344            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18345        }
18346
18347        prepareAppDataAfterInstallLIF(pkg);
18348
18349        // writer
18350        synchronized (mPackages) {
18351            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18352
18353            // Propagate the permissions state as we do not want to drop on the floor
18354            // runtime permissions. The update permissions method below will take
18355            // care of removing obsolete permissions and grant install permissions.
18356            if (origPermissionState != null) {
18357                ps.getPermissionsState().copyFrom(origPermissionState);
18358            }
18359            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18360                    mPermissionCallback);
18361
18362            final boolean applyUserRestrictions
18363                    = (allUserHandles != null) && (origUserHandles != null);
18364            if (applyUserRestrictions) {
18365                boolean installedStateChanged = false;
18366                if (DEBUG_REMOVE) {
18367                    Slog.d(TAG, "Propagating install state across reinstall");
18368                }
18369                for (int userId : allUserHandles) {
18370                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18371                    if (DEBUG_REMOVE) {
18372                        Slog.d(TAG, "    user " + userId + " => " + installed);
18373                    }
18374                    if (installed != ps.getInstalled(userId)) {
18375                        installedStateChanged = true;
18376                    }
18377                    ps.setInstalled(installed, userId);
18378
18379                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18380                }
18381                // Regardless of writeSettings we need to ensure that this restriction
18382                // state propagation is persisted
18383                mSettings.writeAllUsersPackageRestrictionsLPr();
18384                if (installedStateChanged) {
18385                    mSettings.writeKernelMappingLPr(ps);
18386                }
18387            }
18388            // can downgrade to reader here
18389            if (writeSettings) {
18390                mSettings.writeLPr();
18391            }
18392        }
18393        return pkg;
18394    }
18395
18396    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18397            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18398            PackageRemovedInfo outInfo, boolean writeSettings,
18399            PackageParser.Package replacingPackage) {
18400        synchronized (mPackages) {
18401            if (outInfo != null) {
18402                outInfo.uid = ps.appId;
18403            }
18404
18405            if (outInfo != null && outInfo.removedChildPackages != null) {
18406                final int childCount = (ps.childPackageNames != null)
18407                        ? ps.childPackageNames.size() : 0;
18408                for (int i = 0; i < childCount; i++) {
18409                    String childPackageName = ps.childPackageNames.get(i);
18410                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18411                    if (childPs == null) {
18412                        return false;
18413                    }
18414                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18415                            childPackageName);
18416                    if (childInfo != null) {
18417                        childInfo.uid = childPs.appId;
18418                    }
18419                }
18420            }
18421        }
18422
18423        // Delete package data from internal structures and also remove data if flag is set
18424        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18425
18426        // Delete the child packages data
18427        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18428        for (int i = 0; i < childCount; i++) {
18429            PackageSetting childPs;
18430            synchronized (mPackages) {
18431                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18432            }
18433            if (childPs != null) {
18434                PackageRemovedInfo childOutInfo = (outInfo != null
18435                        && outInfo.removedChildPackages != null)
18436                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18437                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18438                        && (replacingPackage != null
18439                        && !replacingPackage.hasChildPackage(childPs.name))
18440                        ? flags & ~DELETE_KEEP_DATA : flags;
18441                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18442                        deleteFlags, writeSettings);
18443            }
18444        }
18445
18446        // Delete application code and resources only for parent packages
18447        if (ps.parentPackageName == null) {
18448            if (deleteCodeAndResources && (outInfo != null)) {
18449                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18450                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18451                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18452            }
18453        }
18454
18455        return true;
18456    }
18457
18458    @Override
18459    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18460            int userId) {
18461        mContext.enforceCallingOrSelfPermission(
18462                android.Manifest.permission.DELETE_PACKAGES, null);
18463        synchronized (mPackages) {
18464            // Cannot block uninstall of static shared libs as they are
18465            // considered a part of the using app (emulating static linking).
18466            // Also static libs are installed always on internal storage.
18467            PackageParser.Package pkg = mPackages.get(packageName);
18468            if (pkg != null && pkg.staticSharedLibName != null) {
18469                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18470                        + " providing static shared library: " + pkg.staticSharedLibName);
18471                return false;
18472            }
18473            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18474            mSettings.writePackageRestrictionsLPr(userId);
18475        }
18476        return true;
18477    }
18478
18479    @Override
18480    public boolean getBlockUninstallForUser(String packageName, int userId) {
18481        synchronized (mPackages) {
18482            final PackageSetting ps = mSettings.mPackages.get(packageName);
18483            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18484                return false;
18485            }
18486            return mSettings.getBlockUninstallLPr(userId, packageName);
18487        }
18488    }
18489
18490    @Override
18491    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18492        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18493        synchronized (mPackages) {
18494            PackageSetting ps = mSettings.mPackages.get(packageName);
18495            if (ps == null) {
18496                Log.w(TAG, "Package doesn't exist: " + packageName);
18497                return false;
18498            }
18499            if (systemUserApp) {
18500                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18501            } else {
18502                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18503            }
18504            mSettings.writeLPr();
18505        }
18506        return true;
18507    }
18508
18509    /*
18510     * This method handles package deletion in general
18511     */
18512    private boolean deletePackageLIF(String packageName, UserHandle user,
18513            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18514            PackageRemovedInfo outInfo, boolean writeSettings,
18515            PackageParser.Package replacingPackage) {
18516        if (packageName == null) {
18517            Slog.w(TAG, "Attempt to delete null packageName.");
18518            return false;
18519        }
18520
18521        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18522
18523        PackageSetting ps;
18524        synchronized (mPackages) {
18525            ps = mSettings.mPackages.get(packageName);
18526            if (ps == null) {
18527                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18528                return false;
18529            }
18530
18531            if (ps.parentPackageName != null && (!isSystemApp(ps)
18532                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18533                if (DEBUG_REMOVE) {
18534                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18535                            + ((user == null) ? UserHandle.USER_ALL : user));
18536                }
18537                final int removedUserId = (user != null) ? user.getIdentifier()
18538                        : UserHandle.USER_ALL;
18539                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18540                    return false;
18541                }
18542                markPackageUninstalledForUserLPw(ps, user);
18543                scheduleWritePackageRestrictionsLocked(user);
18544                return true;
18545            }
18546        }
18547
18548        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18549                && user.getIdentifier() != UserHandle.USER_ALL)) {
18550            // The caller is asking that the package only be deleted for a single
18551            // user.  To do this, we just mark its uninstalled state and delete
18552            // its data. If this is a system app, we only allow this to happen if
18553            // they have set the special DELETE_SYSTEM_APP which requests different
18554            // semantics than normal for uninstalling system apps.
18555            markPackageUninstalledForUserLPw(ps, user);
18556
18557            if (!isSystemApp(ps)) {
18558                // Do not uninstall the APK if an app should be cached
18559                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18560                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18561                    // Other user still have this package installed, so all
18562                    // we need to do is clear this user's data and save that
18563                    // it is uninstalled.
18564                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18565                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18566                        return false;
18567                    }
18568                    scheduleWritePackageRestrictionsLocked(user);
18569                    return true;
18570                } else {
18571                    // We need to set it back to 'installed' so the uninstall
18572                    // broadcasts will be sent correctly.
18573                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18574                    ps.setInstalled(true, user.getIdentifier());
18575                    mSettings.writeKernelMappingLPr(ps);
18576                }
18577            } else {
18578                // This is a system app, so we assume that the
18579                // other users still have this package installed, so all
18580                // we need to do is clear this user's data and save that
18581                // it is uninstalled.
18582                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18583                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18584                    return false;
18585                }
18586                scheduleWritePackageRestrictionsLocked(user);
18587                return true;
18588            }
18589        }
18590
18591        // If we are deleting a composite package for all users, keep track
18592        // of result for each child.
18593        if (ps.childPackageNames != null && outInfo != null) {
18594            synchronized (mPackages) {
18595                final int childCount = ps.childPackageNames.size();
18596                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18597                for (int i = 0; i < childCount; i++) {
18598                    String childPackageName = ps.childPackageNames.get(i);
18599                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18600                    childInfo.removedPackage = childPackageName;
18601                    childInfo.installerPackageName = ps.installerPackageName;
18602                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18603                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18604                    if (childPs != null) {
18605                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18606                    }
18607                }
18608            }
18609        }
18610
18611        boolean ret = false;
18612        if (isSystemApp(ps)) {
18613            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18614            // When an updated system application is deleted we delete the existing resources
18615            // as well and fall back to existing code in system partition
18616            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18617        } else {
18618            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18619            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18620                    outInfo, writeSettings, replacingPackage);
18621        }
18622
18623        // Take a note whether we deleted the package for all users
18624        if (outInfo != null) {
18625            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18626            if (outInfo.removedChildPackages != null) {
18627                synchronized (mPackages) {
18628                    final int childCount = outInfo.removedChildPackages.size();
18629                    for (int i = 0; i < childCount; i++) {
18630                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18631                        if (childInfo != null) {
18632                            childInfo.removedForAllUsers = mPackages.get(
18633                                    childInfo.removedPackage) == null;
18634                        }
18635                    }
18636                }
18637            }
18638            // If we uninstalled an update to a system app there may be some
18639            // child packages that appeared as they are declared in the system
18640            // app but were not declared in the update.
18641            if (isSystemApp(ps)) {
18642                synchronized (mPackages) {
18643                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18644                    final int childCount = (updatedPs.childPackageNames != null)
18645                            ? updatedPs.childPackageNames.size() : 0;
18646                    for (int i = 0; i < childCount; i++) {
18647                        String childPackageName = updatedPs.childPackageNames.get(i);
18648                        if (outInfo.removedChildPackages == null
18649                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18650                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18651                            if (childPs == null) {
18652                                continue;
18653                            }
18654                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18655                            installRes.name = childPackageName;
18656                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18657                            installRes.pkg = mPackages.get(childPackageName);
18658                            installRes.uid = childPs.pkg.applicationInfo.uid;
18659                            if (outInfo.appearedChildPackages == null) {
18660                                outInfo.appearedChildPackages = new ArrayMap<>();
18661                            }
18662                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18663                        }
18664                    }
18665                }
18666            }
18667        }
18668
18669        return ret;
18670    }
18671
18672    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18673        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18674                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18675        for (int nextUserId : userIds) {
18676            if (DEBUG_REMOVE) {
18677                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18678            }
18679            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18680                    false /*installed*/,
18681                    true /*stopped*/,
18682                    true /*notLaunched*/,
18683                    false /*hidden*/,
18684                    false /*suspended*/,
18685                    false /*instantApp*/,
18686                    false /*virtualPreload*/,
18687                    null /*lastDisableAppCaller*/,
18688                    null /*enabledComponents*/,
18689                    null /*disabledComponents*/,
18690                    ps.readUserState(nextUserId).domainVerificationStatus,
18691                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18692                    null /*harmfulAppWarning*/);
18693        }
18694        mSettings.writeKernelMappingLPr(ps);
18695    }
18696
18697    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18698            PackageRemovedInfo outInfo) {
18699        final PackageParser.Package pkg;
18700        synchronized (mPackages) {
18701            pkg = mPackages.get(ps.name);
18702        }
18703
18704        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18705                : new int[] {userId};
18706        for (int nextUserId : userIds) {
18707            if (DEBUG_REMOVE) {
18708                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18709                        + nextUserId);
18710            }
18711
18712            destroyAppDataLIF(pkg, userId,
18713                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18714            destroyAppProfilesLIF(pkg, userId);
18715            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18716            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18717            schedulePackageCleaning(ps.name, nextUserId, false);
18718            synchronized (mPackages) {
18719                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18720                    scheduleWritePackageRestrictionsLocked(nextUserId);
18721                }
18722                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18723            }
18724        }
18725
18726        if (outInfo != null) {
18727            outInfo.removedPackage = ps.name;
18728            outInfo.installerPackageName = ps.installerPackageName;
18729            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18730            outInfo.removedAppId = ps.appId;
18731            outInfo.removedUsers = userIds;
18732            outInfo.broadcastUsers = userIds;
18733        }
18734
18735        return true;
18736    }
18737
18738    private final class ClearStorageConnection implements ServiceConnection {
18739        IMediaContainerService mContainerService;
18740
18741        @Override
18742        public void onServiceConnected(ComponentName name, IBinder service) {
18743            synchronized (this) {
18744                mContainerService = IMediaContainerService.Stub
18745                        .asInterface(Binder.allowBlocking(service));
18746                notifyAll();
18747            }
18748        }
18749
18750        @Override
18751        public void onServiceDisconnected(ComponentName name) {
18752        }
18753    }
18754
18755    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18756        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18757
18758        final boolean mounted;
18759        if (Environment.isExternalStorageEmulated()) {
18760            mounted = true;
18761        } else {
18762            final String status = Environment.getExternalStorageState();
18763
18764            mounted = status.equals(Environment.MEDIA_MOUNTED)
18765                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18766        }
18767
18768        if (!mounted) {
18769            return;
18770        }
18771
18772        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18773        int[] users;
18774        if (userId == UserHandle.USER_ALL) {
18775            users = sUserManager.getUserIds();
18776        } else {
18777            users = new int[] { userId };
18778        }
18779        final ClearStorageConnection conn = new ClearStorageConnection();
18780        if (mContext.bindServiceAsUser(
18781                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18782            try {
18783                for (int curUser : users) {
18784                    long timeout = SystemClock.uptimeMillis() + 5000;
18785                    synchronized (conn) {
18786                        long now;
18787                        while (conn.mContainerService == null &&
18788                                (now = SystemClock.uptimeMillis()) < timeout) {
18789                            try {
18790                                conn.wait(timeout - now);
18791                            } catch (InterruptedException e) {
18792                            }
18793                        }
18794                    }
18795                    if (conn.mContainerService == null) {
18796                        return;
18797                    }
18798
18799                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18800                    clearDirectory(conn.mContainerService,
18801                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18802                    if (allData) {
18803                        clearDirectory(conn.mContainerService,
18804                                userEnv.buildExternalStorageAppDataDirs(packageName));
18805                        clearDirectory(conn.mContainerService,
18806                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18807                    }
18808                }
18809            } finally {
18810                mContext.unbindService(conn);
18811            }
18812        }
18813    }
18814
18815    @Override
18816    public void clearApplicationProfileData(String packageName) {
18817        enforceSystemOrRoot("Only the system can clear all profile data");
18818
18819        final PackageParser.Package pkg;
18820        synchronized (mPackages) {
18821            pkg = mPackages.get(packageName);
18822        }
18823
18824        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18825            synchronized (mInstallLock) {
18826                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18827            }
18828        }
18829    }
18830
18831    @Override
18832    public void clearApplicationUserData(final String packageName,
18833            final IPackageDataObserver observer, final int userId) {
18834        mContext.enforceCallingOrSelfPermission(
18835                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18836
18837        final int callingUid = Binder.getCallingUid();
18838        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18839                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18840
18841        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18842        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18843        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18844            throw new SecurityException("Cannot clear data for a protected package: "
18845                    + packageName);
18846        }
18847        // Queue up an async operation since the package deletion may take a little while.
18848        mHandler.post(new Runnable() {
18849            public void run() {
18850                mHandler.removeCallbacks(this);
18851                final boolean succeeded;
18852                if (!filterApp) {
18853                    try (PackageFreezer freezer = freezePackage(packageName,
18854                            "clearApplicationUserData")) {
18855                        synchronized (mInstallLock) {
18856                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18857                        }
18858                        clearExternalStorageDataSync(packageName, userId, true);
18859                        synchronized (mPackages) {
18860                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18861                                    packageName, userId);
18862                        }
18863                    }
18864                    if (succeeded) {
18865                        // invoke DeviceStorageMonitor's update method to clear any notifications
18866                        DeviceStorageMonitorInternal dsm = LocalServices
18867                                .getService(DeviceStorageMonitorInternal.class);
18868                        if (dsm != null) {
18869                            dsm.checkMemory();
18870                        }
18871                    }
18872                } else {
18873                    succeeded = false;
18874                }
18875                if (observer != null) {
18876                    try {
18877                        observer.onRemoveCompleted(packageName, succeeded);
18878                    } catch (RemoteException e) {
18879                        Log.i(TAG, "Observer no longer exists.");
18880                    }
18881                } //end if observer
18882            } //end run
18883        });
18884    }
18885
18886    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18887        if (packageName == null) {
18888            Slog.w(TAG, "Attempt to delete null packageName.");
18889            return false;
18890        }
18891
18892        // Try finding details about the requested package
18893        PackageParser.Package pkg;
18894        synchronized (mPackages) {
18895            pkg = mPackages.get(packageName);
18896            if (pkg == null) {
18897                final PackageSetting ps = mSettings.mPackages.get(packageName);
18898                if (ps != null) {
18899                    pkg = ps.pkg;
18900                }
18901            }
18902
18903            if (pkg == null) {
18904                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18905                return false;
18906            }
18907
18908            PackageSetting ps = (PackageSetting) pkg.mExtras;
18909            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18910        }
18911
18912        clearAppDataLIF(pkg, userId,
18913                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18914
18915        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18916        removeKeystoreDataIfNeeded(userId, appId);
18917
18918        UserManagerInternal umInternal = getUserManagerInternal();
18919        final int flags;
18920        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18921            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18922        } else if (umInternal.isUserRunning(userId)) {
18923            flags = StorageManager.FLAG_STORAGE_DE;
18924        } else {
18925            flags = 0;
18926        }
18927        prepareAppDataContentsLIF(pkg, userId, flags);
18928
18929        return true;
18930    }
18931
18932    /**
18933     * Reverts user permission state changes (permissions and flags) in
18934     * all packages for a given user.
18935     *
18936     * @param userId The device user for which to do a reset.
18937     */
18938    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18939        final int packageCount = mPackages.size();
18940        for (int i = 0; i < packageCount; i++) {
18941            PackageParser.Package pkg = mPackages.valueAt(i);
18942            PackageSetting ps = (PackageSetting) pkg.mExtras;
18943            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18944        }
18945    }
18946
18947    private void resetNetworkPolicies(int userId) {
18948        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18949    }
18950
18951    /**
18952     * Reverts user permission state changes (permissions and flags).
18953     *
18954     * @param ps The package for which to reset.
18955     * @param userId The device user for which to do a reset.
18956     */
18957    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18958            final PackageSetting ps, final int userId) {
18959        if (ps.pkg == null) {
18960            return;
18961        }
18962
18963        // These are flags that can change base on user actions.
18964        final int userSettableMask = FLAG_PERMISSION_USER_SET
18965                | FLAG_PERMISSION_USER_FIXED
18966                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18967                | FLAG_PERMISSION_REVIEW_REQUIRED;
18968
18969        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18970                | FLAG_PERMISSION_POLICY_FIXED;
18971
18972        boolean writeInstallPermissions = false;
18973        boolean writeRuntimePermissions = false;
18974
18975        final int permissionCount = ps.pkg.requestedPermissions.size();
18976        for (int i = 0; i < permissionCount; i++) {
18977            final String permName = ps.pkg.requestedPermissions.get(i);
18978            final BasePermission bp =
18979                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
18980            if (bp == null) {
18981                continue;
18982            }
18983
18984            // If shared user we just reset the state to which only this app contributed.
18985            if (ps.sharedUser != null) {
18986                boolean used = false;
18987                final int packageCount = ps.sharedUser.packages.size();
18988                for (int j = 0; j < packageCount; j++) {
18989                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18990                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18991                            && pkg.pkg.requestedPermissions.contains(permName)) {
18992                        used = true;
18993                        break;
18994                    }
18995                }
18996                if (used) {
18997                    continue;
18998                }
18999            }
19000
19001            final PermissionsState permissionsState = ps.getPermissionsState();
19002
19003            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19004
19005            // Always clear the user settable flags.
19006            final boolean hasInstallState =
19007                    permissionsState.getInstallPermissionState(permName) != null;
19008            // If permission review is enabled and this is a legacy app, mark the
19009            // permission as requiring a review as this is the initial state.
19010            int flags = 0;
19011            if (mSettings.mPermissions.mPermissionReviewRequired
19012                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19013                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19014            }
19015            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19016                if (hasInstallState) {
19017                    writeInstallPermissions = true;
19018                } else {
19019                    writeRuntimePermissions = true;
19020                }
19021            }
19022
19023            // Below is only runtime permission handling.
19024            if (!bp.isRuntime()) {
19025                continue;
19026            }
19027
19028            // Never clobber system or policy.
19029            if ((oldFlags & policyOrSystemFlags) != 0) {
19030                continue;
19031            }
19032
19033            // If this permission was granted by default, make sure it is.
19034            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19035                if (permissionsState.grantRuntimePermission(bp, userId)
19036                        != PERMISSION_OPERATION_FAILURE) {
19037                    writeRuntimePermissions = true;
19038                }
19039            // If permission review is enabled the permissions for a legacy apps
19040            // are represented as constantly granted runtime ones, so don't revoke.
19041            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19042                // Otherwise, reset the permission.
19043                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19044                switch (revokeResult) {
19045                    case PERMISSION_OPERATION_SUCCESS:
19046                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19047                        writeRuntimePermissions = true;
19048                        final int appId = ps.appId;
19049                        mHandler.post(new Runnable() {
19050                            @Override
19051                            public void run() {
19052                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19053                            }
19054                        });
19055                    } break;
19056                }
19057            }
19058        }
19059
19060        // Synchronously write as we are taking permissions away.
19061        if (writeRuntimePermissions) {
19062            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19063        }
19064
19065        // Synchronously write as we are taking permissions away.
19066        if (writeInstallPermissions) {
19067            mSettings.writeLPr();
19068        }
19069    }
19070
19071    /**
19072     * Remove entries from the keystore daemon. Will only remove it if the
19073     * {@code appId} is valid.
19074     */
19075    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19076        if (appId < 0) {
19077            return;
19078        }
19079
19080        final KeyStore keyStore = KeyStore.getInstance();
19081        if (keyStore != null) {
19082            if (userId == UserHandle.USER_ALL) {
19083                for (final int individual : sUserManager.getUserIds()) {
19084                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19085                }
19086            } else {
19087                keyStore.clearUid(UserHandle.getUid(userId, appId));
19088            }
19089        } else {
19090            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19091        }
19092    }
19093
19094    @Override
19095    public void deleteApplicationCacheFiles(final String packageName,
19096            final IPackageDataObserver observer) {
19097        final int userId = UserHandle.getCallingUserId();
19098        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19099    }
19100
19101    @Override
19102    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19103            final IPackageDataObserver observer) {
19104        final int callingUid = Binder.getCallingUid();
19105        if (mContext.checkCallingOrSelfPermission(
19106                android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
19107                != PackageManager.PERMISSION_GRANTED) {
19108            // If the caller has the old delete cache permission, silently ignore.  Else throw.
19109            if (mContext.checkCallingOrSelfPermission(
19110                    android.Manifest.permission.DELETE_CACHE_FILES)
19111                    == PackageManager.PERMISSION_GRANTED) {
19112                Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
19113                        android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
19114                        ", silently ignoring");
19115                return;
19116            }
19117            mContext.enforceCallingOrSelfPermission(
19118                    android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
19119        }
19120        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19121                /* requireFullPermission= */ true, /* checkShell= */ false,
19122                "delete application cache files");
19123        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19124                android.Manifest.permission.ACCESS_INSTANT_APPS);
19125
19126        final PackageParser.Package pkg;
19127        synchronized (mPackages) {
19128            pkg = mPackages.get(packageName);
19129        }
19130
19131        // Queue up an async operation since the package deletion may take a little while.
19132        mHandler.post(new Runnable() {
19133            public void run() {
19134                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19135                boolean doClearData = true;
19136                if (ps != null) {
19137                    final boolean targetIsInstantApp =
19138                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19139                    doClearData = !targetIsInstantApp
19140                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19141                }
19142                if (doClearData) {
19143                    synchronized (mInstallLock) {
19144                        final int flags = StorageManager.FLAG_STORAGE_DE
19145                                | StorageManager.FLAG_STORAGE_CE;
19146                        // We're only clearing cache files, so we don't care if the
19147                        // app is unfrozen and still able to run
19148                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19149                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19150                    }
19151                    clearExternalStorageDataSync(packageName, userId, false);
19152                }
19153                if (observer != null) {
19154                    try {
19155                        observer.onRemoveCompleted(packageName, true);
19156                    } catch (RemoteException e) {
19157                        Log.i(TAG, "Observer no longer exists.");
19158                    }
19159                }
19160            }
19161        });
19162    }
19163
19164    @Override
19165    public void getPackageSizeInfo(final String packageName, int userHandle,
19166            final IPackageStatsObserver observer) {
19167        throw new UnsupportedOperationException(
19168                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19169    }
19170
19171    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19172        final PackageSetting ps;
19173        synchronized (mPackages) {
19174            ps = mSettings.mPackages.get(packageName);
19175            if (ps == null) {
19176                Slog.w(TAG, "Failed to find settings for " + packageName);
19177                return false;
19178            }
19179        }
19180
19181        final String[] packageNames = { packageName };
19182        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19183        final String[] codePaths = { ps.codePathString };
19184
19185        try {
19186            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19187                    ps.appId, ceDataInodes, codePaths, stats);
19188
19189            // For now, ignore code size of packages on system partition
19190            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19191                stats.codeSize = 0;
19192            }
19193
19194            // External clients expect these to be tracked separately
19195            stats.dataSize -= stats.cacheSize;
19196
19197        } catch (InstallerException e) {
19198            Slog.w(TAG, String.valueOf(e));
19199            return false;
19200        }
19201
19202        return true;
19203    }
19204
19205    private int getUidTargetSdkVersionLockedLPr(int uid) {
19206        Object obj = mSettings.getUserIdLPr(uid);
19207        if (obj instanceof SharedUserSetting) {
19208            final SharedUserSetting sus = (SharedUserSetting) obj;
19209            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19210            final Iterator<PackageSetting> it = sus.packages.iterator();
19211            while (it.hasNext()) {
19212                final PackageSetting ps = it.next();
19213                if (ps.pkg != null) {
19214                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19215                    if (v < vers) vers = v;
19216                }
19217            }
19218            return vers;
19219        } else if (obj instanceof PackageSetting) {
19220            final PackageSetting ps = (PackageSetting) obj;
19221            if (ps.pkg != null) {
19222                return ps.pkg.applicationInfo.targetSdkVersion;
19223            }
19224        }
19225        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19226    }
19227
19228    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19229        final PackageParser.Package p = mPackages.get(packageName);
19230        if (p != null) {
19231            return p.applicationInfo.targetSdkVersion;
19232        }
19233        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19234    }
19235
19236    @Override
19237    public void addPreferredActivity(IntentFilter filter, int match,
19238            ComponentName[] set, ComponentName activity, int userId) {
19239        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19240                "Adding preferred");
19241    }
19242
19243    private void addPreferredActivityInternal(IntentFilter filter, int match,
19244            ComponentName[] set, ComponentName activity, boolean always, int userId,
19245            String opname) {
19246        // writer
19247        int callingUid = Binder.getCallingUid();
19248        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19249                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19250        if (filter.countActions() == 0) {
19251            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19252            return;
19253        }
19254        synchronized (mPackages) {
19255            if (mContext.checkCallingOrSelfPermission(
19256                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19257                    != PackageManager.PERMISSION_GRANTED) {
19258                if (getUidTargetSdkVersionLockedLPr(callingUid)
19259                        < Build.VERSION_CODES.FROYO) {
19260                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19261                            + callingUid);
19262                    return;
19263                }
19264                mContext.enforceCallingOrSelfPermission(
19265                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19266            }
19267
19268            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19269            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19270                    + userId + ":");
19271            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19272            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19273            scheduleWritePackageRestrictionsLocked(userId);
19274            postPreferredActivityChangedBroadcast(userId);
19275        }
19276    }
19277
19278    private void postPreferredActivityChangedBroadcast(int userId) {
19279        mHandler.post(() -> {
19280            final IActivityManager am = ActivityManager.getService();
19281            if (am == null) {
19282                return;
19283            }
19284
19285            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19286            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19287            try {
19288                am.broadcastIntent(null, intent, null, null,
19289                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19290                        null, false, false, userId);
19291            } catch (RemoteException e) {
19292            }
19293        });
19294    }
19295
19296    @Override
19297    public void replacePreferredActivity(IntentFilter filter, int match,
19298            ComponentName[] set, ComponentName activity, int userId) {
19299        if (filter.countActions() != 1) {
19300            throw new IllegalArgumentException(
19301                    "replacePreferredActivity expects filter to have only 1 action.");
19302        }
19303        if (filter.countDataAuthorities() != 0
19304                || filter.countDataPaths() != 0
19305                || filter.countDataSchemes() > 1
19306                || filter.countDataTypes() != 0) {
19307            throw new IllegalArgumentException(
19308                    "replacePreferredActivity expects filter to have no data authorities, " +
19309                    "paths, or types; and at most one scheme.");
19310        }
19311
19312        final int callingUid = Binder.getCallingUid();
19313        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19314                true /* requireFullPermission */, false /* checkShell */,
19315                "replace preferred activity");
19316        synchronized (mPackages) {
19317            if (mContext.checkCallingOrSelfPermission(
19318                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19319                    != PackageManager.PERMISSION_GRANTED) {
19320                if (getUidTargetSdkVersionLockedLPr(callingUid)
19321                        < Build.VERSION_CODES.FROYO) {
19322                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19323                            + Binder.getCallingUid());
19324                    return;
19325                }
19326                mContext.enforceCallingOrSelfPermission(
19327                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19328            }
19329
19330            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19331            if (pir != null) {
19332                // Get all of the existing entries that exactly match this filter.
19333                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19334                if (existing != null && existing.size() == 1) {
19335                    PreferredActivity cur = existing.get(0);
19336                    if (DEBUG_PREFERRED) {
19337                        Slog.i(TAG, "Checking replace of preferred:");
19338                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19339                        if (!cur.mPref.mAlways) {
19340                            Slog.i(TAG, "  -- CUR; not mAlways!");
19341                        } else {
19342                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19343                            Slog.i(TAG, "  -- CUR: mSet="
19344                                    + Arrays.toString(cur.mPref.mSetComponents));
19345                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19346                            Slog.i(TAG, "  -- NEW: mMatch="
19347                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19348                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19349                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19350                        }
19351                    }
19352                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19353                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19354                            && cur.mPref.sameSet(set)) {
19355                        // Setting the preferred activity to what it happens to be already
19356                        if (DEBUG_PREFERRED) {
19357                            Slog.i(TAG, "Replacing with same preferred activity "
19358                                    + cur.mPref.mShortComponent + " for user "
19359                                    + userId + ":");
19360                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19361                        }
19362                        return;
19363                    }
19364                }
19365
19366                if (existing != null) {
19367                    if (DEBUG_PREFERRED) {
19368                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19369                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19370                    }
19371                    for (int i = 0; i < existing.size(); i++) {
19372                        PreferredActivity pa = existing.get(i);
19373                        if (DEBUG_PREFERRED) {
19374                            Slog.i(TAG, "Removing existing preferred activity "
19375                                    + pa.mPref.mComponent + ":");
19376                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19377                        }
19378                        pir.removeFilter(pa);
19379                    }
19380                }
19381            }
19382            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19383                    "Replacing preferred");
19384        }
19385    }
19386
19387    @Override
19388    public void clearPackagePreferredActivities(String packageName) {
19389        final int callingUid = Binder.getCallingUid();
19390        if (getInstantAppPackageName(callingUid) != null) {
19391            return;
19392        }
19393        // writer
19394        synchronized (mPackages) {
19395            PackageParser.Package pkg = mPackages.get(packageName);
19396            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19397                if (mContext.checkCallingOrSelfPermission(
19398                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19399                        != PackageManager.PERMISSION_GRANTED) {
19400                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19401                            < Build.VERSION_CODES.FROYO) {
19402                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19403                                + callingUid);
19404                        return;
19405                    }
19406                    mContext.enforceCallingOrSelfPermission(
19407                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19408                }
19409            }
19410            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19411            if (ps != null
19412                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19413                return;
19414            }
19415            int user = UserHandle.getCallingUserId();
19416            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19417                scheduleWritePackageRestrictionsLocked(user);
19418            }
19419        }
19420    }
19421
19422    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19423    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19424        ArrayList<PreferredActivity> removed = null;
19425        boolean changed = false;
19426        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19427            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19428            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19429            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19430                continue;
19431            }
19432            Iterator<PreferredActivity> it = pir.filterIterator();
19433            while (it.hasNext()) {
19434                PreferredActivity pa = it.next();
19435                // Mark entry for removal only if it matches the package name
19436                // and the entry is of type "always".
19437                if (packageName == null ||
19438                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19439                                && pa.mPref.mAlways)) {
19440                    if (removed == null) {
19441                        removed = new ArrayList<PreferredActivity>();
19442                    }
19443                    removed.add(pa);
19444                }
19445            }
19446            if (removed != null) {
19447                for (int j=0; j<removed.size(); j++) {
19448                    PreferredActivity pa = removed.get(j);
19449                    pir.removeFilter(pa);
19450                }
19451                changed = true;
19452            }
19453        }
19454        if (changed) {
19455            postPreferredActivityChangedBroadcast(userId);
19456        }
19457        return changed;
19458    }
19459
19460    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19461    private void clearIntentFilterVerificationsLPw(int userId) {
19462        final int packageCount = mPackages.size();
19463        for (int i = 0; i < packageCount; i++) {
19464            PackageParser.Package pkg = mPackages.valueAt(i);
19465            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19466        }
19467    }
19468
19469    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19470    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19471        if (userId == UserHandle.USER_ALL) {
19472            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19473                    sUserManager.getUserIds())) {
19474                for (int oneUserId : sUserManager.getUserIds()) {
19475                    scheduleWritePackageRestrictionsLocked(oneUserId);
19476                }
19477            }
19478        } else {
19479            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19480                scheduleWritePackageRestrictionsLocked(userId);
19481            }
19482        }
19483    }
19484
19485    /** Clears state for all users, and touches intent filter verification policy */
19486    void clearDefaultBrowserIfNeeded(String packageName) {
19487        for (int oneUserId : sUserManager.getUserIds()) {
19488            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19489        }
19490    }
19491
19492    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19493        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19494        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19495            if (packageName.equals(defaultBrowserPackageName)) {
19496                setDefaultBrowserPackageName(null, userId);
19497            }
19498        }
19499    }
19500
19501    @Override
19502    public void resetApplicationPreferences(int userId) {
19503        mContext.enforceCallingOrSelfPermission(
19504                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19505        final long identity = Binder.clearCallingIdentity();
19506        // writer
19507        try {
19508            synchronized (mPackages) {
19509                clearPackagePreferredActivitiesLPw(null, userId);
19510                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19511                // TODO: We have to reset the default SMS and Phone. This requires
19512                // significant refactoring to keep all default apps in the package
19513                // manager (cleaner but more work) or have the services provide
19514                // callbacks to the package manager to request a default app reset.
19515                applyFactoryDefaultBrowserLPw(userId);
19516                clearIntentFilterVerificationsLPw(userId);
19517                primeDomainVerificationsLPw(userId);
19518                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19519                scheduleWritePackageRestrictionsLocked(userId);
19520            }
19521            resetNetworkPolicies(userId);
19522        } finally {
19523            Binder.restoreCallingIdentity(identity);
19524        }
19525    }
19526
19527    @Override
19528    public int getPreferredActivities(List<IntentFilter> outFilters,
19529            List<ComponentName> outActivities, String packageName) {
19530        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19531            return 0;
19532        }
19533        int num = 0;
19534        final int userId = UserHandle.getCallingUserId();
19535        // reader
19536        synchronized (mPackages) {
19537            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19538            if (pir != null) {
19539                final Iterator<PreferredActivity> it = pir.filterIterator();
19540                while (it.hasNext()) {
19541                    final PreferredActivity pa = it.next();
19542                    if (packageName == null
19543                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19544                                    && pa.mPref.mAlways)) {
19545                        if (outFilters != null) {
19546                            outFilters.add(new IntentFilter(pa));
19547                        }
19548                        if (outActivities != null) {
19549                            outActivities.add(pa.mPref.mComponent);
19550                        }
19551                    }
19552                }
19553            }
19554        }
19555
19556        return num;
19557    }
19558
19559    @Override
19560    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19561            int userId) {
19562        int callingUid = Binder.getCallingUid();
19563        if (callingUid != Process.SYSTEM_UID) {
19564            throw new SecurityException(
19565                    "addPersistentPreferredActivity can only be run by the system");
19566        }
19567        if (filter.countActions() == 0) {
19568            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19569            return;
19570        }
19571        synchronized (mPackages) {
19572            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19573                    ":");
19574            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19575            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19576                    new PersistentPreferredActivity(filter, activity));
19577            scheduleWritePackageRestrictionsLocked(userId);
19578            postPreferredActivityChangedBroadcast(userId);
19579        }
19580    }
19581
19582    @Override
19583    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19584        int callingUid = Binder.getCallingUid();
19585        if (callingUid != Process.SYSTEM_UID) {
19586            throw new SecurityException(
19587                    "clearPackagePersistentPreferredActivities can only be run by the system");
19588        }
19589        ArrayList<PersistentPreferredActivity> removed = null;
19590        boolean changed = false;
19591        synchronized (mPackages) {
19592            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19593                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19594                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19595                        .valueAt(i);
19596                if (userId != thisUserId) {
19597                    continue;
19598                }
19599                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19600                while (it.hasNext()) {
19601                    PersistentPreferredActivity ppa = it.next();
19602                    // Mark entry for removal only if it matches the package name.
19603                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19604                        if (removed == null) {
19605                            removed = new ArrayList<PersistentPreferredActivity>();
19606                        }
19607                        removed.add(ppa);
19608                    }
19609                }
19610                if (removed != null) {
19611                    for (int j=0; j<removed.size(); j++) {
19612                        PersistentPreferredActivity ppa = removed.get(j);
19613                        ppir.removeFilter(ppa);
19614                    }
19615                    changed = true;
19616                }
19617            }
19618
19619            if (changed) {
19620                scheduleWritePackageRestrictionsLocked(userId);
19621                postPreferredActivityChangedBroadcast(userId);
19622            }
19623        }
19624    }
19625
19626    /**
19627     * Common machinery for picking apart a restored XML blob and passing
19628     * it to a caller-supplied functor to be applied to the running system.
19629     */
19630    private void restoreFromXml(XmlPullParser parser, int userId,
19631            String expectedStartTag, BlobXmlRestorer functor)
19632            throws IOException, XmlPullParserException {
19633        int type;
19634        while ((type = parser.next()) != XmlPullParser.START_TAG
19635                && type != XmlPullParser.END_DOCUMENT) {
19636        }
19637        if (type != XmlPullParser.START_TAG) {
19638            // oops didn't find a start tag?!
19639            if (DEBUG_BACKUP) {
19640                Slog.e(TAG, "Didn't find start tag during restore");
19641            }
19642            return;
19643        }
19644Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19645        // this is supposed to be TAG_PREFERRED_BACKUP
19646        if (!expectedStartTag.equals(parser.getName())) {
19647            if (DEBUG_BACKUP) {
19648                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19649            }
19650            return;
19651        }
19652
19653        // skip interfering stuff, then we're aligned with the backing implementation
19654        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19655Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19656        functor.apply(parser, userId);
19657    }
19658
19659    private interface BlobXmlRestorer {
19660        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19661    }
19662
19663    /**
19664     * Non-Binder method, support for the backup/restore mechanism: write the
19665     * full set of preferred activities in its canonical XML format.  Returns the
19666     * XML output as a byte array, or null if there is none.
19667     */
19668    @Override
19669    public byte[] getPreferredActivityBackup(int userId) {
19670        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19671            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19672        }
19673
19674        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19675        try {
19676            final XmlSerializer serializer = new FastXmlSerializer();
19677            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19678            serializer.startDocument(null, true);
19679            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19680
19681            synchronized (mPackages) {
19682                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19683            }
19684
19685            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19686            serializer.endDocument();
19687            serializer.flush();
19688        } catch (Exception e) {
19689            if (DEBUG_BACKUP) {
19690                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19691            }
19692            return null;
19693        }
19694
19695        return dataStream.toByteArray();
19696    }
19697
19698    @Override
19699    public void restorePreferredActivities(byte[] backup, int userId) {
19700        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19701            throw new SecurityException("Only the system may call restorePreferredActivities()");
19702        }
19703
19704        try {
19705            final XmlPullParser parser = Xml.newPullParser();
19706            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19707            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19708                    new BlobXmlRestorer() {
19709                        @Override
19710                        public void apply(XmlPullParser parser, int userId)
19711                                throws XmlPullParserException, IOException {
19712                            synchronized (mPackages) {
19713                                mSettings.readPreferredActivitiesLPw(parser, userId);
19714                            }
19715                        }
19716                    } );
19717        } catch (Exception e) {
19718            if (DEBUG_BACKUP) {
19719                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19720            }
19721        }
19722    }
19723
19724    /**
19725     * Non-Binder method, support for the backup/restore mechanism: write the
19726     * default browser (etc) settings in its canonical XML format.  Returns the default
19727     * browser XML representation as a byte array, or null if there is none.
19728     */
19729    @Override
19730    public byte[] getDefaultAppsBackup(int userId) {
19731        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19732            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19733        }
19734
19735        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19736        try {
19737            final XmlSerializer serializer = new FastXmlSerializer();
19738            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19739            serializer.startDocument(null, true);
19740            serializer.startTag(null, TAG_DEFAULT_APPS);
19741
19742            synchronized (mPackages) {
19743                mSettings.writeDefaultAppsLPr(serializer, userId);
19744            }
19745
19746            serializer.endTag(null, TAG_DEFAULT_APPS);
19747            serializer.endDocument();
19748            serializer.flush();
19749        } catch (Exception e) {
19750            if (DEBUG_BACKUP) {
19751                Slog.e(TAG, "Unable to write default apps for backup", e);
19752            }
19753            return null;
19754        }
19755
19756        return dataStream.toByteArray();
19757    }
19758
19759    @Override
19760    public void restoreDefaultApps(byte[] backup, int userId) {
19761        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19762            throw new SecurityException("Only the system may call restoreDefaultApps()");
19763        }
19764
19765        try {
19766            final XmlPullParser parser = Xml.newPullParser();
19767            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19768            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19769                    new BlobXmlRestorer() {
19770                        @Override
19771                        public void apply(XmlPullParser parser, int userId)
19772                                throws XmlPullParserException, IOException {
19773                            synchronized (mPackages) {
19774                                mSettings.readDefaultAppsLPw(parser, userId);
19775                            }
19776                        }
19777                    } );
19778        } catch (Exception e) {
19779            if (DEBUG_BACKUP) {
19780                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19781            }
19782        }
19783    }
19784
19785    @Override
19786    public byte[] getIntentFilterVerificationBackup(int userId) {
19787        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19788            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19789        }
19790
19791        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19792        try {
19793            final XmlSerializer serializer = new FastXmlSerializer();
19794            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19795            serializer.startDocument(null, true);
19796            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19797
19798            synchronized (mPackages) {
19799                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19800            }
19801
19802            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19803            serializer.endDocument();
19804            serializer.flush();
19805        } catch (Exception e) {
19806            if (DEBUG_BACKUP) {
19807                Slog.e(TAG, "Unable to write default apps for backup", e);
19808            }
19809            return null;
19810        }
19811
19812        return dataStream.toByteArray();
19813    }
19814
19815    @Override
19816    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19817        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19818            throw new SecurityException("Only the system may call restorePreferredActivities()");
19819        }
19820
19821        try {
19822            final XmlPullParser parser = Xml.newPullParser();
19823            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19824            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19825                    new BlobXmlRestorer() {
19826                        @Override
19827                        public void apply(XmlPullParser parser, int userId)
19828                                throws XmlPullParserException, IOException {
19829                            synchronized (mPackages) {
19830                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19831                                mSettings.writeLPr();
19832                            }
19833                        }
19834                    } );
19835        } catch (Exception e) {
19836            if (DEBUG_BACKUP) {
19837                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19838            }
19839        }
19840    }
19841
19842    @Override
19843    public byte[] getPermissionGrantBackup(int userId) {
19844        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19845            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19846        }
19847
19848        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19849        try {
19850            final XmlSerializer serializer = new FastXmlSerializer();
19851            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19852            serializer.startDocument(null, true);
19853            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19854
19855            synchronized (mPackages) {
19856                serializeRuntimePermissionGrantsLPr(serializer, userId);
19857            }
19858
19859            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19860            serializer.endDocument();
19861            serializer.flush();
19862        } catch (Exception e) {
19863            if (DEBUG_BACKUP) {
19864                Slog.e(TAG, "Unable to write default apps for backup", e);
19865            }
19866            return null;
19867        }
19868
19869        return dataStream.toByteArray();
19870    }
19871
19872    @Override
19873    public void restorePermissionGrants(byte[] backup, int userId) {
19874        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19875            throw new SecurityException("Only the system may call restorePermissionGrants()");
19876        }
19877
19878        try {
19879            final XmlPullParser parser = Xml.newPullParser();
19880            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19881            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19882                    new BlobXmlRestorer() {
19883                        @Override
19884                        public void apply(XmlPullParser parser, int userId)
19885                                throws XmlPullParserException, IOException {
19886                            synchronized (mPackages) {
19887                                processRestoredPermissionGrantsLPr(parser, userId);
19888                            }
19889                        }
19890                    } );
19891        } catch (Exception e) {
19892            if (DEBUG_BACKUP) {
19893                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19894            }
19895        }
19896    }
19897
19898    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19899            throws IOException {
19900        serializer.startTag(null, TAG_ALL_GRANTS);
19901
19902        final int N = mSettings.mPackages.size();
19903        for (int i = 0; i < N; i++) {
19904            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19905            boolean pkgGrantsKnown = false;
19906
19907            PermissionsState packagePerms = ps.getPermissionsState();
19908
19909            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19910                final int grantFlags = state.getFlags();
19911                // only look at grants that are not system/policy fixed
19912                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19913                    final boolean isGranted = state.isGranted();
19914                    // And only back up the user-twiddled state bits
19915                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19916                        final String packageName = mSettings.mPackages.keyAt(i);
19917                        if (!pkgGrantsKnown) {
19918                            serializer.startTag(null, TAG_GRANT);
19919                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19920                            pkgGrantsKnown = true;
19921                        }
19922
19923                        final boolean userSet =
19924                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19925                        final boolean userFixed =
19926                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19927                        final boolean revoke =
19928                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19929
19930                        serializer.startTag(null, TAG_PERMISSION);
19931                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19932                        if (isGranted) {
19933                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19934                        }
19935                        if (userSet) {
19936                            serializer.attribute(null, ATTR_USER_SET, "true");
19937                        }
19938                        if (userFixed) {
19939                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19940                        }
19941                        if (revoke) {
19942                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19943                        }
19944                        serializer.endTag(null, TAG_PERMISSION);
19945                    }
19946                }
19947            }
19948
19949            if (pkgGrantsKnown) {
19950                serializer.endTag(null, TAG_GRANT);
19951            }
19952        }
19953
19954        serializer.endTag(null, TAG_ALL_GRANTS);
19955    }
19956
19957    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19958            throws XmlPullParserException, IOException {
19959        String pkgName = null;
19960        int outerDepth = parser.getDepth();
19961        int type;
19962        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19963                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19964            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19965                continue;
19966            }
19967
19968            final String tagName = parser.getName();
19969            if (tagName.equals(TAG_GRANT)) {
19970                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19971                if (DEBUG_BACKUP) {
19972                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19973                }
19974            } else if (tagName.equals(TAG_PERMISSION)) {
19975
19976                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19977                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19978
19979                int newFlagSet = 0;
19980                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19981                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19982                }
19983                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19984                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19985                }
19986                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19987                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19988                }
19989                if (DEBUG_BACKUP) {
19990                    Slog.v(TAG, "  + Restoring grant:"
19991                            + " pkg=" + pkgName
19992                            + " perm=" + permName
19993                            + " granted=" + isGranted
19994                            + " bits=0x" + Integer.toHexString(newFlagSet));
19995                }
19996                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19997                if (ps != null) {
19998                    // Already installed so we apply the grant immediately
19999                    if (DEBUG_BACKUP) {
20000                        Slog.v(TAG, "        + already installed; applying");
20001                    }
20002                    PermissionsState perms = ps.getPermissionsState();
20003                    BasePermission bp =
20004                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20005                    if (bp != null) {
20006                        if (isGranted) {
20007                            perms.grantRuntimePermission(bp, userId);
20008                        }
20009                        if (newFlagSet != 0) {
20010                            perms.updatePermissionFlags(
20011                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20012                        }
20013                    }
20014                } else {
20015                    // Need to wait for post-restore install to apply the grant
20016                    if (DEBUG_BACKUP) {
20017                        Slog.v(TAG, "        - not yet installed; saving for later");
20018                    }
20019                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20020                            isGranted, newFlagSet, userId);
20021                }
20022            } else {
20023                PackageManagerService.reportSettingsProblem(Log.WARN,
20024                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20025                XmlUtils.skipCurrentTag(parser);
20026            }
20027        }
20028
20029        scheduleWriteSettingsLocked();
20030        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20031    }
20032
20033    @Override
20034    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20035            int sourceUserId, int targetUserId, int flags) {
20036        mContext.enforceCallingOrSelfPermission(
20037                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20038        int callingUid = Binder.getCallingUid();
20039        enforceOwnerRights(ownerPackage, callingUid);
20040        PackageManagerServiceUtils.enforceShellRestriction(
20041                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20042        if (intentFilter.countActions() == 0) {
20043            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20044            return;
20045        }
20046        synchronized (mPackages) {
20047            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20048                    ownerPackage, targetUserId, flags);
20049            CrossProfileIntentResolver resolver =
20050                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20051            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20052            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20053            if (existing != null) {
20054                int size = existing.size();
20055                for (int i = 0; i < size; i++) {
20056                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20057                        return;
20058                    }
20059                }
20060            }
20061            resolver.addFilter(newFilter);
20062            scheduleWritePackageRestrictionsLocked(sourceUserId);
20063        }
20064    }
20065
20066    @Override
20067    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20068        mContext.enforceCallingOrSelfPermission(
20069                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20070        final int callingUid = Binder.getCallingUid();
20071        enforceOwnerRights(ownerPackage, callingUid);
20072        PackageManagerServiceUtils.enforceShellRestriction(
20073                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20074        synchronized (mPackages) {
20075            CrossProfileIntentResolver resolver =
20076                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20077            ArraySet<CrossProfileIntentFilter> set =
20078                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20079            for (CrossProfileIntentFilter filter : set) {
20080                if (filter.getOwnerPackage().equals(ownerPackage)) {
20081                    resolver.removeFilter(filter);
20082                }
20083            }
20084            scheduleWritePackageRestrictionsLocked(sourceUserId);
20085        }
20086    }
20087
20088    // Enforcing that callingUid is owning pkg on userId
20089    private void enforceOwnerRights(String pkg, int callingUid) {
20090        // The system owns everything.
20091        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20092            return;
20093        }
20094        final int callingUserId = UserHandle.getUserId(callingUid);
20095        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20096        if (pi == null) {
20097            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20098                    + callingUserId);
20099        }
20100        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20101            throw new SecurityException("Calling uid " + callingUid
20102                    + " does not own package " + pkg);
20103        }
20104    }
20105
20106    @Override
20107    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20108        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20109            return null;
20110        }
20111        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20112    }
20113
20114    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20115        UserManagerService ums = UserManagerService.getInstance();
20116        if (ums != null) {
20117            final UserInfo parent = ums.getProfileParent(userId);
20118            final int launcherUid = (parent != null) ? parent.id : userId;
20119            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20120            if (launcherComponent != null) {
20121                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20122                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20123                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20124                        .setPackage(launcherComponent.getPackageName());
20125                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20126            }
20127        }
20128    }
20129
20130    /**
20131     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20132     * then reports the most likely home activity or null if there are more than one.
20133     */
20134    private ComponentName getDefaultHomeActivity(int userId) {
20135        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20136        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20137        if (cn != null) {
20138            return cn;
20139        }
20140
20141        // Find the launcher with the highest priority and return that component if there are no
20142        // other home activity with the same priority.
20143        int lastPriority = Integer.MIN_VALUE;
20144        ComponentName lastComponent = null;
20145        final int size = allHomeCandidates.size();
20146        for (int i = 0; i < size; i++) {
20147            final ResolveInfo ri = allHomeCandidates.get(i);
20148            if (ri.priority > lastPriority) {
20149                lastComponent = ri.activityInfo.getComponentName();
20150                lastPriority = ri.priority;
20151            } else if (ri.priority == lastPriority) {
20152                // Two components found with same priority.
20153                lastComponent = null;
20154            }
20155        }
20156        return lastComponent;
20157    }
20158
20159    private Intent getHomeIntent() {
20160        Intent intent = new Intent(Intent.ACTION_MAIN);
20161        intent.addCategory(Intent.CATEGORY_HOME);
20162        intent.addCategory(Intent.CATEGORY_DEFAULT);
20163        return intent;
20164    }
20165
20166    private IntentFilter getHomeFilter() {
20167        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20168        filter.addCategory(Intent.CATEGORY_HOME);
20169        filter.addCategory(Intent.CATEGORY_DEFAULT);
20170        return filter;
20171    }
20172
20173    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20174            int userId) {
20175        Intent intent  = getHomeIntent();
20176        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20177                PackageManager.GET_META_DATA, userId);
20178        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20179                true, false, false, userId);
20180
20181        allHomeCandidates.clear();
20182        if (list != null) {
20183            for (ResolveInfo ri : list) {
20184                allHomeCandidates.add(ri);
20185            }
20186        }
20187        return (preferred == null || preferred.activityInfo == null)
20188                ? null
20189                : new ComponentName(preferred.activityInfo.packageName,
20190                        preferred.activityInfo.name);
20191    }
20192
20193    @Override
20194    public void setHomeActivity(ComponentName comp, int userId) {
20195        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20196            return;
20197        }
20198        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20199        getHomeActivitiesAsUser(homeActivities, userId);
20200
20201        boolean found = false;
20202
20203        final int size = homeActivities.size();
20204        final ComponentName[] set = new ComponentName[size];
20205        for (int i = 0; i < size; i++) {
20206            final ResolveInfo candidate = homeActivities.get(i);
20207            final ActivityInfo info = candidate.activityInfo;
20208            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20209            set[i] = activityName;
20210            if (!found && activityName.equals(comp)) {
20211                found = true;
20212            }
20213        }
20214        if (!found) {
20215            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20216                    + userId);
20217        }
20218        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20219                set, comp, userId);
20220    }
20221
20222    private @Nullable String getSetupWizardPackageName() {
20223        final Intent intent = new Intent(Intent.ACTION_MAIN);
20224        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20225
20226        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20227                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20228                        | MATCH_DISABLED_COMPONENTS,
20229                UserHandle.myUserId());
20230        if (matches.size() == 1) {
20231            return matches.get(0).getComponentInfo().packageName;
20232        } else {
20233            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20234                    + ": matches=" + matches);
20235            return null;
20236        }
20237    }
20238
20239    private @Nullable String getStorageManagerPackageName() {
20240        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20241
20242        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20243                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20244                        | MATCH_DISABLED_COMPONENTS,
20245                UserHandle.myUserId());
20246        if (matches.size() == 1) {
20247            return matches.get(0).getComponentInfo().packageName;
20248        } else {
20249            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20250                    + matches.size() + ": matches=" + matches);
20251            return null;
20252        }
20253    }
20254
20255    @Override
20256    public void setApplicationEnabledSetting(String appPackageName,
20257            int newState, int flags, int userId, String callingPackage) {
20258        if (!sUserManager.exists(userId)) return;
20259        if (callingPackage == null) {
20260            callingPackage = Integer.toString(Binder.getCallingUid());
20261        }
20262        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20263    }
20264
20265    @Override
20266    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20267        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20268        synchronized (mPackages) {
20269            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20270            if (pkgSetting != null) {
20271                pkgSetting.setUpdateAvailable(updateAvailable);
20272            }
20273        }
20274    }
20275
20276    @Override
20277    public void setComponentEnabledSetting(ComponentName componentName,
20278            int newState, int flags, int userId) {
20279        if (!sUserManager.exists(userId)) return;
20280        setEnabledSetting(componentName.getPackageName(),
20281                componentName.getClassName(), newState, flags, userId, null);
20282    }
20283
20284    private void setEnabledSetting(final String packageName, String className, int newState,
20285            final int flags, int userId, String callingPackage) {
20286        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20287              || newState == COMPONENT_ENABLED_STATE_ENABLED
20288              || newState == COMPONENT_ENABLED_STATE_DISABLED
20289              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20290              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20291            throw new IllegalArgumentException("Invalid new component state: "
20292                    + newState);
20293        }
20294        PackageSetting pkgSetting;
20295        final int callingUid = Binder.getCallingUid();
20296        final int permission;
20297        if (callingUid == Process.SYSTEM_UID) {
20298            permission = PackageManager.PERMISSION_GRANTED;
20299        } else {
20300            permission = mContext.checkCallingOrSelfPermission(
20301                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20302        }
20303        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20304                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20305        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20306        boolean sendNow = false;
20307        boolean isApp = (className == null);
20308        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20309        String componentName = isApp ? packageName : className;
20310        int packageUid = -1;
20311        ArrayList<String> components;
20312
20313        // reader
20314        synchronized (mPackages) {
20315            pkgSetting = mSettings.mPackages.get(packageName);
20316            if (pkgSetting == null) {
20317                if (!isCallerInstantApp) {
20318                    if (className == null) {
20319                        throw new IllegalArgumentException("Unknown package: " + packageName);
20320                    }
20321                    throw new IllegalArgumentException(
20322                            "Unknown component: " + packageName + "/" + className);
20323                } else {
20324                    // throw SecurityException to prevent leaking package information
20325                    throw new SecurityException(
20326                            "Attempt to change component state; "
20327                            + "pid=" + Binder.getCallingPid()
20328                            + ", uid=" + callingUid
20329                            + (className == null
20330                                    ? ", package=" + packageName
20331                                    : ", component=" + packageName + "/" + className));
20332                }
20333            }
20334        }
20335
20336        // Limit who can change which apps
20337        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20338            // Don't allow apps that don't have permission to modify other apps
20339            if (!allowedByPermission
20340                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20341                throw new SecurityException(
20342                        "Attempt to change component state; "
20343                        + "pid=" + Binder.getCallingPid()
20344                        + ", uid=" + callingUid
20345                        + (className == null
20346                                ? ", package=" + packageName
20347                                : ", component=" + packageName + "/" + className));
20348            }
20349            // Don't allow changing protected packages.
20350            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20351                throw new SecurityException("Cannot disable a protected package: " + packageName);
20352            }
20353        }
20354
20355        synchronized (mPackages) {
20356            if (callingUid == Process.SHELL_UID
20357                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20358                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20359                // unless it is a test package.
20360                int oldState = pkgSetting.getEnabled(userId);
20361                if (className == null
20362                        &&
20363                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20364                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20365                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20366                        &&
20367                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20368                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20369                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20370                    // ok
20371                } else {
20372                    throw new SecurityException(
20373                            "Shell cannot change component state for " + packageName + "/"
20374                                    + className + " to " + newState);
20375                }
20376            }
20377        }
20378        if (className == null) {
20379            // We're dealing with an application/package level state change
20380            synchronized (mPackages) {
20381                if (pkgSetting.getEnabled(userId) == newState) {
20382                    // Nothing to do
20383                    return;
20384                }
20385            }
20386            // If we're enabling a system stub, there's a little more work to do.
20387            // Prior to enabling the package, we need to decompress the APK(s) to the
20388            // data partition and then replace the version on the system partition.
20389            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20390            final boolean isSystemStub = deletedPkg.isStub
20391                    && deletedPkg.isSystem();
20392            if (isSystemStub
20393                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20394                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20395                final File codePath = decompressPackage(deletedPkg);
20396                if (codePath == null) {
20397                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20398                    return;
20399                }
20400                // TODO remove direct parsing of the package object during internal cleanup
20401                // of scan package
20402                // We need to call parse directly here for no other reason than we need
20403                // the new package in order to disable the old one [we use the information
20404                // for some internal optimization to optionally create a new package setting
20405                // object on replace]. However, we can't get the package from the scan
20406                // because the scan modifies live structures and we need to remove the
20407                // old [system] package from the system before a scan can be attempted.
20408                // Once scan is indempotent we can remove this parse and use the package
20409                // object we scanned, prior to adding it to package settings.
20410                final PackageParser pp = new PackageParser();
20411                pp.setSeparateProcesses(mSeparateProcesses);
20412                pp.setDisplayMetrics(mMetrics);
20413                pp.setCallback(mPackageParserCallback);
20414                final PackageParser.Package tmpPkg;
20415                try {
20416                    final @ParseFlags int parseFlags = mDefParseFlags
20417                            | PackageParser.PARSE_MUST_BE_APK
20418                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20419                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20420                } catch (PackageParserException e) {
20421                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20422                    return;
20423                }
20424                synchronized (mInstallLock) {
20425                    // Disable the stub and remove any package entries
20426                    removePackageLI(deletedPkg, true);
20427                    synchronized (mPackages) {
20428                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20429                    }
20430                    final PackageParser.Package pkg;
20431                    try (PackageFreezer freezer =
20432                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20433                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20434                                | PackageParser.PARSE_ENFORCE_CODE;
20435                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20436                                0 /*currentTime*/, null /*user*/);
20437                        prepareAppDataAfterInstallLIF(pkg);
20438                        synchronized (mPackages) {
20439                            try {
20440                                updateSharedLibrariesLPr(pkg, null);
20441                            } catch (PackageManagerException e) {
20442                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20443                            }
20444                            mPermissionManager.updatePermissions(
20445                                    pkg.packageName, pkg, true, mPackages.values(),
20446                                    mPermissionCallback);
20447                            mSettings.writeLPr();
20448                        }
20449                    } catch (PackageManagerException e) {
20450                        // Whoops! Something went wrong; try to roll back to the stub
20451                        Slog.w(TAG, "Failed to install compressed system package:"
20452                                + pkgSetting.name, e);
20453                        // Remove the failed install
20454                        removeCodePathLI(codePath);
20455
20456                        // Install the system package
20457                        try (PackageFreezer freezer =
20458                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20459                            synchronized (mPackages) {
20460                                // NOTE: The system package always needs to be enabled; even
20461                                // if it's for a compressed stub. If we don't, installing the
20462                                // system package fails during scan [scanning checks the disabled
20463                                // packages]. We will reverse this later, after we've "installed"
20464                                // the stub.
20465                                // This leaves us in a fragile state; the stub should never be
20466                                // enabled, so, cross your fingers and hope nothing goes wrong
20467                                // until we can disable the package later.
20468                                enableSystemPackageLPw(deletedPkg);
20469                            }
20470                            installPackageFromSystemLIF(deletedPkg.codePath,
20471                                    false /*isPrivileged*/, null /*allUserHandles*/,
20472                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20473                                    true /*writeSettings*/);
20474                        } catch (PackageManagerException pme) {
20475                            Slog.w(TAG, "Failed to restore system package:"
20476                                    + deletedPkg.packageName, pme);
20477                        } finally {
20478                            synchronized (mPackages) {
20479                                mSettings.disableSystemPackageLPw(
20480                                        deletedPkg.packageName, true /*replaced*/);
20481                                mSettings.writeLPr();
20482                            }
20483                        }
20484                        return;
20485                    }
20486                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20487                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20488                    mDexManager.notifyPackageUpdated(pkg.packageName,
20489                            pkg.baseCodePath, pkg.splitCodePaths);
20490                }
20491            }
20492            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20493                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20494                // Don't care about who enables an app.
20495                callingPackage = null;
20496            }
20497            synchronized (mPackages) {
20498                pkgSetting.setEnabled(newState, userId, callingPackage);
20499            }
20500        } else {
20501            synchronized (mPackages) {
20502                // We're dealing with a component level state change
20503                // First, verify that this is a valid class name.
20504                PackageParser.Package pkg = pkgSetting.pkg;
20505                if (pkg == null || !pkg.hasComponentClassName(className)) {
20506                    if (pkg != null &&
20507                            pkg.applicationInfo.targetSdkVersion >=
20508                                    Build.VERSION_CODES.JELLY_BEAN) {
20509                        throw new IllegalArgumentException("Component class " + className
20510                                + " does not exist in " + packageName);
20511                    } else {
20512                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20513                                + className + " does not exist in " + packageName);
20514                    }
20515                }
20516                switch (newState) {
20517                    case COMPONENT_ENABLED_STATE_ENABLED:
20518                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20519                            return;
20520                        }
20521                        break;
20522                    case COMPONENT_ENABLED_STATE_DISABLED:
20523                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20524                            return;
20525                        }
20526                        break;
20527                    case COMPONENT_ENABLED_STATE_DEFAULT:
20528                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20529                            return;
20530                        }
20531                        break;
20532                    default:
20533                        Slog.e(TAG, "Invalid new component state: " + newState);
20534                        return;
20535                }
20536            }
20537        }
20538        synchronized (mPackages) {
20539            scheduleWritePackageRestrictionsLocked(userId);
20540            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20541            final long callingId = Binder.clearCallingIdentity();
20542            try {
20543                updateInstantAppInstallerLocked(packageName);
20544            } finally {
20545                Binder.restoreCallingIdentity(callingId);
20546            }
20547            components = mPendingBroadcasts.get(userId, packageName);
20548            final boolean newPackage = components == null;
20549            if (newPackage) {
20550                components = new ArrayList<String>();
20551            }
20552            if (!components.contains(componentName)) {
20553                components.add(componentName);
20554            }
20555            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20556                sendNow = true;
20557                // Purge entry from pending broadcast list if another one exists already
20558                // since we are sending one right away.
20559                mPendingBroadcasts.remove(userId, packageName);
20560            } else {
20561                if (newPackage) {
20562                    mPendingBroadcasts.put(userId, packageName, components);
20563                }
20564                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20565                    // Schedule a message
20566                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20567                }
20568            }
20569        }
20570
20571        long callingId = Binder.clearCallingIdentity();
20572        try {
20573            if (sendNow) {
20574                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20575                sendPackageChangedBroadcast(packageName,
20576                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20577            }
20578        } finally {
20579            Binder.restoreCallingIdentity(callingId);
20580        }
20581    }
20582
20583    @Override
20584    public void flushPackageRestrictionsAsUser(int userId) {
20585        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20586            return;
20587        }
20588        if (!sUserManager.exists(userId)) {
20589            return;
20590        }
20591        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20592                false /* checkShell */, "flushPackageRestrictions");
20593        synchronized (mPackages) {
20594            mSettings.writePackageRestrictionsLPr(userId);
20595            mDirtyUsers.remove(userId);
20596            if (mDirtyUsers.isEmpty()) {
20597                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20598            }
20599        }
20600    }
20601
20602    private void sendPackageChangedBroadcast(String packageName,
20603            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20604        if (DEBUG_INSTALL)
20605            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20606                    + componentNames);
20607        Bundle extras = new Bundle(4);
20608        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20609        String nameList[] = new String[componentNames.size()];
20610        componentNames.toArray(nameList);
20611        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20612        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20613        extras.putInt(Intent.EXTRA_UID, packageUid);
20614        // If this is not reporting a change of the overall package, then only send it
20615        // to registered receivers.  We don't want to launch a swath of apps for every
20616        // little component state change.
20617        final int flags = !componentNames.contains(packageName)
20618                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20619        final int userId = UserHandle.getUserId(packageUid);
20620        final boolean isInstantApp = isInstantApp(packageName, userId);
20621        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20622        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20623        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20624                userIds, instantUserIds);
20625    }
20626
20627    @Override
20628    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20629        if (!sUserManager.exists(userId)) return;
20630        final int callingUid = Binder.getCallingUid();
20631        if (getInstantAppPackageName(callingUid) != null) {
20632            return;
20633        }
20634        final int permission = mContext.checkCallingOrSelfPermission(
20635                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20636        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20637        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20638                true /* requireFullPermission */, true /* checkShell */, "stop package");
20639        // writer
20640        synchronized (mPackages) {
20641            final PackageSetting ps = mSettings.mPackages.get(packageName);
20642            if (!filterAppAccessLPr(ps, callingUid, userId)
20643                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20644                            allowedByPermission, callingUid, userId)) {
20645                scheduleWritePackageRestrictionsLocked(userId);
20646            }
20647        }
20648    }
20649
20650    @Override
20651    public String getInstallerPackageName(String packageName) {
20652        final int callingUid = Binder.getCallingUid();
20653        if (getInstantAppPackageName(callingUid) != null) {
20654            return null;
20655        }
20656        // reader
20657        synchronized (mPackages) {
20658            final PackageSetting ps = mSettings.mPackages.get(packageName);
20659            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20660                return null;
20661            }
20662            return mSettings.getInstallerPackageNameLPr(packageName);
20663        }
20664    }
20665
20666    public boolean isOrphaned(String packageName) {
20667        // reader
20668        synchronized (mPackages) {
20669            return mSettings.isOrphaned(packageName);
20670        }
20671    }
20672
20673    @Override
20674    public int getApplicationEnabledSetting(String packageName, int userId) {
20675        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20676        int callingUid = Binder.getCallingUid();
20677        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20678                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20679        // reader
20680        synchronized (mPackages) {
20681            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20682                return COMPONENT_ENABLED_STATE_DISABLED;
20683            }
20684            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20685        }
20686    }
20687
20688    @Override
20689    public int getComponentEnabledSetting(ComponentName component, int userId) {
20690        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20691        int callingUid = Binder.getCallingUid();
20692        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20693                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20694        synchronized (mPackages) {
20695            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20696                    component, TYPE_UNKNOWN, userId)) {
20697                return COMPONENT_ENABLED_STATE_DISABLED;
20698            }
20699            return mSettings.getComponentEnabledSettingLPr(component, userId);
20700        }
20701    }
20702
20703    @Override
20704    public void enterSafeMode() {
20705        enforceSystemOrRoot("Only the system can request entering safe mode");
20706
20707        if (!mSystemReady) {
20708            mSafeMode = true;
20709        }
20710    }
20711
20712    @Override
20713    public void systemReady() {
20714        enforceSystemOrRoot("Only the system can claim the system is ready");
20715
20716        mSystemReady = true;
20717        final ContentResolver resolver = mContext.getContentResolver();
20718        ContentObserver co = new ContentObserver(mHandler) {
20719            @Override
20720            public void onChange(boolean selfChange) {
20721                mEphemeralAppsDisabled =
20722                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20723                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20724            }
20725        };
20726        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20727                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20728                false, co, UserHandle.USER_SYSTEM);
20729        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20730                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20731        co.onChange(true);
20732
20733        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20734        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20735        // it is done.
20736        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20737            @Override
20738            public void onChange(boolean selfChange) {
20739                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20740                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20741                        oobEnabled == 1 ? "true" : "false");
20742            }
20743        };
20744        mContext.getContentResolver().registerContentObserver(
20745                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20746                UserHandle.USER_SYSTEM);
20747        // At boot, restore the value from the setting, which persists across reboot.
20748        privAppOobObserver.onChange(true);
20749
20750        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20751        // disabled after already being started.
20752        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20753                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20754
20755        // Read the compatibilty setting when the system is ready.
20756        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20757                mContext.getContentResolver(),
20758                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20759        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20760        if (DEBUG_SETTINGS) {
20761            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20762        }
20763
20764        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20765
20766        synchronized (mPackages) {
20767            // Verify that all of the preferred activity components actually
20768            // exist.  It is possible for applications to be updated and at
20769            // that point remove a previously declared activity component that
20770            // had been set as a preferred activity.  We try to clean this up
20771            // the next time we encounter that preferred activity, but it is
20772            // possible for the user flow to never be able to return to that
20773            // situation so here we do a sanity check to make sure we haven't
20774            // left any junk around.
20775            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20776            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20777                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20778                removed.clear();
20779                for (PreferredActivity pa : pir.filterSet()) {
20780                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20781                        removed.add(pa);
20782                    }
20783                }
20784                if (removed.size() > 0) {
20785                    for (int r=0; r<removed.size(); r++) {
20786                        PreferredActivity pa = removed.get(r);
20787                        Slog.w(TAG, "Removing dangling preferred activity: "
20788                                + pa.mPref.mComponent);
20789                        pir.removeFilter(pa);
20790                    }
20791                    mSettings.writePackageRestrictionsLPr(
20792                            mSettings.mPreferredActivities.keyAt(i));
20793                }
20794            }
20795
20796            for (int userId : UserManagerService.getInstance().getUserIds()) {
20797                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20798                    grantPermissionsUserIds = ArrayUtils.appendInt(
20799                            grantPermissionsUserIds, userId);
20800                }
20801            }
20802        }
20803        sUserManager.systemReady();
20804        // If we upgraded grant all default permissions before kicking off.
20805        for (int userId : grantPermissionsUserIds) {
20806            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20807        }
20808
20809        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20810            // If we did not grant default permissions, we preload from this the
20811            // default permission exceptions lazily to ensure we don't hit the
20812            // disk on a new user creation.
20813            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20814        }
20815
20816        // Now that we've scanned all packages, and granted any default
20817        // permissions, ensure permissions are updated. Beware of dragons if you
20818        // try optimizing this.
20819        synchronized (mPackages) {
20820            mPermissionManager.updateAllPermissions(
20821                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20822                    mPermissionCallback);
20823        }
20824
20825        // Kick off any messages waiting for system ready
20826        if (mPostSystemReadyMessages != null) {
20827            for (Message msg : mPostSystemReadyMessages) {
20828                msg.sendToTarget();
20829            }
20830            mPostSystemReadyMessages = null;
20831        }
20832
20833        // Watch for external volumes that come and go over time
20834        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20835        storage.registerListener(mStorageListener);
20836
20837        mInstallerService.systemReady();
20838        mPackageDexOptimizer.systemReady();
20839
20840        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20841                StorageManagerInternal.class);
20842        StorageManagerInternal.addExternalStoragePolicy(
20843                new StorageManagerInternal.ExternalStorageMountPolicy() {
20844            @Override
20845            public int getMountMode(int uid, String packageName) {
20846                if (Process.isIsolated(uid)) {
20847                    return Zygote.MOUNT_EXTERNAL_NONE;
20848                }
20849                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20850                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20851                }
20852                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20853                    return Zygote.MOUNT_EXTERNAL_READ;
20854                }
20855                return Zygote.MOUNT_EXTERNAL_WRITE;
20856            }
20857
20858            @Override
20859            public boolean hasExternalStorage(int uid, String packageName) {
20860                return true;
20861            }
20862        });
20863
20864        // Now that we're mostly running, clean up stale users and apps
20865        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20866        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20867
20868        mPermissionManager.systemReady();
20869    }
20870
20871    public void waitForAppDataPrepared() {
20872        if (mPrepareAppDataFuture == null) {
20873            return;
20874        }
20875        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20876        mPrepareAppDataFuture = null;
20877    }
20878
20879    @Override
20880    public boolean isSafeMode() {
20881        // allow instant applications
20882        return mSafeMode;
20883    }
20884
20885    @Override
20886    public boolean hasSystemUidErrors() {
20887        // allow instant applications
20888        return mHasSystemUidErrors;
20889    }
20890
20891    static String arrayToString(int[] array) {
20892        StringBuffer buf = new StringBuffer(128);
20893        buf.append('[');
20894        if (array != null) {
20895            for (int i=0; i<array.length; i++) {
20896                if (i > 0) buf.append(", ");
20897                buf.append(array[i]);
20898            }
20899        }
20900        buf.append(']');
20901        return buf.toString();
20902    }
20903
20904    @Override
20905    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20906            FileDescriptor err, String[] args, ShellCallback callback,
20907            ResultReceiver resultReceiver) {
20908        (new PackageManagerShellCommand(this)).exec(
20909                this, in, out, err, args, callback, resultReceiver);
20910    }
20911
20912    @Override
20913    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20914        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20915
20916        DumpState dumpState = new DumpState();
20917        boolean fullPreferred = false;
20918        boolean checkin = false;
20919
20920        String packageName = null;
20921        ArraySet<String> permissionNames = null;
20922
20923        int opti = 0;
20924        while (opti < args.length) {
20925            String opt = args[opti];
20926            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20927                break;
20928            }
20929            opti++;
20930
20931            if ("-a".equals(opt)) {
20932                // Right now we only know how to print all.
20933            } else if ("-h".equals(opt)) {
20934                pw.println("Package manager dump options:");
20935                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20936                pw.println("    --checkin: dump for a checkin");
20937                pw.println("    -f: print details of intent filters");
20938                pw.println("    -h: print this help");
20939                pw.println("  cmd may be one of:");
20940                pw.println("    l[ibraries]: list known shared libraries");
20941                pw.println("    f[eatures]: list device features");
20942                pw.println("    k[eysets]: print known keysets");
20943                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20944                pw.println("    perm[issions]: dump permissions");
20945                pw.println("    permission [name ...]: dump declaration and use of given permission");
20946                pw.println("    pref[erred]: print preferred package settings");
20947                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20948                pw.println("    prov[iders]: dump content providers");
20949                pw.println("    p[ackages]: dump installed packages");
20950                pw.println("    s[hared-users]: dump shared user IDs");
20951                pw.println("    m[essages]: print collected runtime messages");
20952                pw.println("    v[erifiers]: print package verifier info");
20953                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20954                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20955                pw.println("    version: print database version info");
20956                pw.println("    write: write current settings now");
20957                pw.println("    installs: details about install sessions");
20958                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20959                pw.println("    dexopt: dump dexopt state");
20960                pw.println("    compiler-stats: dump compiler statistics");
20961                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20962                pw.println("    service-permissions: dump permissions required by services");
20963                pw.println("    <package.name>: info about given package");
20964                return;
20965            } else if ("--checkin".equals(opt)) {
20966                checkin = true;
20967            } else if ("-f".equals(opt)) {
20968                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20969            } else if ("--proto".equals(opt)) {
20970                dumpProto(fd);
20971                return;
20972            } else {
20973                pw.println("Unknown argument: " + opt + "; use -h for help");
20974            }
20975        }
20976
20977        // Is the caller requesting to dump a particular piece of data?
20978        if (opti < args.length) {
20979            String cmd = args[opti];
20980            opti++;
20981            // Is this a package name?
20982            if ("android".equals(cmd) || cmd.contains(".")) {
20983                packageName = cmd;
20984                // When dumping a single package, we always dump all of its
20985                // filter information since the amount of data will be reasonable.
20986                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20987            } else if ("check-permission".equals(cmd)) {
20988                if (opti >= args.length) {
20989                    pw.println("Error: check-permission missing permission argument");
20990                    return;
20991                }
20992                String perm = args[opti];
20993                opti++;
20994                if (opti >= args.length) {
20995                    pw.println("Error: check-permission missing package argument");
20996                    return;
20997                }
20998
20999                String pkg = args[opti];
21000                opti++;
21001                int user = UserHandle.getUserId(Binder.getCallingUid());
21002                if (opti < args.length) {
21003                    try {
21004                        user = Integer.parseInt(args[opti]);
21005                    } catch (NumberFormatException e) {
21006                        pw.println("Error: check-permission user argument is not a number: "
21007                                + args[opti]);
21008                        return;
21009                    }
21010                }
21011
21012                // Normalize package name to handle renamed packages and static libs
21013                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21014
21015                pw.println(checkPermission(perm, pkg, user));
21016                return;
21017            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21018                dumpState.setDump(DumpState.DUMP_LIBS);
21019            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21020                dumpState.setDump(DumpState.DUMP_FEATURES);
21021            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21022                if (opti >= args.length) {
21023                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21024                            | DumpState.DUMP_SERVICE_RESOLVERS
21025                            | DumpState.DUMP_RECEIVER_RESOLVERS
21026                            | DumpState.DUMP_CONTENT_RESOLVERS);
21027                } else {
21028                    while (opti < args.length) {
21029                        String name = args[opti];
21030                        if ("a".equals(name) || "activity".equals(name)) {
21031                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21032                        } else if ("s".equals(name) || "service".equals(name)) {
21033                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21034                        } else if ("r".equals(name) || "receiver".equals(name)) {
21035                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21036                        } else if ("c".equals(name) || "content".equals(name)) {
21037                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21038                        } else {
21039                            pw.println("Error: unknown resolver table type: " + name);
21040                            return;
21041                        }
21042                        opti++;
21043                    }
21044                }
21045            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21046                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21047            } else if ("permission".equals(cmd)) {
21048                if (opti >= args.length) {
21049                    pw.println("Error: permission requires permission name");
21050                    return;
21051                }
21052                permissionNames = new ArraySet<>();
21053                while (opti < args.length) {
21054                    permissionNames.add(args[opti]);
21055                    opti++;
21056                }
21057                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21058                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21059            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21060                dumpState.setDump(DumpState.DUMP_PREFERRED);
21061            } else if ("preferred-xml".equals(cmd)) {
21062                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21063                if (opti < args.length && "--full".equals(args[opti])) {
21064                    fullPreferred = true;
21065                    opti++;
21066                }
21067            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21068                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21069            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21070                dumpState.setDump(DumpState.DUMP_PACKAGES);
21071            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21072                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21073            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21074                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21075            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21076                dumpState.setDump(DumpState.DUMP_MESSAGES);
21077            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21078                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21079            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21080                    || "intent-filter-verifiers".equals(cmd)) {
21081                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21082            } else if ("version".equals(cmd)) {
21083                dumpState.setDump(DumpState.DUMP_VERSION);
21084            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21085                dumpState.setDump(DumpState.DUMP_KEYSETS);
21086            } else if ("installs".equals(cmd)) {
21087                dumpState.setDump(DumpState.DUMP_INSTALLS);
21088            } else if ("frozen".equals(cmd)) {
21089                dumpState.setDump(DumpState.DUMP_FROZEN);
21090            } else if ("volumes".equals(cmd)) {
21091                dumpState.setDump(DumpState.DUMP_VOLUMES);
21092            } else if ("dexopt".equals(cmd)) {
21093                dumpState.setDump(DumpState.DUMP_DEXOPT);
21094            } else if ("compiler-stats".equals(cmd)) {
21095                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21096            } else if ("changes".equals(cmd)) {
21097                dumpState.setDump(DumpState.DUMP_CHANGES);
21098            } else if ("service-permissions".equals(cmd)) {
21099                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21100            } else if ("write".equals(cmd)) {
21101                synchronized (mPackages) {
21102                    mSettings.writeLPr();
21103                    pw.println("Settings written.");
21104                    return;
21105                }
21106            }
21107        }
21108
21109        if (checkin) {
21110            pw.println("vers,1");
21111        }
21112
21113        // reader
21114        synchronized (mPackages) {
21115            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21116                if (!checkin) {
21117                    if (dumpState.onTitlePrinted())
21118                        pw.println();
21119                    pw.println("Database versions:");
21120                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21121                }
21122            }
21123
21124            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21125                if (!checkin) {
21126                    if (dumpState.onTitlePrinted())
21127                        pw.println();
21128                    pw.println("Verifiers:");
21129                    pw.print("  Required: ");
21130                    pw.print(mRequiredVerifierPackage);
21131                    pw.print(" (uid=");
21132                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21133                            UserHandle.USER_SYSTEM));
21134                    pw.println(")");
21135                } else if (mRequiredVerifierPackage != null) {
21136                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21137                    pw.print(",");
21138                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21139                            UserHandle.USER_SYSTEM));
21140                }
21141            }
21142
21143            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21144                    packageName == null) {
21145                if (mIntentFilterVerifierComponent != null) {
21146                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21147                    if (!checkin) {
21148                        if (dumpState.onTitlePrinted())
21149                            pw.println();
21150                        pw.println("Intent Filter Verifier:");
21151                        pw.print("  Using: ");
21152                        pw.print(verifierPackageName);
21153                        pw.print(" (uid=");
21154                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21155                                UserHandle.USER_SYSTEM));
21156                        pw.println(")");
21157                    } else if (verifierPackageName != null) {
21158                        pw.print("ifv,"); pw.print(verifierPackageName);
21159                        pw.print(",");
21160                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21161                                UserHandle.USER_SYSTEM));
21162                    }
21163                } else {
21164                    pw.println();
21165                    pw.println("No Intent Filter Verifier available!");
21166                }
21167            }
21168
21169            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21170                boolean printedHeader = false;
21171                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21172                while (it.hasNext()) {
21173                    String libName = it.next();
21174                    LongSparseArray<SharedLibraryEntry> versionedLib
21175                            = mSharedLibraries.get(libName);
21176                    if (versionedLib == null) {
21177                        continue;
21178                    }
21179                    final int versionCount = versionedLib.size();
21180                    for (int i = 0; i < versionCount; i++) {
21181                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21182                        if (!checkin) {
21183                            if (!printedHeader) {
21184                                if (dumpState.onTitlePrinted())
21185                                    pw.println();
21186                                pw.println("Libraries:");
21187                                printedHeader = true;
21188                            }
21189                            pw.print("  ");
21190                        } else {
21191                            pw.print("lib,");
21192                        }
21193                        pw.print(libEntry.info.getName());
21194                        if (libEntry.info.isStatic()) {
21195                            pw.print(" version=" + libEntry.info.getLongVersion());
21196                        }
21197                        if (!checkin) {
21198                            pw.print(" -> ");
21199                        }
21200                        if (libEntry.path != null) {
21201                            pw.print(" (jar) ");
21202                            pw.print(libEntry.path);
21203                        } else {
21204                            pw.print(" (apk) ");
21205                            pw.print(libEntry.apk);
21206                        }
21207                        pw.println();
21208                    }
21209                }
21210            }
21211
21212            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21213                if (dumpState.onTitlePrinted())
21214                    pw.println();
21215                if (!checkin) {
21216                    pw.println("Features:");
21217                }
21218
21219                synchronized (mAvailableFeatures) {
21220                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21221                        if (checkin) {
21222                            pw.print("feat,");
21223                            pw.print(feat.name);
21224                            pw.print(",");
21225                            pw.println(feat.version);
21226                        } else {
21227                            pw.print("  ");
21228                            pw.print(feat.name);
21229                            if (feat.version > 0) {
21230                                pw.print(" version=");
21231                                pw.print(feat.version);
21232                            }
21233                            pw.println();
21234                        }
21235                    }
21236                }
21237            }
21238
21239            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21240                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21241                        : "Activity Resolver Table:", "  ", packageName,
21242                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21243                    dumpState.setTitlePrinted(true);
21244                }
21245            }
21246            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21247                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21248                        : "Receiver Resolver Table:", "  ", packageName,
21249                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21250                    dumpState.setTitlePrinted(true);
21251                }
21252            }
21253            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21254                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21255                        : "Service Resolver Table:", "  ", packageName,
21256                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21257                    dumpState.setTitlePrinted(true);
21258                }
21259            }
21260            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21261                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21262                        : "Provider Resolver Table:", "  ", packageName,
21263                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21264                    dumpState.setTitlePrinted(true);
21265                }
21266            }
21267
21268            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21269                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21270                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21271                    int user = mSettings.mPreferredActivities.keyAt(i);
21272                    if (pir.dump(pw,
21273                            dumpState.getTitlePrinted()
21274                                ? "\nPreferred Activities User " + user + ":"
21275                                : "Preferred Activities User " + user + ":", "  ",
21276                            packageName, true, false)) {
21277                        dumpState.setTitlePrinted(true);
21278                    }
21279                }
21280            }
21281
21282            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21283                pw.flush();
21284                FileOutputStream fout = new FileOutputStream(fd);
21285                BufferedOutputStream str = new BufferedOutputStream(fout);
21286                XmlSerializer serializer = new FastXmlSerializer();
21287                try {
21288                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21289                    serializer.startDocument(null, true);
21290                    serializer.setFeature(
21291                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21292                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21293                    serializer.endDocument();
21294                    serializer.flush();
21295                } catch (IllegalArgumentException e) {
21296                    pw.println("Failed writing: " + e);
21297                } catch (IllegalStateException e) {
21298                    pw.println("Failed writing: " + e);
21299                } catch (IOException e) {
21300                    pw.println("Failed writing: " + e);
21301                }
21302            }
21303
21304            if (!checkin
21305                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21306                    && packageName == null) {
21307                pw.println();
21308                int count = mSettings.mPackages.size();
21309                if (count == 0) {
21310                    pw.println("No applications!");
21311                    pw.println();
21312                } else {
21313                    final String prefix = "  ";
21314                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21315                    if (allPackageSettings.size() == 0) {
21316                        pw.println("No domain preferred apps!");
21317                        pw.println();
21318                    } else {
21319                        pw.println("App verification status:");
21320                        pw.println();
21321                        count = 0;
21322                        for (PackageSetting ps : allPackageSettings) {
21323                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21324                            if (ivi == null || ivi.getPackageName() == null) continue;
21325                            pw.println(prefix + "Package: " + ivi.getPackageName());
21326                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21327                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21328                            pw.println();
21329                            count++;
21330                        }
21331                        if (count == 0) {
21332                            pw.println(prefix + "No app verification established.");
21333                            pw.println();
21334                        }
21335                        for (int userId : sUserManager.getUserIds()) {
21336                            pw.println("App linkages for user " + userId + ":");
21337                            pw.println();
21338                            count = 0;
21339                            for (PackageSetting ps : allPackageSettings) {
21340                                final long status = ps.getDomainVerificationStatusForUser(userId);
21341                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21342                                        && !DEBUG_DOMAIN_VERIFICATION) {
21343                                    continue;
21344                                }
21345                                pw.println(prefix + "Package: " + ps.name);
21346                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21347                                String statusStr = IntentFilterVerificationInfo.
21348                                        getStatusStringFromValue(status);
21349                                pw.println(prefix + "Status:  " + statusStr);
21350                                pw.println();
21351                                count++;
21352                            }
21353                            if (count == 0) {
21354                                pw.println(prefix + "No configured app linkages.");
21355                                pw.println();
21356                            }
21357                        }
21358                    }
21359                }
21360            }
21361
21362            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21363                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21364            }
21365
21366            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21367                boolean printedSomething = false;
21368                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21369                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21370                        continue;
21371                    }
21372                    if (!printedSomething) {
21373                        if (dumpState.onTitlePrinted())
21374                            pw.println();
21375                        pw.println("Registered ContentProviders:");
21376                        printedSomething = true;
21377                    }
21378                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21379                    pw.print("    "); pw.println(p.toString());
21380                }
21381                printedSomething = false;
21382                for (Map.Entry<String, PackageParser.Provider> entry :
21383                        mProvidersByAuthority.entrySet()) {
21384                    PackageParser.Provider p = entry.getValue();
21385                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21386                        continue;
21387                    }
21388                    if (!printedSomething) {
21389                        if (dumpState.onTitlePrinted())
21390                            pw.println();
21391                        pw.println("ContentProvider Authorities:");
21392                        printedSomething = true;
21393                    }
21394                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21395                    pw.print("    "); pw.println(p.toString());
21396                    if (p.info != null && p.info.applicationInfo != null) {
21397                        final String appInfo = p.info.applicationInfo.toString();
21398                        pw.print("      applicationInfo="); pw.println(appInfo);
21399                    }
21400                }
21401            }
21402
21403            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21404                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21405            }
21406
21407            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21408                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21409            }
21410
21411            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21412                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21413            }
21414
21415            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21416                if (dumpState.onTitlePrinted()) pw.println();
21417                pw.println("Package Changes:");
21418                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21419                final int K = mChangedPackages.size();
21420                for (int i = 0; i < K; i++) {
21421                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21422                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21423                    final int N = changes.size();
21424                    if (N == 0) {
21425                        pw.print("    "); pw.println("No packages changed");
21426                    } else {
21427                        for (int j = 0; j < N; j++) {
21428                            final String pkgName = changes.valueAt(j);
21429                            final int sequenceNumber = changes.keyAt(j);
21430                            pw.print("    ");
21431                            pw.print("seq=");
21432                            pw.print(sequenceNumber);
21433                            pw.print(", package=");
21434                            pw.println(pkgName);
21435                        }
21436                    }
21437                }
21438            }
21439
21440            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21441                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21442            }
21443
21444            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21445                // XXX should handle packageName != null by dumping only install data that
21446                // the given package is involved with.
21447                if (dumpState.onTitlePrinted()) pw.println();
21448
21449                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21450                ipw.println();
21451                ipw.println("Frozen packages:");
21452                ipw.increaseIndent();
21453                if (mFrozenPackages.size() == 0) {
21454                    ipw.println("(none)");
21455                } else {
21456                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21457                        ipw.println(mFrozenPackages.valueAt(i));
21458                    }
21459                }
21460                ipw.decreaseIndent();
21461            }
21462
21463            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21464                if (dumpState.onTitlePrinted()) pw.println();
21465
21466                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21467                ipw.println();
21468                ipw.println("Loaded volumes:");
21469                ipw.increaseIndent();
21470                if (mLoadedVolumes.size() == 0) {
21471                    ipw.println("(none)");
21472                } else {
21473                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21474                        ipw.println(mLoadedVolumes.valueAt(i));
21475                    }
21476                }
21477                ipw.decreaseIndent();
21478            }
21479
21480            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21481                    && packageName == null) {
21482                if (dumpState.onTitlePrinted()) pw.println();
21483                pw.println("Service permissions:");
21484
21485                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21486                while (filterIterator.hasNext()) {
21487                    final ServiceIntentInfo info = filterIterator.next();
21488                    final ServiceInfo serviceInfo = info.service.info;
21489                    final String permission = serviceInfo.permission;
21490                    if (permission != null) {
21491                        pw.print("    ");
21492                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21493                        pw.print(": ");
21494                        pw.println(permission);
21495                    }
21496                }
21497            }
21498
21499            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21500                if (dumpState.onTitlePrinted()) pw.println();
21501                dumpDexoptStateLPr(pw, packageName);
21502            }
21503
21504            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21505                if (dumpState.onTitlePrinted()) pw.println();
21506                dumpCompilerStatsLPr(pw, packageName);
21507            }
21508
21509            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21510                if (dumpState.onTitlePrinted()) pw.println();
21511                mSettings.dumpReadMessagesLPr(pw, dumpState);
21512
21513                pw.println();
21514                pw.println("Package warning messages:");
21515                dumpCriticalInfo(pw, null);
21516            }
21517
21518            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21519                dumpCriticalInfo(pw, "msg,");
21520            }
21521        }
21522
21523        // PackageInstaller should be called outside of mPackages lock
21524        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21525            // XXX should handle packageName != null by dumping only install data that
21526            // the given package is involved with.
21527            if (dumpState.onTitlePrinted()) pw.println();
21528            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21529        }
21530    }
21531
21532    private void dumpProto(FileDescriptor fd) {
21533        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21534
21535        synchronized (mPackages) {
21536            final long requiredVerifierPackageToken =
21537                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21538            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21539            proto.write(
21540                    PackageServiceDumpProto.PackageShortProto.UID,
21541                    getPackageUid(
21542                            mRequiredVerifierPackage,
21543                            MATCH_DEBUG_TRIAGED_MISSING,
21544                            UserHandle.USER_SYSTEM));
21545            proto.end(requiredVerifierPackageToken);
21546
21547            if (mIntentFilterVerifierComponent != null) {
21548                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21549                final long verifierPackageToken =
21550                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21551                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21552                proto.write(
21553                        PackageServiceDumpProto.PackageShortProto.UID,
21554                        getPackageUid(
21555                                verifierPackageName,
21556                                MATCH_DEBUG_TRIAGED_MISSING,
21557                                UserHandle.USER_SYSTEM));
21558                proto.end(verifierPackageToken);
21559            }
21560
21561            dumpSharedLibrariesProto(proto);
21562            dumpFeaturesProto(proto);
21563            mSettings.dumpPackagesProto(proto);
21564            mSettings.dumpSharedUsersProto(proto);
21565            dumpCriticalInfo(proto);
21566        }
21567        proto.flush();
21568    }
21569
21570    private void dumpFeaturesProto(ProtoOutputStream proto) {
21571        synchronized (mAvailableFeatures) {
21572            final int count = mAvailableFeatures.size();
21573            for (int i = 0; i < count; i++) {
21574                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21575            }
21576        }
21577    }
21578
21579    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21580        final int count = mSharedLibraries.size();
21581        for (int i = 0; i < count; i++) {
21582            final String libName = mSharedLibraries.keyAt(i);
21583            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21584            if (versionedLib == null) {
21585                continue;
21586            }
21587            final int versionCount = versionedLib.size();
21588            for (int j = 0; j < versionCount; j++) {
21589                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21590                final long sharedLibraryToken =
21591                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21592                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21593                final boolean isJar = (libEntry.path != null);
21594                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21595                if (isJar) {
21596                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21597                } else {
21598                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21599                }
21600                proto.end(sharedLibraryToken);
21601            }
21602        }
21603    }
21604
21605    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21606        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21607        ipw.println();
21608        ipw.println("Dexopt state:");
21609        ipw.increaseIndent();
21610        Collection<PackageParser.Package> packages = null;
21611        if (packageName != null) {
21612            PackageParser.Package targetPackage = mPackages.get(packageName);
21613            if (targetPackage != null) {
21614                packages = Collections.singletonList(targetPackage);
21615            } else {
21616                ipw.println("Unable to find package: " + packageName);
21617                return;
21618            }
21619        } else {
21620            packages = mPackages.values();
21621        }
21622
21623        for (PackageParser.Package pkg : packages) {
21624            ipw.println("[" + pkg.packageName + "]");
21625            ipw.increaseIndent();
21626            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21627                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21628            ipw.decreaseIndent();
21629        }
21630    }
21631
21632    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21633        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21634        ipw.println();
21635        ipw.println("Compiler stats:");
21636        ipw.increaseIndent();
21637        Collection<PackageParser.Package> packages = null;
21638        if (packageName != null) {
21639            PackageParser.Package targetPackage = mPackages.get(packageName);
21640            if (targetPackage != null) {
21641                packages = Collections.singletonList(targetPackage);
21642            } else {
21643                ipw.println("Unable to find package: " + packageName);
21644                return;
21645            }
21646        } else {
21647            packages = mPackages.values();
21648        }
21649
21650        for (PackageParser.Package pkg : packages) {
21651            ipw.println("[" + pkg.packageName + "]");
21652            ipw.increaseIndent();
21653
21654            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21655            if (stats == null) {
21656                ipw.println("(No recorded stats)");
21657            } else {
21658                stats.dump(ipw);
21659            }
21660            ipw.decreaseIndent();
21661        }
21662    }
21663
21664    private String dumpDomainString(String packageName) {
21665        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21666                .getList();
21667        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21668
21669        ArraySet<String> result = new ArraySet<>();
21670        if (iviList.size() > 0) {
21671            for (IntentFilterVerificationInfo ivi : iviList) {
21672                for (String host : ivi.getDomains()) {
21673                    result.add(host);
21674                }
21675            }
21676        }
21677        if (filters != null && filters.size() > 0) {
21678            for (IntentFilter filter : filters) {
21679                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21680                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21681                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21682                    result.addAll(filter.getHostsList());
21683                }
21684            }
21685        }
21686
21687        StringBuilder sb = new StringBuilder(result.size() * 16);
21688        for (String domain : result) {
21689            if (sb.length() > 0) sb.append(" ");
21690            sb.append(domain);
21691        }
21692        return sb.toString();
21693    }
21694
21695    // ------- apps on sdcard specific code -------
21696    static final boolean DEBUG_SD_INSTALL = false;
21697
21698    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21699
21700    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21701
21702    private boolean mMediaMounted = false;
21703
21704    static String getEncryptKey() {
21705        try {
21706            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21707                    SD_ENCRYPTION_KEYSTORE_NAME);
21708            if (sdEncKey == null) {
21709                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21710                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21711                if (sdEncKey == null) {
21712                    Slog.e(TAG, "Failed to create encryption keys");
21713                    return null;
21714                }
21715            }
21716            return sdEncKey;
21717        } catch (NoSuchAlgorithmException nsae) {
21718            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21719            return null;
21720        } catch (IOException ioe) {
21721            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21722            return null;
21723        }
21724    }
21725
21726    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21727            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21728        final int size = infos.size();
21729        final String[] packageNames = new String[size];
21730        final int[] packageUids = new int[size];
21731        for (int i = 0; i < size; i++) {
21732            final ApplicationInfo info = infos.get(i);
21733            packageNames[i] = info.packageName;
21734            packageUids[i] = info.uid;
21735        }
21736        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21737                finishedReceiver);
21738    }
21739
21740    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21741            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21742        sendResourcesChangedBroadcast(mediaStatus, replacing,
21743                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21744    }
21745
21746    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21747            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21748        int size = pkgList.length;
21749        if (size > 0) {
21750            // Send broadcasts here
21751            Bundle extras = new Bundle();
21752            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21753            if (uidArr != null) {
21754                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21755            }
21756            if (replacing) {
21757                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21758            }
21759            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21760                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21761            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
21762        }
21763    }
21764
21765    private void loadPrivatePackages(final VolumeInfo vol) {
21766        mHandler.post(new Runnable() {
21767            @Override
21768            public void run() {
21769                loadPrivatePackagesInner(vol);
21770            }
21771        });
21772    }
21773
21774    private void loadPrivatePackagesInner(VolumeInfo vol) {
21775        final String volumeUuid = vol.fsUuid;
21776        if (TextUtils.isEmpty(volumeUuid)) {
21777            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21778            return;
21779        }
21780
21781        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21782        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21783        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21784
21785        final VersionInfo ver;
21786        final List<PackageSetting> packages;
21787        synchronized (mPackages) {
21788            ver = mSettings.findOrCreateVersion(volumeUuid);
21789            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21790        }
21791
21792        for (PackageSetting ps : packages) {
21793            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21794            synchronized (mInstallLock) {
21795                final PackageParser.Package pkg;
21796                try {
21797                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21798                    loaded.add(pkg.applicationInfo);
21799
21800                } catch (PackageManagerException e) {
21801                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21802                }
21803
21804                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21805                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21806                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21807                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21808                }
21809            }
21810        }
21811
21812        // Reconcile app data for all started/unlocked users
21813        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21814        final UserManager um = mContext.getSystemService(UserManager.class);
21815        UserManagerInternal umInternal = getUserManagerInternal();
21816        for (UserInfo user : um.getUsers()) {
21817            final int flags;
21818            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21819                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21820            } else if (umInternal.isUserRunning(user.id)) {
21821                flags = StorageManager.FLAG_STORAGE_DE;
21822            } else {
21823                continue;
21824            }
21825
21826            try {
21827                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21828                synchronized (mInstallLock) {
21829                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21830                }
21831            } catch (IllegalStateException e) {
21832                // Device was probably ejected, and we'll process that event momentarily
21833                Slog.w(TAG, "Failed to prepare storage: " + e);
21834            }
21835        }
21836
21837        synchronized (mPackages) {
21838            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
21839            if (sdkUpdated) {
21840                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21841                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21842            }
21843            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
21844                    mPermissionCallback);
21845
21846            // Yay, everything is now upgraded
21847            ver.forceCurrent();
21848
21849            mSettings.writeLPr();
21850        }
21851
21852        for (PackageFreezer freezer : freezers) {
21853            freezer.close();
21854        }
21855
21856        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21857        sendResourcesChangedBroadcast(true, false, loaded, null);
21858        mLoadedVolumes.add(vol.getId());
21859    }
21860
21861    private void unloadPrivatePackages(final VolumeInfo vol) {
21862        mHandler.post(new Runnable() {
21863            @Override
21864            public void run() {
21865                unloadPrivatePackagesInner(vol);
21866            }
21867        });
21868    }
21869
21870    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21871        final String volumeUuid = vol.fsUuid;
21872        if (TextUtils.isEmpty(volumeUuid)) {
21873            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21874            return;
21875        }
21876
21877        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21878        synchronized (mInstallLock) {
21879        synchronized (mPackages) {
21880            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21881            for (PackageSetting ps : packages) {
21882                if (ps.pkg == null) continue;
21883
21884                final ApplicationInfo info = ps.pkg.applicationInfo;
21885                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21886                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21887
21888                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21889                        "unloadPrivatePackagesInner")) {
21890                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21891                            false, null)) {
21892                        unloaded.add(info);
21893                    } else {
21894                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21895                    }
21896                }
21897
21898                // Try very hard to release any references to this package
21899                // so we don't risk the system server being killed due to
21900                // open FDs
21901                AttributeCache.instance().removePackage(ps.name);
21902            }
21903
21904            mSettings.writeLPr();
21905        }
21906        }
21907
21908        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21909        sendResourcesChangedBroadcast(false, false, unloaded, null);
21910        mLoadedVolumes.remove(vol.getId());
21911
21912        // Try very hard to release any references to this path so we don't risk
21913        // the system server being killed due to open FDs
21914        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21915
21916        for (int i = 0; i < 3; i++) {
21917            System.gc();
21918            System.runFinalization();
21919        }
21920    }
21921
21922    private void assertPackageKnown(String volumeUuid, String packageName)
21923            throws PackageManagerException {
21924        synchronized (mPackages) {
21925            // Normalize package name to handle renamed packages
21926            packageName = normalizePackageNameLPr(packageName);
21927
21928            final PackageSetting ps = mSettings.mPackages.get(packageName);
21929            if (ps == null) {
21930                throw new PackageManagerException("Package " + packageName + " is unknown");
21931            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21932                throw new PackageManagerException(
21933                        "Package " + packageName + " found on unknown volume " + volumeUuid
21934                                + "; expected volume " + ps.volumeUuid);
21935            }
21936        }
21937    }
21938
21939    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21940            throws PackageManagerException {
21941        synchronized (mPackages) {
21942            // Normalize package name to handle renamed packages
21943            packageName = normalizePackageNameLPr(packageName);
21944
21945            final PackageSetting ps = mSettings.mPackages.get(packageName);
21946            if (ps == null) {
21947                throw new PackageManagerException("Package " + packageName + " is unknown");
21948            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21949                throw new PackageManagerException(
21950                        "Package " + packageName + " found on unknown volume " + volumeUuid
21951                                + "; expected volume " + ps.volumeUuid);
21952            } else if (!ps.getInstalled(userId)) {
21953                throw new PackageManagerException(
21954                        "Package " + packageName + " not installed for user " + userId);
21955            }
21956        }
21957    }
21958
21959    private List<String> collectAbsoluteCodePaths() {
21960        synchronized (mPackages) {
21961            List<String> codePaths = new ArrayList<>();
21962            final int packageCount = mSettings.mPackages.size();
21963            for (int i = 0; i < packageCount; i++) {
21964                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21965                codePaths.add(ps.codePath.getAbsolutePath());
21966            }
21967            return codePaths;
21968        }
21969    }
21970
21971    /**
21972     * Examine all apps present on given mounted volume, and destroy apps that
21973     * aren't expected, either due to uninstallation or reinstallation on
21974     * another volume.
21975     */
21976    private void reconcileApps(String volumeUuid) {
21977        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21978        List<File> filesToDelete = null;
21979
21980        final File[] files = FileUtils.listFilesOrEmpty(
21981                Environment.getDataAppDirectory(volumeUuid));
21982        for (File file : files) {
21983            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21984                    && !PackageInstallerService.isStageName(file.getName());
21985            if (!isPackage) {
21986                // Ignore entries which are not packages
21987                continue;
21988            }
21989
21990            String absolutePath = file.getAbsolutePath();
21991
21992            boolean pathValid = false;
21993            final int absoluteCodePathCount = absoluteCodePaths.size();
21994            for (int i = 0; i < absoluteCodePathCount; i++) {
21995                String absoluteCodePath = absoluteCodePaths.get(i);
21996                if (absolutePath.startsWith(absoluteCodePath)) {
21997                    pathValid = true;
21998                    break;
21999                }
22000            }
22001
22002            if (!pathValid) {
22003                if (filesToDelete == null) {
22004                    filesToDelete = new ArrayList<>();
22005                }
22006                filesToDelete.add(file);
22007            }
22008        }
22009
22010        if (filesToDelete != null) {
22011            final int fileToDeleteCount = filesToDelete.size();
22012            for (int i = 0; i < fileToDeleteCount; i++) {
22013                File fileToDelete = filesToDelete.get(i);
22014                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22015                synchronized (mInstallLock) {
22016                    removeCodePathLI(fileToDelete);
22017                }
22018            }
22019        }
22020    }
22021
22022    /**
22023     * Reconcile all app data for the given user.
22024     * <p>
22025     * Verifies that directories exist and that ownership and labeling is
22026     * correct for all installed apps on all mounted volumes.
22027     */
22028    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22029        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22030        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22031            final String volumeUuid = vol.getFsUuid();
22032            synchronized (mInstallLock) {
22033                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22034            }
22035        }
22036    }
22037
22038    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22039            boolean migrateAppData) {
22040        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22041    }
22042
22043    /**
22044     * Reconcile all app data on given mounted volume.
22045     * <p>
22046     * Destroys app data that isn't expected, either due to uninstallation or
22047     * reinstallation on another volume.
22048     * <p>
22049     * Verifies that directories exist and that ownership and labeling is
22050     * correct for all installed apps.
22051     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22052     */
22053    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22054            boolean migrateAppData, boolean onlyCoreApps) {
22055        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22056                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22057        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22058
22059        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22060        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22061
22062        // First look for stale data that doesn't belong, and check if things
22063        // have changed since we did our last restorecon
22064        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22065            if (StorageManager.isFileEncryptedNativeOrEmulated()
22066                    && !StorageManager.isUserKeyUnlocked(userId)) {
22067                throw new RuntimeException(
22068                        "Yikes, someone asked us to reconcile CE storage while " + userId
22069                                + " was still locked; this would have caused massive data loss!");
22070            }
22071
22072            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22073            for (File file : files) {
22074                final String packageName = file.getName();
22075                try {
22076                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22077                } catch (PackageManagerException e) {
22078                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22079                    try {
22080                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22081                                StorageManager.FLAG_STORAGE_CE, 0);
22082                    } catch (InstallerException e2) {
22083                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22084                    }
22085                }
22086            }
22087        }
22088        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22089            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22090            for (File file : files) {
22091                final String packageName = file.getName();
22092                try {
22093                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22094                } catch (PackageManagerException e) {
22095                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22096                    try {
22097                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22098                                StorageManager.FLAG_STORAGE_DE, 0);
22099                    } catch (InstallerException e2) {
22100                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22101                    }
22102                }
22103            }
22104        }
22105
22106        // Ensure that data directories are ready to roll for all packages
22107        // installed for this volume and user
22108        final List<PackageSetting> packages;
22109        synchronized (mPackages) {
22110            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22111        }
22112        int preparedCount = 0;
22113        for (PackageSetting ps : packages) {
22114            final String packageName = ps.name;
22115            if (ps.pkg == null) {
22116                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22117                // TODO: might be due to legacy ASEC apps; we should circle back
22118                // and reconcile again once they're scanned
22119                continue;
22120            }
22121            // Skip non-core apps if requested
22122            if (onlyCoreApps && !ps.pkg.coreApp) {
22123                result.add(packageName);
22124                continue;
22125            }
22126
22127            if (ps.getInstalled(userId)) {
22128                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22129                preparedCount++;
22130            }
22131        }
22132
22133        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22134        return result;
22135    }
22136
22137    /**
22138     * Prepare app data for the given app just after it was installed or
22139     * upgraded. This method carefully only touches users that it's installed
22140     * for, and it forces a restorecon to handle any seinfo changes.
22141     * <p>
22142     * Verifies that directories exist and that ownership and labeling is
22143     * correct for all installed apps. If there is an ownership mismatch, it
22144     * will try recovering system apps by wiping data; third-party app data is
22145     * left intact.
22146     * <p>
22147     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22148     */
22149    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22150        final PackageSetting ps;
22151        synchronized (mPackages) {
22152            ps = mSettings.mPackages.get(pkg.packageName);
22153            mSettings.writeKernelMappingLPr(ps);
22154        }
22155
22156        final UserManager um = mContext.getSystemService(UserManager.class);
22157        UserManagerInternal umInternal = getUserManagerInternal();
22158        for (UserInfo user : um.getUsers()) {
22159            final int flags;
22160            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22161                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22162            } else if (umInternal.isUserRunning(user.id)) {
22163                flags = StorageManager.FLAG_STORAGE_DE;
22164            } else {
22165                continue;
22166            }
22167
22168            if (ps.getInstalled(user.id)) {
22169                // TODO: when user data is locked, mark that we're still dirty
22170                prepareAppDataLIF(pkg, user.id, flags);
22171            }
22172        }
22173    }
22174
22175    /**
22176     * Prepare app data for the given app.
22177     * <p>
22178     * Verifies that directories exist and that ownership and labeling is
22179     * correct for all installed apps. If there is an ownership mismatch, this
22180     * will try recovering system apps by wiping data; third-party app data is
22181     * left intact.
22182     */
22183    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22184        if (pkg == null) {
22185            Slog.wtf(TAG, "Package was null!", new Throwable());
22186            return;
22187        }
22188        prepareAppDataLeafLIF(pkg, userId, flags);
22189        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22190        for (int i = 0; i < childCount; i++) {
22191            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22192        }
22193    }
22194
22195    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22196            boolean maybeMigrateAppData) {
22197        prepareAppDataLIF(pkg, userId, flags);
22198
22199        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22200            // We may have just shuffled around app data directories, so
22201            // prepare them one more time
22202            prepareAppDataLIF(pkg, userId, flags);
22203        }
22204    }
22205
22206    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22207        if (DEBUG_APP_DATA) {
22208            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22209                    + Integer.toHexString(flags));
22210        }
22211
22212        final String volumeUuid = pkg.volumeUuid;
22213        final String packageName = pkg.packageName;
22214        final ApplicationInfo app = pkg.applicationInfo;
22215        final int appId = UserHandle.getAppId(app.uid);
22216
22217        Preconditions.checkNotNull(app.seInfo);
22218
22219        long ceDataInode = -1;
22220        try {
22221            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22222                    appId, app.seInfo, app.targetSdkVersion);
22223        } catch (InstallerException e) {
22224            if (app.isSystemApp()) {
22225                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22226                        + ", but trying to recover: " + e);
22227                destroyAppDataLeafLIF(pkg, userId, flags);
22228                try {
22229                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22230                            appId, app.seInfo, app.targetSdkVersion);
22231                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22232                } catch (InstallerException e2) {
22233                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22234                }
22235            } else {
22236                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22237            }
22238        }
22239        // Prepare the application profiles.
22240        mArtManagerService.prepareAppProfiles(pkg, userId);
22241
22242        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22243            // TODO: mark this structure as dirty so we persist it!
22244            synchronized (mPackages) {
22245                final PackageSetting ps = mSettings.mPackages.get(packageName);
22246                if (ps != null) {
22247                    ps.setCeDataInode(ceDataInode, userId);
22248                }
22249            }
22250        }
22251
22252        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22253    }
22254
22255    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22256        if (pkg == null) {
22257            Slog.wtf(TAG, "Package was null!", new Throwable());
22258            return;
22259        }
22260        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22261        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22262        for (int i = 0; i < childCount; i++) {
22263            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22264        }
22265    }
22266
22267    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22268        final String volumeUuid = pkg.volumeUuid;
22269        final String packageName = pkg.packageName;
22270        final ApplicationInfo app = pkg.applicationInfo;
22271
22272        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22273            // Create a native library symlink only if we have native libraries
22274            // and if the native libraries are 32 bit libraries. We do not provide
22275            // this symlink for 64 bit libraries.
22276            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22277                final String nativeLibPath = app.nativeLibraryDir;
22278                try {
22279                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22280                            nativeLibPath, userId);
22281                } catch (InstallerException e) {
22282                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22283                }
22284            }
22285        }
22286    }
22287
22288    /**
22289     * For system apps on non-FBE devices, this method migrates any existing
22290     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22291     * requested by the app.
22292     */
22293    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22294        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22295                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22296            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22297                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22298            try {
22299                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22300                        storageTarget);
22301            } catch (InstallerException e) {
22302                logCriticalInfo(Log.WARN,
22303                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22304            }
22305            return true;
22306        } else {
22307            return false;
22308        }
22309    }
22310
22311    public PackageFreezer freezePackage(String packageName, String killReason) {
22312        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22313    }
22314
22315    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22316        return new PackageFreezer(packageName, userId, killReason);
22317    }
22318
22319    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22320            String killReason) {
22321        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22322    }
22323
22324    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22325            String killReason) {
22326        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22327            return new PackageFreezer();
22328        } else {
22329            return freezePackage(packageName, userId, killReason);
22330        }
22331    }
22332
22333    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22334            String killReason) {
22335        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22336    }
22337
22338    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22339            String killReason) {
22340        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22341            return new PackageFreezer();
22342        } else {
22343            return freezePackage(packageName, userId, killReason);
22344        }
22345    }
22346
22347    /**
22348     * Class that freezes and kills the given package upon creation, and
22349     * unfreezes it upon closing. This is typically used when doing surgery on
22350     * app code/data to prevent the app from running while you're working.
22351     */
22352    private class PackageFreezer implements AutoCloseable {
22353        private final String mPackageName;
22354        private final PackageFreezer[] mChildren;
22355
22356        private final boolean mWeFroze;
22357
22358        private final AtomicBoolean mClosed = new AtomicBoolean();
22359        private final CloseGuard mCloseGuard = CloseGuard.get();
22360
22361        /**
22362         * Create and return a stub freezer that doesn't actually do anything,
22363         * typically used when someone requested
22364         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22365         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22366         */
22367        public PackageFreezer() {
22368            mPackageName = null;
22369            mChildren = null;
22370            mWeFroze = false;
22371            mCloseGuard.open("close");
22372        }
22373
22374        public PackageFreezer(String packageName, int userId, String killReason) {
22375            synchronized (mPackages) {
22376                mPackageName = packageName;
22377                mWeFroze = mFrozenPackages.add(mPackageName);
22378
22379                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22380                if (ps != null) {
22381                    killApplication(ps.name, ps.appId, userId, killReason);
22382                }
22383
22384                final PackageParser.Package p = mPackages.get(packageName);
22385                if (p != null && p.childPackages != null) {
22386                    final int N = p.childPackages.size();
22387                    mChildren = new PackageFreezer[N];
22388                    for (int i = 0; i < N; i++) {
22389                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22390                                userId, killReason);
22391                    }
22392                } else {
22393                    mChildren = null;
22394                }
22395            }
22396            mCloseGuard.open("close");
22397        }
22398
22399        @Override
22400        protected void finalize() throws Throwable {
22401            try {
22402                if (mCloseGuard != null) {
22403                    mCloseGuard.warnIfOpen();
22404                }
22405
22406                close();
22407            } finally {
22408                super.finalize();
22409            }
22410        }
22411
22412        @Override
22413        public void close() {
22414            mCloseGuard.close();
22415            if (mClosed.compareAndSet(false, true)) {
22416                synchronized (mPackages) {
22417                    if (mWeFroze) {
22418                        mFrozenPackages.remove(mPackageName);
22419                    }
22420
22421                    if (mChildren != null) {
22422                        for (PackageFreezer freezer : mChildren) {
22423                            freezer.close();
22424                        }
22425                    }
22426                }
22427            }
22428        }
22429    }
22430
22431    /**
22432     * Verify that given package is currently frozen.
22433     */
22434    private void checkPackageFrozen(String packageName) {
22435        synchronized (mPackages) {
22436            if (!mFrozenPackages.contains(packageName)) {
22437                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22438            }
22439        }
22440    }
22441
22442    @Override
22443    public int movePackage(final String packageName, final String volumeUuid) {
22444        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22445
22446        final int callingUid = Binder.getCallingUid();
22447        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22448        final int moveId = mNextMoveId.getAndIncrement();
22449        mHandler.post(new Runnable() {
22450            @Override
22451            public void run() {
22452                try {
22453                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22454                } catch (PackageManagerException e) {
22455                    Slog.w(TAG, "Failed to move " + packageName, e);
22456                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22457                }
22458            }
22459        });
22460        return moveId;
22461    }
22462
22463    private void movePackageInternal(final String packageName, final String volumeUuid,
22464            final int moveId, final int callingUid, UserHandle user)
22465                    throws PackageManagerException {
22466        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22467        final PackageManager pm = mContext.getPackageManager();
22468
22469        final boolean currentAsec;
22470        final String currentVolumeUuid;
22471        final File codeFile;
22472        final String installerPackageName;
22473        final String packageAbiOverride;
22474        final int appId;
22475        final String seinfo;
22476        final String label;
22477        final int targetSdkVersion;
22478        final PackageFreezer freezer;
22479        final int[] installedUserIds;
22480
22481        // reader
22482        synchronized (mPackages) {
22483            final PackageParser.Package pkg = mPackages.get(packageName);
22484            final PackageSetting ps = mSettings.mPackages.get(packageName);
22485            if (pkg == null
22486                    || ps == null
22487                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22488                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22489            }
22490            if (pkg.applicationInfo.isSystemApp()) {
22491                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22492                        "Cannot move system application");
22493            }
22494
22495            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22496            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22497                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22498            if (isInternalStorage && !allow3rdPartyOnInternal) {
22499                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22500                        "3rd party apps are not allowed on internal storage");
22501            }
22502
22503            if (pkg.applicationInfo.isExternalAsec()) {
22504                currentAsec = true;
22505                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22506            } else if (pkg.applicationInfo.isForwardLocked()) {
22507                currentAsec = true;
22508                currentVolumeUuid = "forward_locked";
22509            } else {
22510                currentAsec = false;
22511                currentVolumeUuid = ps.volumeUuid;
22512
22513                final File probe = new File(pkg.codePath);
22514                final File probeOat = new File(probe, "oat");
22515                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22516                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22517                            "Move only supported for modern cluster style installs");
22518                }
22519            }
22520
22521            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22522                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22523                        "Package already moved to " + volumeUuid);
22524            }
22525            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22526                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22527                        "Device admin cannot be moved");
22528            }
22529
22530            if (mFrozenPackages.contains(packageName)) {
22531                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22532                        "Failed to move already frozen package");
22533            }
22534
22535            codeFile = new File(pkg.codePath);
22536            installerPackageName = ps.installerPackageName;
22537            packageAbiOverride = ps.cpuAbiOverrideString;
22538            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22539            seinfo = pkg.applicationInfo.seInfo;
22540            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22541            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22542            freezer = freezePackage(packageName, "movePackageInternal");
22543            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22544        }
22545
22546        final Bundle extras = new Bundle();
22547        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22548        extras.putString(Intent.EXTRA_TITLE, label);
22549        mMoveCallbacks.notifyCreated(moveId, extras);
22550
22551        int installFlags;
22552        final boolean moveCompleteApp;
22553        final File measurePath;
22554
22555        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22556            installFlags = INSTALL_INTERNAL;
22557            moveCompleteApp = !currentAsec;
22558            measurePath = Environment.getDataAppDirectory(volumeUuid);
22559        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22560            installFlags = INSTALL_EXTERNAL;
22561            moveCompleteApp = false;
22562            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22563        } else {
22564            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22565            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22566                    || !volume.isMountedWritable()) {
22567                freezer.close();
22568                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22569                        "Move location not mounted private volume");
22570            }
22571
22572            Preconditions.checkState(!currentAsec);
22573
22574            installFlags = INSTALL_INTERNAL;
22575            moveCompleteApp = true;
22576            measurePath = Environment.getDataAppDirectory(volumeUuid);
22577        }
22578
22579        // If we're moving app data around, we need all the users unlocked
22580        if (moveCompleteApp) {
22581            for (int userId : installedUserIds) {
22582                if (StorageManager.isFileEncryptedNativeOrEmulated()
22583                        && !StorageManager.isUserKeyUnlocked(userId)) {
22584                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22585                            "User " + userId + " must be unlocked");
22586                }
22587            }
22588        }
22589
22590        final PackageStats stats = new PackageStats(null, -1);
22591        synchronized (mInstaller) {
22592            for (int userId : installedUserIds) {
22593                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22594                    freezer.close();
22595                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22596                            "Failed to measure package size");
22597                }
22598            }
22599        }
22600
22601        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22602                + stats.dataSize);
22603
22604        final long startFreeBytes = measurePath.getUsableSpace();
22605        final long sizeBytes;
22606        if (moveCompleteApp) {
22607            sizeBytes = stats.codeSize + stats.dataSize;
22608        } else {
22609            sizeBytes = stats.codeSize;
22610        }
22611
22612        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22613            freezer.close();
22614            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22615                    "Not enough free space to move");
22616        }
22617
22618        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22619
22620        final CountDownLatch installedLatch = new CountDownLatch(1);
22621        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22622            @Override
22623            public void onUserActionRequired(Intent intent) throws RemoteException {
22624                throw new IllegalStateException();
22625            }
22626
22627            @Override
22628            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22629                    Bundle extras) throws RemoteException {
22630                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22631                        + PackageManager.installStatusToString(returnCode, msg));
22632
22633                installedLatch.countDown();
22634                freezer.close();
22635
22636                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22637                switch (status) {
22638                    case PackageInstaller.STATUS_SUCCESS:
22639                        mMoveCallbacks.notifyStatusChanged(moveId,
22640                                PackageManager.MOVE_SUCCEEDED);
22641                        break;
22642                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22643                        mMoveCallbacks.notifyStatusChanged(moveId,
22644                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22645                        break;
22646                    default:
22647                        mMoveCallbacks.notifyStatusChanged(moveId,
22648                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22649                        break;
22650                }
22651            }
22652        };
22653
22654        final MoveInfo move;
22655        if (moveCompleteApp) {
22656            // Kick off a thread to report progress estimates
22657            new Thread() {
22658                @Override
22659                public void run() {
22660                    while (true) {
22661                        try {
22662                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22663                                break;
22664                            }
22665                        } catch (InterruptedException ignored) {
22666                        }
22667
22668                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22669                        final int progress = 10 + (int) MathUtils.constrain(
22670                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22671                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22672                    }
22673                }
22674            }.start();
22675
22676            final String dataAppName = codeFile.getName();
22677            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22678                    dataAppName, appId, seinfo, targetSdkVersion);
22679        } else {
22680            move = null;
22681        }
22682
22683        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22684
22685        final Message msg = mHandler.obtainMessage(INIT_COPY);
22686        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22687        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22688                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22689                packageAbiOverride, null /*grantedPermissions*/,
22690                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22691        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22692        msg.obj = params;
22693
22694        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22695                System.identityHashCode(msg.obj));
22696        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22697                System.identityHashCode(msg.obj));
22698
22699        mHandler.sendMessage(msg);
22700    }
22701
22702    @Override
22703    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22704        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22705
22706        final int realMoveId = mNextMoveId.getAndIncrement();
22707        final Bundle extras = new Bundle();
22708        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22709        mMoveCallbacks.notifyCreated(realMoveId, extras);
22710
22711        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22712            @Override
22713            public void onCreated(int moveId, Bundle extras) {
22714                // Ignored
22715            }
22716
22717            @Override
22718            public void onStatusChanged(int moveId, int status, long estMillis) {
22719                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22720            }
22721        };
22722
22723        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22724        storage.setPrimaryStorageUuid(volumeUuid, callback);
22725        return realMoveId;
22726    }
22727
22728    @Override
22729    public int getMoveStatus(int moveId) {
22730        mContext.enforceCallingOrSelfPermission(
22731                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22732        return mMoveCallbacks.mLastStatus.get(moveId);
22733    }
22734
22735    @Override
22736    public void registerMoveCallback(IPackageMoveObserver callback) {
22737        mContext.enforceCallingOrSelfPermission(
22738                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22739        mMoveCallbacks.register(callback);
22740    }
22741
22742    @Override
22743    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22744        mContext.enforceCallingOrSelfPermission(
22745                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22746        mMoveCallbacks.unregister(callback);
22747    }
22748
22749    @Override
22750    public boolean setInstallLocation(int loc) {
22751        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22752                null);
22753        if (getInstallLocation() == loc) {
22754            return true;
22755        }
22756        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22757                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22758            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22759                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22760            return true;
22761        }
22762        return false;
22763   }
22764
22765    @Override
22766    public int getInstallLocation() {
22767        // allow instant app access
22768        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22769                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22770                PackageHelper.APP_INSTALL_AUTO);
22771    }
22772
22773    /** Called by UserManagerService */
22774    void cleanUpUser(UserManagerService userManager, int userHandle) {
22775        synchronized (mPackages) {
22776            mDirtyUsers.remove(userHandle);
22777            mUserNeedsBadging.delete(userHandle);
22778            mSettings.removeUserLPw(userHandle);
22779            mPendingBroadcasts.remove(userHandle);
22780            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22781            removeUnusedPackagesLPw(userManager, userHandle);
22782        }
22783    }
22784
22785    /**
22786     * We're removing userHandle and would like to remove any downloaded packages
22787     * that are no longer in use by any other user.
22788     * @param userHandle the user being removed
22789     */
22790    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22791        final boolean DEBUG_CLEAN_APKS = false;
22792        int [] users = userManager.getUserIds();
22793        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22794        while (psit.hasNext()) {
22795            PackageSetting ps = psit.next();
22796            if (ps.pkg == null) {
22797                continue;
22798            }
22799            final String packageName = ps.pkg.packageName;
22800            // Skip over if system app
22801            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22802                continue;
22803            }
22804            if (DEBUG_CLEAN_APKS) {
22805                Slog.i(TAG, "Checking package " + packageName);
22806            }
22807            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22808            if (keep) {
22809                if (DEBUG_CLEAN_APKS) {
22810                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22811                }
22812            } else {
22813                for (int i = 0; i < users.length; i++) {
22814                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22815                        keep = true;
22816                        if (DEBUG_CLEAN_APKS) {
22817                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22818                                    + users[i]);
22819                        }
22820                        break;
22821                    }
22822                }
22823            }
22824            if (!keep) {
22825                if (DEBUG_CLEAN_APKS) {
22826                    Slog.i(TAG, "  Removing package " + packageName);
22827                }
22828                mHandler.post(new Runnable() {
22829                    public void run() {
22830                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22831                                userHandle, 0);
22832                    } //end run
22833                });
22834            }
22835        }
22836    }
22837
22838    /** Called by UserManagerService */
22839    void createNewUser(int userId, String[] disallowedPackages) {
22840        synchronized (mInstallLock) {
22841            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22842        }
22843        synchronized (mPackages) {
22844            scheduleWritePackageRestrictionsLocked(userId);
22845            scheduleWritePackageListLocked(userId);
22846            applyFactoryDefaultBrowserLPw(userId);
22847            primeDomainVerificationsLPw(userId);
22848        }
22849    }
22850
22851    void onNewUserCreated(final int userId) {
22852        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22853        synchronized(mPackages) {
22854            // If permission review for legacy apps is required, we represent
22855            // dagerous permissions for such apps as always granted runtime
22856            // permissions to keep per user flag state whether review is needed.
22857            // Hence, if a new user is added we have to propagate dangerous
22858            // permission grants for these legacy apps.
22859            if (mSettings.mPermissions.mPermissionReviewRequired) {
22860// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
22861                mPermissionManager.updateAllPermissions(
22862                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
22863                        mPermissionCallback);
22864            }
22865        }
22866    }
22867
22868    @Override
22869    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22870        mContext.enforceCallingOrSelfPermission(
22871                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22872                "Only package verification agents can read the verifier device identity");
22873
22874        synchronized (mPackages) {
22875            return mSettings.getVerifierDeviceIdentityLPw();
22876        }
22877    }
22878
22879    @Override
22880    public void setPermissionEnforced(String permission, boolean enforced) {
22881        // TODO: Now that we no longer change GID for storage, this should to away.
22882        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22883                "setPermissionEnforced");
22884        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22885            synchronized (mPackages) {
22886                if (mSettings.mReadExternalStorageEnforced == null
22887                        || mSettings.mReadExternalStorageEnforced != enforced) {
22888                    mSettings.mReadExternalStorageEnforced =
22889                            enforced ? Boolean.TRUE : Boolean.FALSE;
22890                    mSettings.writeLPr();
22891                }
22892            }
22893            // kill any non-foreground processes so we restart them and
22894            // grant/revoke the GID.
22895            final IActivityManager am = ActivityManager.getService();
22896            if (am != null) {
22897                final long token = Binder.clearCallingIdentity();
22898                try {
22899                    am.killProcessesBelowForeground("setPermissionEnforcement");
22900                } catch (RemoteException e) {
22901                } finally {
22902                    Binder.restoreCallingIdentity(token);
22903                }
22904            }
22905        } else {
22906            throw new IllegalArgumentException("No selective enforcement for " + permission);
22907        }
22908    }
22909
22910    @Override
22911    @Deprecated
22912    public boolean isPermissionEnforced(String permission) {
22913        // allow instant applications
22914        return true;
22915    }
22916
22917    @Override
22918    public boolean isStorageLow() {
22919        // allow instant applications
22920        final long token = Binder.clearCallingIdentity();
22921        try {
22922            final DeviceStorageMonitorInternal
22923                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22924            if (dsm != null) {
22925                return dsm.isMemoryLow();
22926            } else {
22927                return false;
22928            }
22929        } finally {
22930            Binder.restoreCallingIdentity(token);
22931        }
22932    }
22933
22934    @Override
22935    public IPackageInstaller getPackageInstaller() {
22936        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22937            return null;
22938        }
22939        return mInstallerService;
22940    }
22941
22942    @Override
22943    public IArtManager getArtManager() {
22944        return mArtManagerService;
22945    }
22946
22947    private boolean userNeedsBadging(int userId) {
22948        int index = mUserNeedsBadging.indexOfKey(userId);
22949        if (index < 0) {
22950            final UserInfo userInfo;
22951            final long token = Binder.clearCallingIdentity();
22952            try {
22953                userInfo = sUserManager.getUserInfo(userId);
22954            } finally {
22955                Binder.restoreCallingIdentity(token);
22956            }
22957            final boolean b;
22958            if (userInfo != null && userInfo.isManagedProfile()) {
22959                b = true;
22960            } else {
22961                b = false;
22962            }
22963            mUserNeedsBadging.put(userId, b);
22964            return b;
22965        }
22966        return mUserNeedsBadging.valueAt(index);
22967    }
22968
22969    @Override
22970    public KeySet getKeySetByAlias(String packageName, String alias) {
22971        if (packageName == null || alias == null) {
22972            return null;
22973        }
22974        synchronized(mPackages) {
22975            final PackageParser.Package pkg = mPackages.get(packageName);
22976            if (pkg == null) {
22977                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22978                throw new IllegalArgumentException("Unknown package: " + packageName);
22979            }
22980            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22981            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
22982                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
22983                throw new IllegalArgumentException("Unknown package: " + packageName);
22984            }
22985            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22986            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22987        }
22988    }
22989
22990    @Override
22991    public KeySet getSigningKeySet(String packageName) {
22992        if (packageName == null) {
22993            return null;
22994        }
22995        synchronized(mPackages) {
22996            final int callingUid = Binder.getCallingUid();
22997            final int callingUserId = UserHandle.getUserId(callingUid);
22998            final PackageParser.Package pkg = mPackages.get(packageName);
22999            if (pkg == null) {
23000                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23001                throw new IllegalArgumentException("Unknown package: " + packageName);
23002            }
23003            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23004            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23005                // filter and pretend the package doesn't exist
23006                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23007                        + ", uid:" + callingUid);
23008                throw new IllegalArgumentException("Unknown package: " + packageName);
23009            }
23010            if (pkg.applicationInfo.uid != callingUid
23011                    && Process.SYSTEM_UID != callingUid) {
23012                throw new SecurityException("May not access signing KeySet of other apps.");
23013            }
23014            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23015            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23016        }
23017    }
23018
23019    @Override
23020    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23021        final int callingUid = Binder.getCallingUid();
23022        if (getInstantAppPackageName(callingUid) != null) {
23023            return false;
23024        }
23025        if (packageName == null || ks == null) {
23026            return false;
23027        }
23028        synchronized(mPackages) {
23029            final PackageParser.Package pkg = mPackages.get(packageName);
23030            if (pkg == null
23031                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23032                            UserHandle.getUserId(callingUid))) {
23033                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23034                throw new IllegalArgumentException("Unknown package: " + packageName);
23035            }
23036            IBinder ksh = ks.getToken();
23037            if (ksh instanceof KeySetHandle) {
23038                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23039                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23040            }
23041            return false;
23042        }
23043    }
23044
23045    @Override
23046    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23047        final int callingUid = Binder.getCallingUid();
23048        if (getInstantAppPackageName(callingUid) != null) {
23049            return false;
23050        }
23051        if (packageName == null || ks == null) {
23052            return false;
23053        }
23054        synchronized(mPackages) {
23055            final PackageParser.Package pkg = mPackages.get(packageName);
23056            if (pkg == null
23057                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23058                            UserHandle.getUserId(callingUid))) {
23059                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23060                throw new IllegalArgumentException("Unknown package: " + packageName);
23061            }
23062            IBinder ksh = ks.getToken();
23063            if (ksh instanceof KeySetHandle) {
23064                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23065                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23066            }
23067            return false;
23068        }
23069    }
23070
23071    private void deletePackageIfUnusedLPr(final String packageName) {
23072        PackageSetting ps = mSettings.mPackages.get(packageName);
23073        if (ps == null) {
23074            return;
23075        }
23076        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23077            // TODO Implement atomic delete if package is unused
23078            // It is currently possible that the package will be deleted even if it is installed
23079            // after this method returns.
23080            mHandler.post(new Runnable() {
23081                public void run() {
23082                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23083                            0, PackageManager.DELETE_ALL_USERS);
23084                }
23085            });
23086        }
23087    }
23088
23089    /**
23090     * Check and throw if the given before/after packages would be considered a
23091     * downgrade.
23092     */
23093    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23094            throws PackageManagerException {
23095        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23096            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23097                    "Update version code " + after.versionCode + " is older than current "
23098                    + before.getLongVersionCode());
23099        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23100            if (after.baseRevisionCode < before.baseRevisionCode) {
23101                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23102                        "Update base revision code " + after.baseRevisionCode
23103                        + " is older than current " + before.baseRevisionCode);
23104            }
23105
23106            if (!ArrayUtils.isEmpty(after.splitNames)) {
23107                for (int i = 0; i < after.splitNames.length; i++) {
23108                    final String splitName = after.splitNames[i];
23109                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23110                    if (j != -1) {
23111                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23112                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23113                                    "Update split " + splitName + " revision code "
23114                                    + after.splitRevisionCodes[i] + " is older than current "
23115                                    + before.splitRevisionCodes[j]);
23116                        }
23117                    }
23118                }
23119            }
23120        }
23121    }
23122
23123    private static class MoveCallbacks extends Handler {
23124        private static final int MSG_CREATED = 1;
23125        private static final int MSG_STATUS_CHANGED = 2;
23126
23127        private final RemoteCallbackList<IPackageMoveObserver>
23128                mCallbacks = new RemoteCallbackList<>();
23129
23130        private final SparseIntArray mLastStatus = new SparseIntArray();
23131
23132        public MoveCallbacks(Looper looper) {
23133            super(looper);
23134        }
23135
23136        public void register(IPackageMoveObserver callback) {
23137            mCallbacks.register(callback);
23138        }
23139
23140        public void unregister(IPackageMoveObserver callback) {
23141            mCallbacks.unregister(callback);
23142        }
23143
23144        @Override
23145        public void handleMessage(Message msg) {
23146            final SomeArgs args = (SomeArgs) msg.obj;
23147            final int n = mCallbacks.beginBroadcast();
23148            for (int i = 0; i < n; i++) {
23149                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23150                try {
23151                    invokeCallback(callback, msg.what, args);
23152                } catch (RemoteException ignored) {
23153                }
23154            }
23155            mCallbacks.finishBroadcast();
23156            args.recycle();
23157        }
23158
23159        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23160                throws RemoteException {
23161            switch (what) {
23162                case MSG_CREATED: {
23163                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23164                    break;
23165                }
23166                case MSG_STATUS_CHANGED: {
23167                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23168                    break;
23169                }
23170            }
23171        }
23172
23173        private void notifyCreated(int moveId, Bundle extras) {
23174            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23175
23176            final SomeArgs args = SomeArgs.obtain();
23177            args.argi1 = moveId;
23178            args.arg2 = extras;
23179            obtainMessage(MSG_CREATED, args).sendToTarget();
23180        }
23181
23182        private void notifyStatusChanged(int moveId, int status) {
23183            notifyStatusChanged(moveId, status, -1);
23184        }
23185
23186        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23187            Slog.v(TAG, "Move " + moveId + " status " + status);
23188
23189            final SomeArgs args = SomeArgs.obtain();
23190            args.argi1 = moveId;
23191            args.argi2 = status;
23192            args.arg3 = estMillis;
23193            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23194
23195            synchronized (mLastStatus) {
23196                mLastStatus.put(moveId, status);
23197            }
23198        }
23199    }
23200
23201    private final static class OnPermissionChangeListeners extends Handler {
23202        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23203
23204        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23205                new RemoteCallbackList<>();
23206
23207        public OnPermissionChangeListeners(Looper looper) {
23208            super(looper);
23209        }
23210
23211        @Override
23212        public void handleMessage(Message msg) {
23213            switch (msg.what) {
23214                case MSG_ON_PERMISSIONS_CHANGED: {
23215                    final int uid = msg.arg1;
23216                    handleOnPermissionsChanged(uid);
23217                } break;
23218            }
23219        }
23220
23221        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23222            mPermissionListeners.register(listener);
23223
23224        }
23225
23226        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23227            mPermissionListeners.unregister(listener);
23228        }
23229
23230        public void onPermissionsChanged(int uid) {
23231            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23232                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23233            }
23234        }
23235
23236        private void handleOnPermissionsChanged(int uid) {
23237            final int count = mPermissionListeners.beginBroadcast();
23238            try {
23239                for (int i = 0; i < count; i++) {
23240                    IOnPermissionsChangeListener callback = mPermissionListeners
23241                            .getBroadcastItem(i);
23242                    try {
23243                        callback.onPermissionsChanged(uid);
23244                    } catch (RemoteException e) {
23245                        Log.e(TAG, "Permission listener is dead", e);
23246                    }
23247                }
23248            } finally {
23249                mPermissionListeners.finishBroadcast();
23250            }
23251        }
23252    }
23253
23254    private class PackageManagerNative extends IPackageManagerNative.Stub {
23255        @Override
23256        public String[] getNamesForUids(int[] uids) throws RemoteException {
23257            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23258            // massage results so they can be parsed by the native binder
23259            for (int i = results.length - 1; i >= 0; --i) {
23260                if (results[i] == null) {
23261                    results[i] = "";
23262                }
23263            }
23264            return results;
23265        }
23266
23267        // NB: this differentiates between preloads and sideloads
23268        @Override
23269        public String getInstallerForPackage(String packageName) throws RemoteException {
23270            final String installerName = getInstallerPackageName(packageName);
23271            if (!TextUtils.isEmpty(installerName)) {
23272                return installerName;
23273            }
23274            // differentiate between preload and sideload
23275            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23276            ApplicationInfo appInfo = getApplicationInfo(packageName,
23277                                    /*flags*/ 0,
23278                                    /*userId*/ callingUser);
23279            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23280                return "preload";
23281            }
23282            return "";
23283        }
23284
23285        @Override
23286        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23287            try {
23288                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23289                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23290                if (pInfo != null) {
23291                    return pInfo.getLongVersionCode();
23292                }
23293            } catch (Exception e) {
23294            }
23295            return 0;
23296        }
23297    }
23298
23299    private class PackageManagerInternalImpl extends PackageManagerInternal {
23300        @Override
23301        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23302                int flagValues, int userId) {
23303            PackageManagerService.this.updatePermissionFlags(
23304                    permName, packageName, flagMask, flagValues, userId);
23305        }
23306
23307        @Override
23308        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23309            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23310        }
23311
23312        @Override
23313        public boolean isInstantApp(String packageName, int userId) {
23314            return PackageManagerService.this.isInstantApp(packageName, userId);
23315        }
23316
23317        @Override
23318        public String getInstantAppPackageName(int uid) {
23319            return PackageManagerService.this.getInstantAppPackageName(uid);
23320        }
23321
23322        @Override
23323        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23324            synchronized (mPackages) {
23325                return PackageManagerService.this.filterAppAccessLPr(
23326                        (PackageSetting) pkg.mExtras, callingUid, userId);
23327            }
23328        }
23329
23330        @Override
23331        public PackageParser.Package getPackage(String packageName) {
23332            synchronized (mPackages) {
23333                packageName = resolveInternalPackageNameLPr(
23334                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23335                return mPackages.get(packageName);
23336            }
23337        }
23338
23339        @Override
23340        public PackageList getPackageList(PackageListObserver observer) {
23341            synchronized (mPackages) {
23342                final int N = mPackages.size();
23343                final ArrayList<String> list = new ArrayList<>(N);
23344                for (int i = 0; i < N; i++) {
23345                    list.add(mPackages.keyAt(i));
23346                }
23347                final PackageList packageList = new PackageList(list, observer);
23348                if (observer != null) {
23349                    mPackageListObservers.add(packageList);
23350                }
23351                return packageList;
23352            }
23353        }
23354
23355        @Override
23356        public void removePackageListObserver(PackageListObserver observer) {
23357            synchronized (mPackages) {
23358                mPackageListObservers.remove(observer);
23359            }
23360        }
23361
23362        @Override
23363        public PackageParser.Package getDisabledPackage(String packageName) {
23364            synchronized (mPackages) {
23365                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23366                return (ps != null) ? ps.pkg : null;
23367            }
23368        }
23369
23370        @Override
23371        public String getKnownPackageName(int knownPackage, int userId) {
23372            switch(knownPackage) {
23373                case PackageManagerInternal.PACKAGE_BROWSER:
23374                    return getDefaultBrowserPackageName(userId);
23375                case PackageManagerInternal.PACKAGE_INSTALLER:
23376                    return mRequiredInstallerPackage;
23377                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23378                    return mSetupWizardPackage;
23379                case PackageManagerInternal.PACKAGE_SYSTEM:
23380                    return "android";
23381                case PackageManagerInternal.PACKAGE_VERIFIER:
23382                    return mRequiredVerifierPackage;
23383            }
23384            return null;
23385        }
23386
23387        @Override
23388        public boolean isResolveActivityComponent(ComponentInfo component) {
23389            return mResolveActivity.packageName.equals(component.packageName)
23390                    && mResolveActivity.name.equals(component.name);
23391        }
23392
23393        @Override
23394        public void setLocationPackagesProvider(PackagesProvider provider) {
23395            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23396        }
23397
23398        @Override
23399        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23400            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23401        }
23402
23403        @Override
23404        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23405            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23406        }
23407
23408        @Override
23409        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23410            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23411        }
23412
23413        @Override
23414        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23415            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23416        }
23417
23418        @Override
23419        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23420            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23421        }
23422
23423        @Override
23424        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23425            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23426        }
23427
23428        @Override
23429        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23430            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23431        }
23432
23433        @Override
23434        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23435            synchronized (mPackages) {
23436                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23437            }
23438            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23439        }
23440
23441        @Override
23442        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23443            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23444                    packageName, userId);
23445        }
23446
23447        @Override
23448        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23449            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23450                    packageName, userId);
23451        }
23452
23453        @Override
23454        public void setKeepUninstalledPackages(final List<String> packageList) {
23455            Preconditions.checkNotNull(packageList);
23456            List<String> removedFromList = null;
23457            synchronized (mPackages) {
23458                if (mKeepUninstalledPackages != null) {
23459                    final int packagesCount = mKeepUninstalledPackages.size();
23460                    for (int i = 0; i < packagesCount; i++) {
23461                        String oldPackage = mKeepUninstalledPackages.get(i);
23462                        if (packageList != null && packageList.contains(oldPackage)) {
23463                            continue;
23464                        }
23465                        if (removedFromList == null) {
23466                            removedFromList = new ArrayList<>();
23467                        }
23468                        removedFromList.add(oldPackage);
23469                    }
23470                }
23471                mKeepUninstalledPackages = new ArrayList<>(packageList);
23472                if (removedFromList != null) {
23473                    final int removedCount = removedFromList.size();
23474                    for (int i = 0; i < removedCount; i++) {
23475                        deletePackageIfUnusedLPr(removedFromList.get(i));
23476                    }
23477                }
23478            }
23479        }
23480
23481        @Override
23482        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23483            synchronized (mPackages) {
23484                return mPermissionManager.isPermissionsReviewRequired(
23485                        mPackages.get(packageName), userId);
23486            }
23487        }
23488
23489        @Override
23490        public PackageInfo getPackageInfo(
23491                String packageName, int flags, int filterCallingUid, int userId) {
23492            return PackageManagerService.this
23493                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23494                            flags, filterCallingUid, userId);
23495        }
23496
23497        @Override
23498        public int getPackageUid(String packageName, int flags, int userId) {
23499            return PackageManagerService.this
23500                    .getPackageUid(packageName, flags, userId);
23501        }
23502
23503        @Override
23504        public ApplicationInfo getApplicationInfo(
23505                String packageName, int flags, int filterCallingUid, int userId) {
23506            return PackageManagerService.this
23507                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23508        }
23509
23510        @Override
23511        public ActivityInfo getActivityInfo(
23512                ComponentName component, int flags, int filterCallingUid, int userId) {
23513            return PackageManagerService.this
23514                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23515        }
23516
23517        @Override
23518        public List<ResolveInfo> queryIntentActivities(
23519                Intent intent, int flags, int filterCallingUid, int userId) {
23520            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23521            return PackageManagerService.this
23522                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23523                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23524        }
23525
23526        @Override
23527        public List<ResolveInfo> queryIntentServices(
23528                Intent intent, int flags, int callingUid, int userId) {
23529            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23530            return PackageManagerService.this
23531                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23532                            false);
23533        }
23534
23535        @Override
23536        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23537                int userId) {
23538            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23539        }
23540
23541        @Override
23542        public void setDeviceAndProfileOwnerPackages(
23543                int deviceOwnerUserId, String deviceOwnerPackage,
23544                SparseArray<String> profileOwnerPackages) {
23545            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23546                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23547        }
23548
23549        @Override
23550        public boolean isPackageDataProtected(int userId, String packageName) {
23551            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23552        }
23553
23554        @Override
23555        public boolean isPackageEphemeral(int userId, String packageName) {
23556            synchronized (mPackages) {
23557                final PackageSetting ps = mSettings.mPackages.get(packageName);
23558                return ps != null ? ps.getInstantApp(userId) : false;
23559            }
23560        }
23561
23562        @Override
23563        public boolean wasPackageEverLaunched(String packageName, int userId) {
23564            synchronized (mPackages) {
23565                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23566            }
23567        }
23568
23569        @Override
23570        public void grantRuntimePermission(String packageName, String permName, int userId,
23571                boolean overridePolicy) {
23572            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23573                    permName, packageName, overridePolicy, getCallingUid(), userId,
23574                    mPermissionCallback);
23575        }
23576
23577        @Override
23578        public void revokeRuntimePermission(String packageName, String permName, int userId,
23579                boolean overridePolicy) {
23580            mPermissionManager.revokeRuntimePermission(
23581                    permName, packageName, overridePolicy, getCallingUid(), userId,
23582                    mPermissionCallback);
23583        }
23584
23585        @Override
23586        public String getNameForUid(int uid) {
23587            return PackageManagerService.this.getNameForUid(uid);
23588        }
23589
23590        @Override
23591        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23592                Intent origIntent, String resolvedType, String callingPackage,
23593                Bundle verificationBundle, int userId) {
23594            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23595                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23596                    userId);
23597        }
23598
23599        @Override
23600        public void grantEphemeralAccess(int userId, Intent intent,
23601                int targetAppId, int ephemeralAppId) {
23602            synchronized (mPackages) {
23603                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23604                        targetAppId, ephemeralAppId);
23605            }
23606        }
23607
23608        @Override
23609        public boolean isInstantAppInstallerComponent(ComponentName component) {
23610            synchronized (mPackages) {
23611                return mInstantAppInstallerActivity != null
23612                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23613            }
23614        }
23615
23616        @Override
23617        public void pruneInstantApps() {
23618            mInstantAppRegistry.pruneInstantApps();
23619        }
23620
23621        @Override
23622        public String getSetupWizardPackageName() {
23623            return mSetupWizardPackage;
23624        }
23625
23626        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23627            if (policy != null) {
23628                mExternalSourcesPolicy = policy;
23629            }
23630        }
23631
23632        @Override
23633        public boolean isPackagePersistent(String packageName) {
23634            synchronized (mPackages) {
23635                PackageParser.Package pkg = mPackages.get(packageName);
23636                return pkg != null
23637                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23638                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23639                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23640                        : false;
23641            }
23642        }
23643
23644        @Override
23645        public boolean isLegacySystemApp(Package pkg) {
23646            synchronized (mPackages) {
23647                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23648                return mPromoteSystemApps
23649                        && ps.isSystem()
23650                        && mExistingSystemPackages.contains(ps.name);
23651            }
23652        }
23653
23654        @Override
23655        public List<PackageInfo> getOverlayPackages(int userId) {
23656            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23657            synchronized (mPackages) {
23658                for (PackageParser.Package p : mPackages.values()) {
23659                    if (p.mOverlayTarget != null) {
23660                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23661                        if (pkg != null) {
23662                            overlayPackages.add(pkg);
23663                        }
23664                    }
23665                }
23666            }
23667            return overlayPackages;
23668        }
23669
23670        @Override
23671        public List<String> getTargetPackageNames(int userId) {
23672            List<String> targetPackages = new ArrayList<>();
23673            synchronized (mPackages) {
23674                for (PackageParser.Package p : mPackages.values()) {
23675                    if (p.mOverlayTarget == null) {
23676                        targetPackages.add(p.packageName);
23677                    }
23678                }
23679            }
23680            return targetPackages;
23681        }
23682
23683        @Override
23684        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23685                @Nullable List<String> overlayPackageNames) {
23686            synchronized (mPackages) {
23687                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23688                    Slog.e(TAG, "failed to find package " + targetPackageName);
23689                    return false;
23690                }
23691                ArrayList<String> overlayPaths = null;
23692                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23693                    final int N = overlayPackageNames.size();
23694                    overlayPaths = new ArrayList<>(N);
23695                    for (int i = 0; i < N; i++) {
23696                        final String packageName = overlayPackageNames.get(i);
23697                        final PackageParser.Package pkg = mPackages.get(packageName);
23698                        if (pkg == null) {
23699                            Slog.e(TAG, "failed to find package " + packageName);
23700                            return false;
23701                        }
23702                        overlayPaths.add(pkg.baseCodePath);
23703                    }
23704                }
23705
23706                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23707                ps.setOverlayPaths(overlayPaths, userId);
23708                return true;
23709            }
23710        }
23711
23712        @Override
23713        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23714                int flags, int userId, boolean resolveForStart) {
23715            return resolveIntentInternal(
23716                    intent, resolvedType, flags, userId, resolveForStart);
23717        }
23718
23719        @Override
23720        public ResolveInfo resolveService(Intent intent, String resolvedType,
23721                int flags, int userId, int callingUid) {
23722            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23723        }
23724
23725        @Override
23726        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23727            return PackageManagerService.this.resolveContentProviderInternal(
23728                    name, flags, userId);
23729        }
23730
23731        @Override
23732        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23733            synchronized (mPackages) {
23734                mIsolatedOwners.put(isolatedUid, ownerUid);
23735            }
23736        }
23737
23738        @Override
23739        public void removeIsolatedUid(int isolatedUid) {
23740            synchronized (mPackages) {
23741                mIsolatedOwners.delete(isolatedUid);
23742            }
23743        }
23744
23745        @Override
23746        public int getUidTargetSdkVersion(int uid) {
23747            synchronized (mPackages) {
23748                return getUidTargetSdkVersionLockedLPr(uid);
23749            }
23750        }
23751
23752        @Override
23753        public int getPackageTargetSdkVersion(String packageName) {
23754            synchronized (mPackages) {
23755                return getPackageTargetSdkVersionLockedLPr(packageName);
23756            }
23757        }
23758
23759        @Override
23760        public boolean canAccessInstantApps(int callingUid, int userId) {
23761            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
23762        }
23763
23764        @Override
23765        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
23766            synchronized (mPackages) {
23767                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
23768            }
23769        }
23770
23771        @Override
23772        public void notifyPackageUse(String packageName, int reason) {
23773            synchronized (mPackages) {
23774                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
23775            }
23776        }
23777    }
23778
23779    @Override
23780    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23781        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23782        synchronized (mPackages) {
23783            final long identity = Binder.clearCallingIdentity();
23784            try {
23785                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
23786                        packageNames, userId);
23787            } finally {
23788                Binder.restoreCallingIdentity(identity);
23789            }
23790        }
23791    }
23792
23793    @Override
23794    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23795        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23796        synchronized (mPackages) {
23797            final long identity = Binder.clearCallingIdentity();
23798            try {
23799                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
23800                        packageNames, userId);
23801            } finally {
23802                Binder.restoreCallingIdentity(identity);
23803            }
23804        }
23805    }
23806
23807    private static void enforceSystemOrPhoneCaller(String tag) {
23808        int callingUid = Binder.getCallingUid();
23809        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23810            throw new SecurityException(
23811                    "Cannot call " + tag + " from UID " + callingUid);
23812        }
23813    }
23814
23815    boolean isHistoricalPackageUsageAvailable() {
23816        return mPackageUsage.isHistoricalPackageUsageAvailable();
23817    }
23818
23819    /**
23820     * Return a <b>copy</b> of the collection of packages known to the package manager.
23821     * @return A copy of the values of mPackages.
23822     */
23823    Collection<PackageParser.Package> getPackages() {
23824        synchronized (mPackages) {
23825            return new ArrayList<>(mPackages.values());
23826        }
23827    }
23828
23829    /**
23830     * Logs process start information (including base APK hash) to the security log.
23831     * @hide
23832     */
23833    @Override
23834    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23835            String apkFile, int pid) {
23836        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23837            return;
23838        }
23839        if (!SecurityLog.isLoggingEnabled()) {
23840            return;
23841        }
23842        Bundle data = new Bundle();
23843        data.putLong("startTimestamp", System.currentTimeMillis());
23844        data.putString("processName", processName);
23845        data.putInt("uid", uid);
23846        data.putString("seinfo", seinfo);
23847        data.putString("apkFile", apkFile);
23848        data.putInt("pid", pid);
23849        Message msg = mProcessLoggingHandler.obtainMessage(
23850                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23851        msg.setData(data);
23852        mProcessLoggingHandler.sendMessage(msg);
23853    }
23854
23855    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23856        return mCompilerStats.getPackageStats(pkgName);
23857    }
23858
23859    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23860        return getOrCreateCompilerPackageStats(pkg.packageName);
23861    }
23862
23863    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23864        return mCompilerStats.getOrCreatePackageStats(pkgName);
23865    }
23866
23867    public void deleteCompilerPackageStats(String pkgName) {
23868        mCompilerStats.deletePackageStats(pkgName);
23869    }
23870
23871    @Override
23872    public int getInstallReason(String packageName, int userId) {
23873        final int callingUid = Binder.getCallingUid();
23874        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23875                true /* requireFullPermission */, false /* checkShell */,
23876                "get install reason");
23877        synchronized (mPackages) {
23878            final PackageSetting ps = mSettings.mPackages.get(packageName);
23879            if (filterAppAccessLPr(ps, callingUid, userId)) {
23880                return PackageManager.INSTALL_REASON_UNKNOWN;
23881            }
23882            if (ps != null) {
23883                return ps.getInstallReason(userId);
23884            }
23885        }
23886        return PackageManager.INSTALL_REASON_UNKNOWN;
23887    }
23888
23889    @Override
23890    public boolean canRequestPackageInstalls(String packageName, int userId) {
23891        return canRequestPackageInstallsInternal(packageName, 0, userId,
23892                true /* throwIfPermNotDeclared*/);
23893    }
23894
23895    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
23896            boolean throwIfPermNotDeclared) {
23897        int callingUid = Binder.getCallingUid();
23898        int uid = getPackageUid(packageName, 0, userId);
23899        if (callingUid != uid && callingUid != Process.ROOT_UID
23900                && callingUid != Process.SYSTEM_UID) {
23901            throw new SecurityException(
23902                    "Caller uid " + callingUid + " does not own package " + packageName);
23903        }
23904        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
23905        if (info == null) {
23906            return false;
23907        }
23908        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23909            return false;
23910        }
23911        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23912        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23913        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23914            if (throwIfPermNotDeclared) {
23915                throw new SecurityException("Need to declare " + appOpPermission
23916                        + " to call this api");
23917            } else {
23918                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
23919                return false;
23920            }
23921        }
23922        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23923            return false;
23924        }
23925        if (mExternalSourcesPolicy != null) {
23926            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23927            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23928                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23929            }
23930        }
23931        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23932    }
23933
23934    @Override
23935    public ComponentName getInstantAppResolverSettingsComponent() {
23936        return mInstantAppResolverSettingsComponent;
23937    }
23938
23939    @Override
23940    public ComponentName getInstantAppInstallerComponent() {
23941        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23942            return null;
23943        }
23944        return mInstantAppInstallerActivity == null
23945                ? null : mInstantAppInstallerActivity.getComponentName();
23946    }
23947
23948    @Override
23949    public String getInstantAppAndroidId(String packageName, int userId) {
23950        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23951                "getInstantAppAndroidId");
23952        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
23953                true /* requireFullPermission */, false /* checkShell */,
23954                "getInstantAppAndroidId");
23955        // Make sure the target is an Instant App.
23956        if (!isInstantApp(packageName, userId)) {
23957            return null;
23958        }
23959        synchronized (mPackages) {
23960            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
23961        }
23962    }
23963
23964    boolean canHaveOatDir(String packageName) {
23965        synchronized (mPackages) {
23966            PackageParser.Package p = mPackages.get(packageName);
23967            if (p == null) {
23968                return false;
23969            }
23970            return p.canHaveOatDir();
23971        }
23972    }
23973
23974    private String getOatDir(PackageParser.Package pkg) {
23975        if (!pkg.canHaveOatDir()) {
23976            return null;
23977        }
23978        File codePath = new File(pkg.codePath);
23979        if (codePath.isDirectory()) {
23980            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
23981        }
23982        return null;
23983    }
23984
23985    void deleteOatArtifactsOfPackage(String packageName) {
23986        final String[] instructionSets;
23987        final List<String> codePaths;
23988        final String oatDir;
23989        final PackageParser.Package pkg;
23990        synchronized (mPackages) {
23991            pkg = mPackages.get(packageName);
23992        }
23993        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
23994        codePaths = pkg.getAllCodePaths();
23995        oatDir = getOatDir(pkg);
23996
23997        for (String codePath : codePaths) {
23998            for (String isa : instructionSets) {
23999                try {
24000                    mInstaller.deleteOdex(codePath, isa, oatDir);
24001                } catch (InstallerException e) {
24002                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24003                }
24004            }
24005        }
24006    }
24007
24008    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24009        Set<String> unusedPackages = new HashSet<>();
24010        long currentTimeInMillis = System.currentTimeMillis();
24011        synchronized (mPackages) {
24012            for (PackageParser.Package pkg : mPackages.values()) {
24013                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24014                if (ps == null) {
24015                    continue;
24016                }
24017                PackageDexUsage.PackageUseInfo packageUseInfo =
24018                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24019                if (PackageManagerServiceUtils
24020                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24021                                downgradeTimeThresholdMillis, packageUseInfo,
24022                                pkg.getLatestPackageUseTimeInMills(),
24023                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24024                    unusedPackages.add(pkg.packageName);
24025                }
24026            }
24027        }
24028        return unusedPackages;
24029    }
24030
24031    @Override
24032    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24033            int userId) {
24034        final int callingUid = Binder.getCallingUid();
24035        final int callingAppId = UserHandle.getAppId(callingUid);
24036
24037        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24038                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24039
24040        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24041                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24042            throw new SecurityException("Caller must have the "
24043                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24044        }
24045
24046        synchronized(mPackages) {
24047            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24048            scheduleWritePackageRestrictionsLocked(userId);
24049        }
24050    }
24051
24052    @Nullable
24053    @Override
24054    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24055        final int callingUid = Binder.getCallingUid();
24056        final int callingAppId = UserHandle.getAppId(callingUid);
24057
24058        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24059                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24060
24061        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24062                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24063            throw new SecurityException("Caller must have the "
24064                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24065        }
24066
24067        synchronized(mPackages) {
24068            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24069        }
24070    }
24071}
24072
24073interface PackageSender {
24074    /**
24075     * @param userIds User IDs where the action occurred on a full application
24076     * @param instantUserIds User IDs where the action occurred on an instant application
24077     */
24078    void sendPackageBroadcast(final String action, final String pkg,
24079        final Bundle extras, final int flags, final String targetPkg,
24080        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24081    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24082        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24083    void notifyPackageAdded(String packageName);
24084    void notifyPackageRemoved(String packageName);
24085}
24086