PackageManagerService.java revision 4bc8f4daf3635b50e25a470c2e07e4d62b5e798f
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_UNKNOWN = -1;
602    public static final int REASON_FIRST_BOOT = 0;
603    public static final int REASON_BOOT = 1;
604    public static final int REASON_INSTALL = 2;
605    public static final int REASON_BACKGROUND_DEXOPT = 3;
606    public static final int REASON_AB_OTA = 4;
607    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
608    public static final int REASON_SHARED = 6;
609
610    public static final int REASON_LAST = REASON_SHARED;
611
612    /**
613     * Version number for the package parser cache. Increment this whenever the format or
614     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
615     */
616    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
617
618    /**
619     * Whether the package parser cache is enabled.
620     */
621    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
622
623    /**
624     * Permissions required in order to receive instant application lifecycle broadcasts.
625     */
626    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
627            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
628
629    final ServiceThread mHandlerThread;
630
631    final PackageHandler mHandler;
632
633    private final ProcessLoggingHandler mProcessLoggingHandler;
634
635    /**
636     * Messages for {@link #mHandler} that need to wait for system ready before
637     * being dispatched.
638     */
639    private ArrayList<Message> mPostSystemReadyMessages;
640
641    final int mSdkVersion = Build.VERSION.SDK_INT;
642
643    final Context mContext;
644    final boolean mFactoryTest;
645    final boolean mOnlyCore;
646    final DisplayMetrics mMetrics;
647    final int mDefParseFlags;
648    final String[] mSeparateProcesses;
649    final boolean mIsUpgrade;
650    final boolean mIsPreNUpgrade;
651    final boolean mIsPreNMR1Upgrade;
652
653    // Have we told the Activity Manager to whitelist the default container service by uid yet?
654    @GuardedBy("mPackages")
655    boolean mDefaultContainerWhitelisted = false;
656
657    @GuardedBy("mPackages")
658    private boolean mDexOptDialogShown;
659
660    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
661    // LOCK HELD.  Can be called with mInstallLock held.
662    @GuardedBy("mInstallLock")
663    final Installer mInstaller;
664
665    /** Directory where installed applications are stored */
666    private static final File sAppInstallDir =
667            new File(Environment.getDataDirectory(), "app");
668    /** Directory where installed application's 32-bit native libraries are copied. */
669    private static final File sAppLib32InstallDir =
670            new File(Environment.getDataDirectory(), "app-lib");
671    /** Directory where code and non-resource assets of forward-locked applications are stored */
672    private static final File sDrmAppPrivateInstallDir =
673            new File(Environment.getDataDirectory(), "app-private");
674
675    // ----------------------------------------------------------------
676
677    // Lock for state used when installing and doing other long running
678    // operations.  Methods that must be called with this lock held have
679    // the suffix "LI".
680    final Object mInstallLock = new Object();
681
682    // ----------------------------------------------------------------
683
684    // Keys are String (package name), values are Package.  This also serves
685    // as the lock for the global state.  Methods that must be called with
686    // this lock held have the prefix "LP".
687    @GuardedBy("mPackages")
688    final ArrayMap<String, PackageParser.Package> mPackages =
689            new ArrayMap<String, PackageParser.Package>();
690
691    final ArrayMap<String, Set<String>> mKnownCodebase =
692            new ArrayMap<String, Set<String>>();
693
694    // Keys are isolated uids and values are the uid of the application
695    // that created the isolated proccess.
696    @GuardedBy("mPackages")
697    final SparseIntArray mIsolatedOwners = new SparseIntArray();
698
699    /**
700     * Tracks new system packages [received in an OTA] that we expect to
701     * find updated user-installed versions. Keys are package name, values
702     * are package location.
703     */
704    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
705    /**
706     * Tracks high priority intent filters for protected actions. During boot, certain
707     * filter actions are protected and should never be allowed to have a high priority
708     * intent filter for them. However, there is one, and only one exception -- the
709     * setup wizard. It must be able to define a high priority intent filter for these
710     * actions to ensure there are no escapes from the wizard. We need to delay processing
711     * of these during boot as we need to look at all of the system packages in order
712     * to know which component is the setup wizard.
713     */
714    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
715    /**
716     * Whether or not processing protected filters should be deferred.
717     */
718    private boolean mDeferProtectedFilters = true;
719
720    /**
721     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
722     */
723    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
724    /**
725     * Whether or not system app permissions should be promoted from install to runtime.
726     */
727    boolean mPromoteSystemApps;
728
729    @GuardedBy("mPackages")
730    final Settings mSettings;
731
732    /**
733     * Set of package names that are currently "frozen", which means active
734     * surgery is being done on the code/data for that package. The platform
735     * will refuse to launch frozen packages to avoid race conditions.
736     *
737     * @see PackageFreezer
738     */
739    @GuardedBy("mPackages")
740    final ArraySet<String> mFrozenPackages = new ArraySet<>();
741
742    final ProtectedPackages mProtectedPackages;
743
744    @GuardedBy("mLoadedVolumes")
745    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
746
747    boolean mFirstBoot;
748
749    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
750
751    @GuardedBy("mAvailableFeatures")
752    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
753
754    private final InstantAppRegistry mInstantAppRegistry;
755
756    @GuardedBy("mPackages")
757    int mChangedPackagesSequenceNumber;
758    /**
759     * List of changed [installed, removed or updated] packages.
760     * mapping from user id -> sequence number -> package name
761     */
762    @GuardedBy("mPackages")
763    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
764    /**
765     * The sequence number of the last change to a package.
766     * mapping from user id -> package name -> sequence number
767     */
768    @GuardedBy("mPackages")
769    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
770
771    @GuardedBy("mPackages")
772    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
773
774    class PackageParserCallback implements PackageParser.Callback {
775        @Override public final boolean hasFeature(String feature) {
776            return PackageManagerService.this.hasSystemFeature(feature, 0);
777        }
778
779        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
780                Collection<PackageParser.Package> allPackages, String targetPackageName) {
781            List<PackageParser.Package> overlayPackages = null;
782            for (PackageParser.Package p : allPackages) {
783                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
784                    if (overlayPackages == null) {
785                        overlayPackages = new ArrayList<PackageParser.Package>();
786                    }
787                    overlayPackages.add(p);
788                }
789            }
790            if (overlayPackages != null) {
791                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
792                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
793                        return p1.mOverlayPriority - p2.mOverlayPriority;
794                    }
795                };
796                Collections.sort(overlayPackages, cmp);
797            }
798            return overlayPackages;
799        }
800
801        @GuardedBy("mInstallLock")
802        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
803                String targetPackageName, String targetPath) {
804            if ("android".equals(targetPackageName)) {
805                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
806                // native AssetManager.
807                return null;
808            }
809            List<PackageParser.Package> overlayPackages =
810                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
811            if (overlayPackages == null || overlayPackages.isEmpty()) {
812                return null;
813            }
814            List<String> overlayPathList = null;
815            for (PackageParser.Package overlayPackage : overlayPackages) {
816                if (targetPath == null) {
817                    if (overlayPathList == null) {
818                        overlayPathList = new ArrayList<String>();
819                    }
820                    overlayPathList.add(overlayPackage.baseCodePath);
821                    continue;
822                }
823
824                try {
825                    // Creates idmaps for system to parse correctly the Android manifest of the
826                    // target package.
827                    //
828                    // OverlayManagerService will update each of them with a correct gid from its
829                    // target package app id.
830                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
831                            UserHandle.getSharedAppGid(
832                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
833                    if (overlayPathList == null) {
834                        overlayPathList = new ArrayList<String>();
835                    }
836                    overlayPathList.add(overlayPackage.baseCodePath);
837                } catch (InstallerException e) {
838                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
839                            overlayPackage.baseCodePath);
840                }
841            }
842            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
843        }
844
845        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
846            synchronized (mPackages) {
847                return getStaticOverlayPathsLocked(
848                        mPackages.values(), targetPackageName, targetPath);
849            }
850        }
851
852        @Override public final String[] getOverlayApks(String targetPackageName) {
853            return getStaticOverlayPaths(targetPackageName, null);
854        }
855
856        @Override public final String[] getOverlayPaths(String targetPackageName,
857                String targetPath) {
858            return getStaticOverlayPaths(targetPackageName, targetPath);
859        }
860    }
861
862    class ParallelPackageParserCallback extends PackageParserCallback {
863        List<PackageParser.Package> mOverlayPackages = null;
864
865        void findStaticOverlayPackages() {
866            synchronized (mPackages) {
867                for (PackageParser.Package p : mPackages.values()) {
868                    if (p.mOverlayIsStatic) {
869                        if (mOverlayPackages == null) {
870                            mOverlayPackages = new ArrayList<PackageParser.Package>();
871                        }
872                        mOverlayPackages.add(p);
873                    }
874                }
875            }
876        }
877
878        @Override
879        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
880            // We can trust mOverlayPackages without holding mPackages because package uninstall
881            // can't happen while running parallel parsing.
882            // Moreover holding mPackages on each parsing thread causes dead-lock.
883            return mOverlayPackages == null ? null :
884                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
885        }
886    }
887
888    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
889    final ParallelPackageParserCallback mParallelPackageParserCallback =
890            new ParallelPackageParserCallback();
891
892    public static final class SharedLibraryEntry {
893        public final @Nullable String path;
894        public final @Nullable String apk;
895        public final @NonNull SharedLibraryInfo info;
896
897        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
898                String declaringPackageName, long declaringPackageVersionCode) {
899            path = _path;
900            apk = _apk;
901            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
902                    declaringPackageName, declaringPackageVersionCode), null);
903        }
904    }
905
906    // Currently known shared libraries.
907    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
908    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
909            new ArrayMap<>();
910
911    // All available activities, for your resolving pleasure.
912    final ActivityIntentResolver mActivities =
913            new ActivityIntentResolver();
914
915    // All available receivers, for your resolving pleasure.
916    final ActivityIntentResolver mReceivers =
917            new ActivityIntentResolver();
918
919    // All available services, for your resolving pleasure.
920    final ServiceIntentResolver mServices = new ServiceIntentResolver();
921
922    // All available providers, for your resolving pleasure.
923    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
924
925    // Mapping from provider base names (first directory in content URI codePath)
926    // to the provider information.
927    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
928            new ArrayMap<String, PackageParser.Provider>();
929
930    // Mapping from instrumentation class names to info about them.
931    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
932            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
933
934    // Packages whose data we have transfered into another package, thus
935    // should no longer exist.
936    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
937
938    // Broadcast actions that are only available to the system.
939    @GuardedBy("mProtectedBroadcasts")
940    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
941
942    /** List of packages waiting for verification. */
943    final SparseArray<PackageVerificationState> mPendingVerification
944            = new SparseArray<PackageVerificationState>();
945
946    final PackageInstallerService mInstallerService;
947
948    final ArtManagerService mArtManagerService;
949
950    private final PackageDexOptimizer mPackageDexOptimizer;
951    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
952    // is used by other apps).
953    private final DexManager mDexManager;
954
955    private AtomicInteger mNextMoveId = new AtomicInteger();
956    private final MoveCallbacks mMoveCallbacks;
957
958    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
959
960    // Cache of users who need badging.
961    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
962
963    /** Token for keys in mPendingVerification. */
964    private int mPendingVerificationToken = 0;
965
966    volatile boolean mSystemReady;
967    volatile boolean mSafeMode;
968    volatile boolean mHasSystemUidErrors;
969    private volatile boolean mWebInstantAppsDisabled;
970
971    ApplicationInfo mAndroidApplication;
972    final ActivityInfo mResolveActivity = new ActivityInfo();
973    final ResolveInfo mResolveInfo = new ResolveInfo();
974    ComponentName mResolveComponentName;
975    PackageParser.Package mPlatformPackage;
976    ComponentName mCustomResolverComponentName;
977
978    boolean mResolverReplaced = false;
979
980    private final @Nullable ComponentName mIntentFilterVerifierComponent;
981    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
982
983    private int mIntentFilterVerificationToken = 0;
984
985    /** The service connection to the ephemeral resolver */
986    final InstantAppResolverConnection mInstantAppResolverConnection;
987    /** Component used to show resolver settings for Instant Apps */
988    final ComponentName mInstantAppResolverSettingsComponent;
989
990    /** Activity used to install instant applications */
991    ActivityInfo mInstantAppInstallerActivity;
992    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
993
994    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
995            = new SparseArray<IntentFilterVerificationState>();
996
997    // TODO remove this and go through mPermissonManager directly
998    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
999    private final PermissionManagerInternal mPermissionManager;
1000
1001    // List of packages names to keep cached, even if they are uninstalled for all users
1002    private List<String> mKeepUninstalledPackages;
1003
1004    private UserManagerInternal mUserManagerInternal;
1005    private ActivityManagerInternal mActivityManagerInternal;
1006
1007    private DeviceIdleController.LocalService mDeviceIdleController;
1008
1009    private File mCacheDir;
1010
1011    private Future<?> mPrepareAppDataFuture;
1012
1013    private static class IFVerificationParams {
1014        PackageParser.Package pkg;
1015        boolean replacing;
1016        int userId;
1017        int verifierUid;
1018
1019        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1020                int _userId, int _verifierUid) {
1021            pkg = _pkg;
1022            replacing = _replacing;
1023            userId = _userId;
1024            replacing = _replacing;
1025            verifierUid = _verifierUid;
1026        }
1027    }
1028
1029    private interface IntentFilterVerifier<T extends IntentFilter> {
1030        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1031                                               T filter, String packageName);
1032        void startVerifications(int userId);
1033        void receiveVerificationResponse(int verificationId);
1034    }
1035
1036    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1037        private Context mContext;
1038        private ComponentName mIntentFilterVerifierComponent;
1039        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1040
1041        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1042            mContext = context;
1043            mIntentFilterVerifierComponent = verifierComponent;
1044        }
1045
1046        private String getDefaultScheme() {
1047            return IntentFilter.SCHEME_HTTPS;
1048        }
1049
1050        @Override
1051        public void startVerifications(int userId) {
1052            // Launch verifications requests
1053            int count = mCurrentIntentFilterVerifications.size();
1054            for (int n=0; n<count; n++) {
1055                int verificationId = mCurrentIntentFilterVerifications.get(n);
1056                final IntentFilterVerificationState ivs =
1057                        mIntentFilterVerificationStates.get(verificationId);
1058
1059                String packageName = ivs.getPackageName();
1060
1061                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1062                final int filterCount = filters.size();
1063                ArraySet<String> domainsSet = new ArraySet<>();
1064                for (int m=0; m<filterCount; m++) {
1065                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1066                    domainsSet.addAll(filter.getHostsList());
1067                }
1068                synchronized (mPackages) {
1069                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1070                            packageName, domainsSet) != null) {
1071                        scheduleWriteSettingsLocked();
1072                    }
1073                }
1074                sendVerificationRequest(verificationId, ivs);
1075            }
1076            mCurrentIntentFilterVerifications.clear();
1077        }
1078
1079        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1080            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1081            verificationIntent.putExtra(
1082                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1083                    verificationId);
1084            verificationIntent.putExtra(
1085                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1086                    getDefaultScheme());
1087            verificationIntent.putExtra(
1088                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1089                    ivs.getHostsString());
1090            verificationIntent.putExtra(
1091                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1092                    ivs.getPackageName());
1093            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1094            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1095
1096            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1097            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1098                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1099                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1100
1101            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1102            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1103                    "Sending IntentFilter verification broadcast");
1104        }
1105
1106        public void receiveVerificationResponse(int verificationId) {
1107            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1108
1109            final boolean verified = ivs.isVerified();
1110
1111            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1112            final int count = filters.size();
1113            if (DEBUG_DOMAIN_VERIFICATION) {
1114                Slog.i(TAG, "Received verification response " + verificationId
1115                        + " for " + count + " filters, verified=" + verified);
1116            }
1117            for (int n=0; n<count; n++) {
1118                PackageParser.ActivityIntentInfo filter = filters.get(n);
1119                filter.setVerified(verified);
1120
1121                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1122                        + " verified with result:" + verified + " and hosts:"
1123                        + ivs.getHostsString());
1124            }
1125
1126            mIntentFilterVerificationStates.remove(verificationId);
1127
1128            final String packageName = ivs.getPackageName();
1129            IntentFilterVerificationInfo ivi = null;
1130
1131            synchronized (mPackages) {
1132                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1133            }
1134            if (ivi == null) {
1135                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1136                        + verificationId + " packageName:" + packageName);
1137                return;
1138            }
1139            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1140                    "Updating IntentFilterVerificationInfo for package " + packageName
1141                            +" verificationId:" + verificationId);
1142
1143            synchronized (mPackages) {
1144                if (verified) {
1145                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1146                } else {
1147                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1148                }
1149                scheduleWriteSettingsLocked();
1150
1151                final int userId = ivs.getUserId();
1152                if (userId != UserHandle.USER_ALL) {
1153                    final int userStatus =
1154                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1155
1156                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1157                    boolean needUpdate = false;
1158
1159                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1160                    // already been set by the User thru the Disambiguation dialog
1161                    switch (userStatus) {
1162                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1163                            if (verified) {
1164                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1165                            } else {
1166                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1167                            }
1168                            needUpdate = true;
1169                            break;
1170
1171                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1172                            if (verified) {
1173                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1174                                needUpdate = true;
1175                            }
1176                            break;
1177
1178                        default:
1179                            // Nothing to do
1180                    }
1181
1182                    if (needUpdate) {
1183                        mSettings.updateIntentFilterVerificationStatusLPw(
1184                                packageName, updatedStatus, userId);
1185                        scheduleWritePackageRestrictionsLocked(userId);
1186                    }
1187                }
1188            }
1189        }
1190
1191        @Override
1192        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1193                    ActivityIntentInfo filter, String packageName) {
1194            if (!hasValidDomains(filter)) {
1195                return false;
1196            }
1197            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1198            if (ivs == null) {
1199                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1200                        packageName);
1201            }
1202            if (DEBUG_DOMAIN_VERIFICATION) {
1203                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1204            }
1205            ivs.addFilter(filter);
1206            return true;
1207        }
1208
1209        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1210                int userId, int verificationId, String packageName) {
1211            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1212                    verifierUid, userId, packageName);
1213            ivs.setPendingState();
1214            synchronized (mPackages) {
1215                mIntentFilterVerificationStates.append(verificationId, ivs);
1216                mCurrentIntentFilterVerifications.add(verificationId);
1217            }
1218            return ivs;
1219        }
1220    }
1221
1222    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1223        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1224                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1225                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1226    }
1227
1228    // Set of pending broadcasts for aggregating enable/disable of components.
1229    static class PendingPackageBroadcasts {
1230        // for each user id, a map of <package name -> components within that package>
1231        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1232
1233        public PendingPackageBroadcasts() {
1234            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1235        }
1236
1237        public ArrayList<String> get(int userId, String packageName) {
1238            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1239            return packages.get(packageName);
1240        }
1241
1242        public void put(int userId, String packageName, ArrayList<String> components) {
1243            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1244            packages.put(packageName, components);
1245        }
1246
1247        public void remove(int userId, String packageName) {
1248            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1249            if (packages != null) {
1250                packages.remove(packageName);
1251            }
1252        }
1253
1254        public void remove(int userId) {
1255            mUidMap.remove(userId);
1256        }
1257
1258        public int userIdCount() {
1259            return mUidMap.size();
1260        }
1261
1262        public int userIdAt(int n) {
1263            return mUidMap.keyAt(n);
1264        }
1265
1266        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1267            return mUidMap.get(userId);
1268        }
1269
1270        public int size() {
1271            // total number of pending broadcast entries across all userIds
1272            int num = 0;
1273            for (int i = 0; i< mUidMap.size(); i++) {
1274                num += mUidMap.valueAt(i).size();
1275            }
1276            return num;
1277        }
1278
1279        public void clear() {
1280            mUidMap.clear();
1281        }
1282
1283        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1284            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1285            if (map == null) {
1286                map = new ArrayMap<String, ArrayList<String>>();
1287                mUidMap.put(userId, map);
1288            }
1289            return map;
1290        }
1291    }
1292    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1293
1294    // Service Connection to remote media container service to copy
1295    // package uri's from external media onto secure containers
1296    // or internal storage.
1297    private IMediaContainerService mContainerService = null;
1298
1299    static final int SEND_PENDING_BROADCAST = 1;
1300    static final int MCS_BOUND = 3;
1301    static final int END_COPY = 4;
1302    static final int INIT_COPY = 5;
1303    static final int MCS_UNBIND = 6;
1304    static final int START_CLEANING_PACKAGE = 7;
1305    static final int FIND_INSTALL_LOC = 8;
1306    static final int POST_INSTALL = 9;
1307    static final int MCS_RECONNECT = 10;
1308    static final int MCS_GIVE_UP = 11;
1309    static final int WRITE_SETTINGS = 13;
1310    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1311    static final int PACKAGE_VERIFIED = 15;
1312    static final int CHECK_PENDING_VERIFICATION = 16;
1313    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1314    static final int INTENT_FILTER_VERIFIED = 18;
1315    static final int WRITE_PACKAGE_LIST = 19;
1316    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1317
1318    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1319
1320    // Delay time in millisecs
1321    static final int BROADCAST_DELAY = 10 * 1000;
1322
1323    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1324            2 * 60 * 60 * 1000L; /* two hours */
1325
1326    static UserManagerService sUserManager;
1327
1328    // Stores a list of users whose package restrictions file needs to be updated
1329    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1330
1331    final private DefaultContainerConnection mDefContainerConn =
1332            new DefaultContainerConnection();
1333    class DefaultContainerConnection implements ServiceConnection {
1334        public void onServiceConnected(ComponentName name, IBinder service) {
1335            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1336            final IMediaContainerService imcs = IMediaContainerService.Stub
1337                    .asInterface(Binder.allowBlocking(service));
1338            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1339        }
1340
1341        public void onServiceDisconnected(ComponentName name) {
1342            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1343        }
1344    }
1345
1346    // Recordkeeping of restore-after-install operations that are currently in flight
1347    // between the Package Manager and the Backup Manager
1348    static class PostInstallData {
1349        public InstallArgs args;
1350        public PackageInstalledInfo res;
1351
1352        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1353            args = _a;
1354            res = _r;
1355        }
1356    }
1357
1358    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1359    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1360
1361    // XML tags for backup/restore of various bits of state
1362    private static final String TAG_PREFERRED_BACKUP = "pa";
1363    private static final String TAG_DEFAULT_APPS = "da";
1364    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1365
1366    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1367    private static final String TAG_ALL_GRANTS = "rt-grants";
1368    private static final String TAG_GRANT = "grant";
1369    private static final String ATTR_PACKAGE_NAME = "pkg";
1370
1371    private static final String TAG_PERMISSION = "perm";
1372    private static final String ATTR_PERMISSION_NAME = "name";
1373    private static final String ATTR_IS_GRANTED = "g";
1374    private static final String ATTR_USER_SET = "set";
1375    private static final String ATTR_USER_FIXED = "fixed";
1376    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1377
1378    // System/policy permission grants are not backed up
1379    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1380            FLAG_PERMISSION_POLICY_FIXED
1381            | FLAG_PERMISSION_SYSTEM_FIXED
1382            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1383
1384    // And we back up these user-adjusted states
1385    private static final int USER_RUNTIME_GRANT_MASK =
1386            FLAG_PERMISSION_USER_SET
1387            | FLAG_PERMISSION_USER_FIXED
1388            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1389
1390    final @Nullable String mRequiredVerifierPackage;
1391    final @NonNull String mRequiredInstallerPackage;
1392    final @NonNull String mRequiredUninstallerPackage;
1393    final @Nullable String mSetupWizardPackage;
1394    final @Nullable String mStorageManagerPackage;
1395    final @NonNull String mServicesSystemSharedLibraryPackageName;
1396    final @NonNull String mSharedSystemSharedLibraryPackageName;
1397
1398    private final PackageUsage mPackageUsage = new PackageUsage();
1399    private final CompilerStats mCompilerStats = new CompilerStats();
1400
1401    class PackageHandler extends Handler {
1402        private boolean mBound = false;
1403        final ArrayList<HandlerParams> mPendingInstalls =
1404            new ArrayList<HandlerParams>();
1405
1406        private boolean connectToService() {
1407            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1408                    " DefaultContainerService");
1409            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1410            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1411            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1412                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1413                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1414                mBound = true;
1415                return true;
1416            }
1417            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1418            return false;
1419        }
1420
1421        private void disconnectService() {
1422            mContainerService = null;
1423            mBound = false;
1424            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1425            mContext.unbindService(mDefContainerConn);
1426            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1427        }
1428
1429        PackageHandler(Looper looper) {
1430            super(looper);
1431        }
1432
1433        public void handleMessage(Message msg) {
1434            try {
1435                doHandleMessage(msg);
1436            } finally {
1437                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1438            }
1439        }
1440
1441        void doHandleMessage(Message msg) {
1442            switch (msg.what) {
1443                case INIT_COPY: {
1444                    HandlerParams params = (HandlerParams) msg.obj;
1445                    int idx = mPendingInstalls.size();
1446                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1447                    // If a bind was already initiated we dont really
1448                    // need to do anything. The pending install
1449                    // will be processed later on.
1450                    if (!mBound) {
1451                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1452                                System.identityHashCode(mHandler));
1453                        // If this is the only one pending we might
1454                        // have to bind to the service again.
1455                        if (!connectToService()) {
1456                            Slog.e(TAG, "Failed to bind to media container service");
1457                            params.serviceError();
1458                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1459                                    System.identityHashCode(mHandler));
1460                            if (params.traceMethod != null) {
1461                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1462                                        params.traceCookie);
1463                            }
1464                            return;
1465                        } else {
1466                            // Once we bind to the service, the first
1467                            // pending request will be processed.
1468                            mPendingInstalls.add(idx, params);
1469                        }
1470                    } else {
1471                        mPendingInstalls.add(idx, params);
1472                        // Already bound to the service. Just make
1473                        // sure we trigger off processing the first request.
1474                        if (idx == 0) {
1475                            mHandler.sendEmptyMessage(MCS_BOUND);
1476                        }
1477                    }
1478                    break;
1479                }
1480                case MCS_BOUND: {
1481                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1482                    if (msg.obj != null) {
1483                        mContainerService = (IMediaContainerService) msg.obj;
1484                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1485                                System.identityHashCode(mHandler));
1486                    }
1487                    if (mContainerService == null) {
1488                        if (!mBound) {
1489                            // Something seriously wrong since we are not bound and we are not
1490                            // waiting for connection. Bail out.
1491                            Slog.e(TAG, "Cannot bind to media container service");
1492                            for (HandlerParams params : mPendingInstalls) {
1493                                // Indicate service bind error
1494                                params.serviceError();
1495                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1496                                        System.identityHashCode(params));
1497                                if (params.traceMethod != null) {
1498                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1499                                            params.traceMethod, params.traceCookie);
1500                                }
1501                                return;
1502                            }
1503                            mPendingInstalls.clear();
1504                        } else {
1505                            Slog.w(TAG, "Waiting to connect to media container service");
1506                        }
1507                    } else if (mPendingInstalls.size() > 0) {
1508                        HandlerParams params = mPendingInstalls.get(0);
1509                        if (params != null) {
1510                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1511                                    System.identityHashCode(params));
1512                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1513                            if (params.startCopy()) {
1514                                // We are done...  look for more work or to
1515                                // go idle.
1516                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1517                                        "Checking for more work or unbind...");
1518                                // Delete pending install
1519                                if (mPendingInstalls.size() > 0) {
1520                                    mPendingInstalls.remove(0);
1521                                }
1522                                if (mPendingInstalls.size() == 0) {
1523                                    if (mBound) {
1524                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1525                                                "Posting delayed MCS_UNBIND");
1526                                        removeMessages(MCS_UNBIND);
1527                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1528                                        // Unbind after a little delay, to avoid
1529                                        // continual thrashing.
1530                                        sendMessageDelayed(ubmsg, 10000);
1531                                    }
1532                                } else {
1533                                    // There are more pending requests in queue.
1534                                    // Just post MCS_BOUND message to trigger processing
1535                                    // of next pending install.
1536                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1537                                            "Posting MCS_BOUND for next work");
1538                                    mHandler.sendEmptyMessage(MCS_BOUND);
1539                                }
1540                            }
1541                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1542                        }
1543                    } else {
1544                        // Should never happen ideally.
1545                        Slog.w(TAG, "Empty queue");
1546                    }
1547                    break;
1548                }
1549                case MCS_RECONNECT: {
1550                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1551                    if (mPendingInstalls.size() > 0) {
1552                        if (mBound) {
1553                            disconnectService();
1554                        }
1555                        if (!connectToService()) {
1556                            Slog.e(TAG, "Failed to bind to media container service");
1557                            for (HandlerParams params : mPendingInstalls) {
1558                                // Indicate service bind error
1559                                params.serviceError();
1560                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1561                                        System.identityHashCode(params));
1562                            }
1563                            mPendingInstalls.clear();
1564                        }
1565                    }
1566                    break;
1567                }
1568                case MCS_UNBIND: {
1569                    // If there is no actual work left, then time to unbind.
1570                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1571
1572                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1573                        if (mBound) {
1574                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1575
1576                            disconnectService();
1577                        }
1578                    } else if (mPendingInstalls.size() > 0) {
1579                        // There are more pending requests in queue.
1580                        // Just post MCS_BOUND message to trigger processing
1581                        // of next pending install.
1582                        mHandler.sendEmptyMessage(MCS_BOUND);
1583                    }
1584
1585                    break;
1586                }
1587                case MCS_GIVE_UP: {
1588                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1589                    HandlerParams params = mPendingInstalls.remove(0);
1590                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1591                            System.identityHashCode(params));
1592                    break;
1593                }
1594                case SEND_PENDING_BROADCAST: {
1595                    String packages[];
1596                    ArrayList<String> components[];
1597                    int size = 0;
1598                    int uids[];
1599                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1600                    synchronized (mPackages) {
1601                        if (mPendingBroadcasts == null) {
1602                            return;
1603                        }
1604                        size = mPendingBroadcasts.size();
1605                        if (size <= 0) {
1606                            // Nothing to be done. Just return
1607                            return;
1608                        }
1609                        packages = new String[size];
1610                        components = new ArrayList[size];
1611                        uids = new int[size];
1612                        int i = 0;  // filling out the above arrays
1613
1614                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1615                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1616                            Iterator<Map.Entry<String, ArrayList<String>>> it
1617                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1618                                            .entrySet().iterator();
1619                            while (it.hasNext() && i < size) {
1620                                Map.Entry<String, ArrayList<String>> ent = it.next();
1621                                packages[i] = ent.getKey();
1622                                components[i] = ent.getValue();
1623                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1624                                uids[i] = (ps != null)
1625                                        ? UserHandle.getUid(packageUserId, ps.appId)
1626                                        : -1;
1627                                i++;
1628                            }
1629                        }
1630                        size = i;
1631                        mPendingBroadcasts.clear();
1632                    }
1633                    // Send broadcasts
1634                    for (int i = 0; i < size; i++) {
1635                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1636                    }
1637                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1638                    break;
1639                }
1640                case START_CLEANING_PACKAGE: {
1641                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1642                    final String packageName = (String)msg.obj;
1643                    final int userId = msg.arg1;
1644                    final boolean andCode = msg.arg2 != 0;
1645                    synchronized (mPackages) {
1646                        if (userId == UserHandle.USER_ALL) {
1647                            int[] users = sUserManager.getUserIds();
1648                            for (int user : users) {
1649                                mSettings.addPackageToCleanLPw(
1650                                        new PackageCleanItem(user, packageName, andCode));
1651                            }
1652                        } else {
1653                            mSettings.addPackageToCleanLPw(
1654                                    new PackageCleanItem(userId, packageName, andCode));
1655                        }
1656                    }
1657                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1658                    startCleaningPackages();
1659                } break;
1660                case POST_INSTALL: {
1661                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1662
1663                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1664                    final boolean didRestore = (msg.arg2 != 0);
1665                    mRunningInstalls.delete(msg.arg1);
1666
1667                    if (data != null) {
1668                        InstallArgs args = data.args;
1669                        PackageInstalledInfo parentRes = data.res;
1670
1671                        final boolean grantPermissions = (args.installFlags
1672                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1673                        final boolean killApp = (args.installFlags
1674                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1675                        final boolean virtualPreload = ((args.installFlags
1676                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1677                        final String[] grantedPermissions = args.installGrantPermissions;
1678
1679                        // Handle the parent package
1680                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1681                                virtualPreload, grantedPermissions, didRestore,
1682                                args.installerPackageName, args.observer);
1683
1684                        // Handle the child packages
1685                        final int childCount = (parentRes.addedChildPackages != null)
1686                                ? parentRes.addedChildPackages.size() : 0;
1687                        for (int i = 0; i < childCount; i++) {
1688                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1689                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1690                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1691                                    args.installerPackageName, args.observer);
1692                        }
1693
1694                        // Log tracing if needed
1695                        if (args.traceMethod != null) {
1696                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1697                                    args.traceCookie);
1698                        }
1699                    } else {
1700                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1701                    }
1702
1703                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1704                } break;
1705                case WRITE_SETTINGS: {
1706                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1707                    synchronized (mPackages) {
1708                        removeMessages(WRITE_SETTINGS);
1709                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1710                        mSettings.writeLPr();
1711                        mDirtyUsers.clear();
1712                    }
1713                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1714                } break;
1715                case WRITE_PACKAGE_RESTRICTIONS: {
1716                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1717                    synchronized (mPackages) {
1718                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1719                        for (int userId : mDirtyUsers) {
1720                            mSettings.writePackageRestrictionsLPr(userId);
1721                        }
1722                        mDirtyUsers.clear();
1723                    }
1724                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1725                } break;
1726                case WRITE_PACKAGE_LIST: {
1727                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1728                    synchronized (mPackages) {
1729                        removeMessages(WRITE_PACKAGE_LIST);
1730                        mSettings.writePackageListLPr(msg.arg1);
1731                    }
1732                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1733                } break;
1734                case CHECK_PENDING_VERIFICATION: {
1735                    final int verificationId = msg.arg1;
1736                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1737
1738                    if ((state != null) && !state.timeoutExtended()) {
1739                        final InstallArgs args = state.getInstallArgs();
1740                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1741
1742                        Slog.i(TAG, "Verification timed out for " + originUri);
1743                        mPendingVerification.remove(verificationId);
1744
1745                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1746
1747                        final UserHandle user = args.getUser();
1748                        if (getDefaultVerificationResponse(user)
1749                                == PackageManager.VERIFICATION_ALLOW) {
1750                            Slog.i(TAG, "Continuing with installation of " + originUri);
1751                            state.setVerifierResponse(Binder.getCallingUid(),
1752                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1753                            broadcastPackageVerified(verificationId, originUri,
1754                                    PackageManager.VERIFICATION_ALLOW, user);
1755                            try {
1756                                ret = args.copyApk(mContainerService, true);
1757                            } catch (RemoteException e) {
1758                                Slog.e(TAG, "Could not contact the ContainerService");
1759                            }
1760                        } else {
1761                            broadcastPackageVerified(verificationId, originUri,
1762                                    PackageManager.VERIFICATION_REJECT, user);
1763                        }
1764
1765                        Trace.asyncTraceEnd(
1766                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1767
1768                        processPendingInstall(args, ret);
1769                        mHandler.sendEmptyMessage(MCS_UNBIND);
1770                    }
1771                    break;
1772                }
1773                case PACKAGE_VERIFIED: {
1774                    final int verificationId = msg.arg1;
1775
1776                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1777                    if (state == null) {
1778                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1779                        break;
1780                    }
1781
1782                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1783
1784                    state.setVerifierResponse(response.callerUid, response.code);
1785
1786                    if (state.isVerificationComplete()) {
1787                        mPendingVerification.remove(verificationId);
1788
1789                        final InstallArgs args = state.getInstallArgs();
1790                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1791
1792                        int ret;
1793                        if (state.isInstallAllowed()) {
1794                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1795                            broadcastPackageVerified(verificationId, originUri,
1796                                    response.code, state.getInstallArgs().getUser());
1797                            try {
1798                                ret = args.copyApk(mContainerService, true);
1799                            } catch (RemoteException e) {
1800                                Slog.e(TAG, "Could not contact the ContainerService");
1801                            }
1802                        } else {
1803                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1804                        }
1805
1806                        Trace.asyncTraceEnd(
1807                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1808
1809                        processPendingInstall(args, ret);
1810                        mHandler.sendEmptyMessage(MCS_UNBIND);
1811                    }
1812
1813                    break;
1814                }
1815                case START_INTENT_FILTER_VERIFICATIONS: {
1816                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1817                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1818                            params.replacing, params.pkg);
1819                    break;
1820                }
1821                case INTENT_FILTER_VERIFIED: {
1822                    final int verificationId = msg.arg1;
1823
1824                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1825                            verificationId);
1826                    if (state == null) {
1827                        Slog.w(TAG, "Invalid IntentFilter verification token "
1828                                + verificationId + " received");
1829                        break;
1830                    }
1831
1832                    final int userId = state.getUserId();
1833
1834                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1835                            "Processing IntentFilter verification with token:"
1836                            + verificationId + " and userId:" + userId);
1837
1838                    final IntentFilterVerificationResponse response =
1839                            (IntentFilterVerificationResponse) msg.obj;
1840
1841                    state.setVerifierResponse(response.callerUid, response.code);
1842
1843                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1844                            "IntentFilter verification with token:" + verificationId
1845                            + " and userId:" + userId
1846                            + " is settings verifier response with response code:"
1847                            + response.code);
1848
1849                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1850                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1851                                + response.getFailedDomainsString());
1852                    }
1853
1854                    if (state.isVerificationComplete()) {
1855                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1856                    } else {
1857                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1858                                "IntentFilter verification with token:" + verificationId
1859                                + " was not said to be complete");
1860                    }
1861
1862                    break;
1863                }
1864                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1865                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1866                            mInstantAppResolverConnection,
1867                            (InstantAppRequest) msg.obj,
1868                            mInstantAppInstallerActivity,
1869                            mHandler);
1870                }
1871            }
1872        }
1873    }
1874
1875    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1876        @Override
1877        public void onGidsChanged(int appId, int userId) {
1878            mHandler.post(new Runnable() {
1879                @Override
1880                public void run() {
1881                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1882                }
1883            });
1884        }
1885        @Override
1886        public void onPermissionGranted(int uid, int userId) {
1887            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1888
1889            // Not critical; if this is lost, the application has to request again.
1890            synchronized (mPackages) {
1891                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1892            }
1893        }
1894        @Override
1895        public void onInstallPermissionGranted() {
1896            synchronized (mPackages) {
1897                scheduleWriteSettingsLocked();
1898            }
1899        }
1900        @Override
1901        public void onPermissionRevoked(int uid, int userId) {
1902            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1903
1904            synchronized (mPackages) {
1905                // Critical; after this call the application should never have the permission
1906                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1907            }
1908
1909            final int appId = UserHandle.getAppId(uid);
1910            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1911        }
1912        @Override
1913        public void onInstallPermissionRevoked() {
1914            synchronized (mPackages) {
1915                scheduleWriteSettingsLocked();
1916            }
1917        }
1918        @Override
1919        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1920            synchronized (mPackages) {
1921                for (int userId : updatedUserIds) {
1922                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1923                }
1924            }
1925        }
1926        @Override
1927        public void onInstallPermissionUpdated() {
1928            synchronized (mPackages) {
1929                scheduleWriteSettingsLocked();
1930            }
1931        }
1932        @Override
1933        public void onPermissionRemoved() {
1934            synchronized (mPackages) {
1935                mSettings.writeLPr();
1936            }
1937        }
1938    };
1939
1940    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1941            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1942            boolean launchedForRestore, String installerPackage,
1943            IPackageInstallObserver2 installObserver) {
1944        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1945            // Send the removed broadcasts
1946            if (res.removedInfo != null) {
1947                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1948            }
1949
1950            // Now that we successfully installed the package, grant runtime
1951            // permissions if requested before broadcasting the install. Also
1952            // for legacy apps in permission review mode we clear the permission
1953            // review flag which is used to emulate runtime permissions for
1954            // legacy apps.
1955            if (grantPermissions) {
1956                final int callingUid = Binder.getCallingUid();
1957                mPermissionManager.grantRequestedRuntimePermissions(
1958                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1959                        mPermissionCallback);
1960            }
1961
1962            final boolean update = res.removedInfo != null
1963                    && res.removedInfo.removedPackage != null;
1964            final String installerPackageName =
1965                    res.installerPackageName != null
1966                            ? res.installerPackageName
1967                            : res.removedInfo != null
1968                                    ? res.removedInfo.installerPackageName
1969                                    : null;
1970
1971            // If this is the first time we have child packages for a disabled privileged
1972            // app that had no children, we grant requested runtime permissions to the new
1973            // children if the parent on the system image had them already granted.
1974            if (res.pkg.parentPackage != null) {
1975                final int callingUid = Binder.getCallingUid();
1976                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1977                        res.pkg, callingUid, mPermissionCallback);
1978            }
1979
1980            synchronized (mPackages) {
1981                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1982            }
1983
1984            final String packageName = res.pkg.applicationInfo.packageName;
1985
1986            // Determine the set of users who are adding this package for
1987            // the first time vs. those who are seeing an update.
1988            int[] firstUserIds = EMPTY_INT_ARRAY;
1989            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
1990            int[] updateUserIds = EMPTY_INT_ARRAY;
1991            int[] instantUserIds = EMPTY_INT_ARRAY;
1992            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1993            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1994            for (int newUser : res.newUsers) {
1995                final boolean isInstantApp = ps.getInstantApp(newUser);
1996                if (allNewUsers) {
1997                    if (isInstantApp) {
1998                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
1999                    } else {
2000                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2001                    }
2002                    continue;
2003                }
2004                boolean isNew = true;
2005                for (int origUser : res.origUsers) {
2006                    if (origUser == newUser) {
2007                        isNew = false;
2008                        break;
2009                    }
2010                }
2011                if (isNew) {
2012                    if (isInstantApp) {
2013                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2014                    } else {
2015                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2016                    }
2017                } else {
2018                    if (isInstantApp) {
2019                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2020                    } else {
2021                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2022                    }
2023                }
2024            }
2025
2026            // Send installed broadcasts if the package is not a static shared lib.
2027            if (res.pkg.staticSharedLibName == null) {
2028                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2029
2030                // Send added for users that see the package for the first time
2031                // sendPackageAddedForNewUsers also deals with system apps
2032                int appId = UserHandle.getAppId(res.uid);
2033                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2034                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2035                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2036
2037                // Send added for users that don't see the package for the first time
2038                Bundle extras = new Bundle(1);
2039                extras.putInt(Intent.EXTRA_UID, res.uid);
2040                if (update) {
2041                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2042                }
2043                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2044                        extras, 0 /*flags*/,
2045                        null /*targetPackage*/, null /*finishedReceiver*/,
2046                        updateUserIds, instantUserIds);
2047                if (installerPackageName != null) {
2048                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2049                            extras, 0 /*flags*/,
2050                            installerPackageName, null /*finishedReceiver*/,
2051                            updateUserIds, instantUserIds);
2052                }
2053
2054                // Send replaced for users that don't see the package for the first time
2055                if (update) {
2056                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2057                            packageName, extras, 0 /*flags*/,
2058                            null /*targetPackage*/, null /*finishedReceiver*/,
2059                            updateUserIds, instantUserIds);
2060                    if (installerPackageName != null) {
2061                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2062                                extras, 0 /*flags*/,
2063                                installerPackageName, null /*finishedReceiver*/,
2064                                updateUserIds, instantUserIds);
2065                    }
2066                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2067                            null /*package*/, null /*extras*/, 0 /*flags*/,
2068                            packageName /*targetPackage*/,
2069                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2070                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2071                    // First-install and we did a restore, so we're responsible for the
2072                    // first-launch broadcast.
2073                    if (DEBUG_BACKUP) {
2074                        Slog.i(TAG, "Post-restore of " + packageName
2075                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2076                    }
2077                    sendFirstLaunchBroadcast(packageName, installerPackage,
2078                            firstUserIds, firstInstantUserIds);
2079                }
2080
2081                // Send broadcast package appeared if forward locked/external for all users
2082                // treat asec-hosted packages like removable media on upgrade
2083                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2084                    if (DEBUG_INSTALL) {
2085                        Slog.i(TAG, "upgrading pkg " + res.pkg
2086                                + " is ASEC-hosted -> AVAILABLE");
2087                    }
2088                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2089                    ArrayList<String> pkgList = new ArrayList<>(1);
2090                    pkgList.add(packageName);
2091                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2092                }
2093            }
2094
2095            // Work that needs to happen on first install within each user
2096            if (firstUserIds != null && firstUserIds.length > 0) {
2097                synchronized (mPackages) {
2098                    for (int userId : firstUserIds) {
2099                        // If this app is a browser and it's newly-installed for some
2100                        // users, clear any default-browser state in those users. The
2101                        // app's nature doesn't depend on the user, so we can just check
2102                        // its browser nature in any user and generalize.
2103                        if (packageIsBrowser(packageName, userId)) {
2104                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2105                        }
2106
2107                        // We may also need to apply pending (restored) runtime
2108                        // permission grants within these users.
2109                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2110                    }
2111                }
2112            }
2113
2114            if (allNewUsers && !update) {
2115                notifyPackageAdded(packageName);
2116            }
2117
2118            // Log current value of "unknown sources" setting
2119            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2120                    getUnknownSourcesSettings());
2121
2122            // Remove the replaced package's older resources safely now
2123            // We delete after a gc for applications  on sdcard.
2124            if (res.removedInfo != null && res.removedInfo.args != null) {
2125                Runtime.getRuntime().gc();
2126                synchronized (mInstallLock) {
2127                    res.removedInfo.args.doPostDeleteLI(true);
2128                }
2129            } else {
2130                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2131                // and not block here.
2132                VMRuntime.getRuntime().requestConcurrentGC();
2133            }
2134
2135            // Notify DexManager that the package was installed for new users.
2136            // The updated users should already be indexed and the package code paths
2137            // should not change.
2138            // Don't notify the manager for ephemeral apps as they are not expected to
2139            // survive long enough to benefit of background optimizations.
2140            for (int userId : firstUserIds) {
2141                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2142                // There's a race currently where some install events may interleave with an uninstall.
2143                // This can lead to package info being null (b/36642664).
2144                if (info != null) {
2145                    mDexManager.notifyPackageInstalled(info, userId);
2146                }
2147            }
2148        }
2149
2150        // If someone is watching installs - notify them
2151        if (installObserver != null) {
2152            try {
2153                Bundle extras = extrasForInstallResult(res);
2154                installObserver.onPackageInstalled(res.name, res.returnCode,
2155                        res.returnMsg, extras);
2156            } catch (RemoteException e) {
2157                Slog.i(TAG, "Observer no longer exists.");
2158            }
2159        }
2160    }
2161
2162    private StorageEventListener mStorageListener = new StorageEventListener() {
2163        @Override
2164        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2165            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2166                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2167                    final String volumeUuid = vol.getFsUuid();
2168
2169                    // Clean up any users or apps that were removed or recreated
2170                    // while this volume was missing
2171                    sUserManager.reconcileUsers(volumeUuid);
2172                    reconcileApps(volumeUuid);
2173
2174                    // Clean up any install sessions that expired or were
2175                    // cancelled while this volume was missing
2176                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2177
2178                    loadPrivatePackages(vol);
2179
2180                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2181                    unloadPrivatePackages(vol);
2182                }
2183            }
2184        }
2185
2186        @Override
2187        public void onVolumeForgotten(String fsUuid) {
2188            if (TextUtils.isEmpty(fsUuid)) {
2189                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2190                return;
2191            }
2192
2193            // Remove any apps installed on the forgotten volume
2194            synchronized (mPackages) {
2195                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2196                for (PackageSetting ps : packages) {
2197                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2198                    deletePackageVersioned(new VersionedPackage(ps.name,
2199                            PackageManager.VERSION_CODE_HIGHEST),
2200                            new LegacyPackageDeleteObserver(null).getBinder(),
2201                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2202                    // Try very hard to release any references to this package
2203                    // so we don't risk the system server being killed due to
2204                    // open FDs
2205                    AttributeCache.instance().removePackage(ps.name);
2206                }
2207
2208                mSettings.onVolumeForgotten(fsUuid);
2209                mSettings.writeLPr();
2210            }
2211        }
2212    };
2213
2214    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2215        Bundle extras = null;
2216        switch (res.returnCode) {
2217            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2218                extras = new Bundle();
2219                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2220                        res.origPermission);
2221                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2222                        res.origPackage);
2223                break;
2224            }
2225            case PackageManager.INSTALL_SUCCEEDED: {
2226                extras = new Bundle();
2227                extras.putBoolean(Intent.EXTRA_REPLACING,
2228                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2229                break;
2230            }
2231        }
2232        return extras;
2233    }
2234
2235    void scheduleWriteSettingsLocked() {
2236        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2237            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2238        }
2239    }
2240
2241    void scheduleWritePackageListLocked(int userId) {
2242        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2243            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2244            msg.arg1 = userId;
2245            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2246        }
2247    }
2248
2249    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2250        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2251        scheduleWritePackageRestrictionsLocked(userId);
2252    }
2253
2254    void scheduleWritePackageRestrictionsLocked(int userId) {
2255        final int[] userIds = (userId == UserHandle.USER_ALL)
2256                ? sUserManager.getUserIds() : new int[]{userId};
2257        for (int nextUserId : userIds) {
2258            if (!sUserManager.exists(nextUserId)) return;
2259            mDirtyUsers.add(nextUserId);
2260            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2261                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2262            }
2263        }
2264    }
2265
2266    public static PackageManagerService main(Context context, Installer installer,
2267            boolean factoryTest, boolean onlyCore) {
2268        // Self-check for initial settings.
2269        PackageManagerServiceCompilerMapping.checkProperties();
2270
2271        PackageManagerService m = new PackageManagerService(context, installer,
2272                factoryTest, onlyCore);
2273        m.enableSystemUserPackages();
2274        ServiceManager.addService("package", m);
2275        final PackageManagerNative pmn = m.new PackageManagerNative();
2276        ServiceManager.addService("package_native", pmn);
2277        return m;
2278    }
2279
2280    private void enableSystemUserPackages() {
2281        if (!UserManager.isSplitSystemUser()) {
2282            return;
2283        }
2284        // For system user, enable apps based on the following conditions:
2285        // - app is whitelisted or belong to one of these groups:
2286        //   -- system app which has no launcher icons
2287        //   -- system app which has INTERACT_ACROSS_USERS permission
2288        //   -- system IME app
2289        // - app is not in the blacklist
2290        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2291        Set<String> enableApps = new ArraySet<>();
2292        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2293                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2294                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2295        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2296        enableApps.addAll(wlApps);
2297        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2298                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2299        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2300        enableApps.removeAll(blApps);
2301        Log.i(TAG, "Applications installed for system user: " + enableApps);
2302        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2303                UserHandle.SYSTEM);
2304        final int allAppsSize = allAps.size();
2305        synchronized (mPackages) {
2306            for (int i = 0; i < allAppsSize; i++) {
2307                String pName = allAps.get(i);
2308                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2309                // Should not happen, but we shouldn't be failing if it does
2310                if (pkgSetting == null) {
2311                    continue;
2312                }
2313                boolean install = enableApps.contains(pName);
2314                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2315                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2316                            + " for system user");
2317                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2318                }
2319            }
2320            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2321        }
2322    }
2323
2324    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2325        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2326                Context.DISPLAY_SERVICE);
2327        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2328    }
2329
2330    /**
2331     * Requests that files preopted on a secondary system partition be copied to the data partition
2332     * if possible.  Note that the actual copying of the files is accomplished by init for security
2333     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2334     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2335     */
2336    private static void requestCopyPreoptedFiles() {
2337        final int WAIT_TIME_MS = 100;
2338        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2339        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2340            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2341            // We will wait for up to 100 seconds.
2342            final long timeStart = SystemClock.uptimeMillis();
2343            final long timeEnd = timeStart + 100 * 1000;
2344            long timeNow = timeStart;
2345            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2346                try {
2347                    Thread.sleep(WAIT_TIME_MS);
2348                } catch (InterruptedException e) {
2349                    // Do nothing
2350                }
2351                timeNow = SystemClock.uptimeMillis();
2352                if (timeNow > timeEnd) {
2353                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2354                    Slog.wtf(TAG, "cppreopt did not finish!");
2355                    break;
2356                }
2357            }
2358
2359            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2360        }
2361    }
2362
2363    public PackageManagerService(Context context, Installer installer,
2364            boolean factoryTest, boolean onlyCore) {
2365        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2366        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2367        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2368                SystemClock.uptimeMillis());
2369
2370        if (mSdkVersion <= 0) {
2371            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2372        }
2373
2374        mContext = context;
2375
2376        mFactoryTest = factoryTest;
2377        mOnlyCore = onlyCore;
2378        mMetrics = new DisplayMetrics();
2379        mInstaller = installer;
2380
2381        // Create sub-components that provide services / data. Order here is important.
2382        synchronized (mInstallLock) {
2383        synchronized (mPackages) {
2384            // Expose private service for system components to use.
2385            LocalServices.addService(
2386                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2387            sUserManager = new UserManagerService(context, this,
2388                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2389            mPermissionManager = PermissionManagerService.create(context,
2390                    new DefaultPermissionGrantedCallback() {
2391                        @Override
2392                        public void onDefaultRuntimePermissionsGranted(int userId) {
2393                            synchronized(mPackages) {
2394                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2395                            }
2396                        }
2397                    }, mPackages /*externalLock*/);
2398            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2399            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2400        }
2401        }
2402        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2403                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2404        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2405                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2406        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2407                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2408        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2409                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2410        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2411                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2412        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2413                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2414        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2415                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2416
2417        String separateProcesses = SystemProperties.get("debug.separate_processes");
2418        if (separateProcesses != null && separateProcesses.length() > 0) {
2419            if ("*".equals(separateProcesses)) {
2420                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2421                mSeparateProcesses = null;
2422                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2423            } else {
2424                mDefParseFlags = 0;
2425                mSeparateProcesses = separateProcesses.split(",");
2426                Slog.w(TAG, "Running with debug.separate_processes: "
2427                        + separateProcesses);
2428            }
2429        } else {
2430            mDefParseFlags = 0;
2431            mSeparateProcesses = null;
2432        }
2433
2434        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2435                "*dexopt*");
2436        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2437                installer, mInstallLock);
2438        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2439                dexManagerListener);
2440        mArtManagerService = new ArtManagerService(this, installer, mInstallLock);
2441        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2442
2443        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2444                FgThread.get().getLooper());
2445
2446        getDefaultDisplayMetrics(context, mMetrics);
2447
2448        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2449        SystemConfig systemConfig = SystemConfig.getInstance();
2450        mAvailableFeatures = systemConfig.getAvailableFeatures();
2451        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2452
2453        mProtectedPackages = new ProtectedPackages(mContext);
2454
2455        synchronized (mInstallLock) {
2456        // writer
2457        synchronized (mPackages) {
2458            mHandlerThread = new ServiceThread(TAG,
2459                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2460            mHandlerThread.start();
2461            mHandler = new PackageHandler(mHandlerThread.getLooper());
2462            mProcessLoggingHandler = new ProcessLoggingHandler();
2463            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2464            mInstantAppRegistry = new InstantAppRegistry(this);
2465
2466            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2467            final int builtInLibCount = libConfig.size();
2468            for (int i = 0; i < builtInLibCount; i++) {
2469                String name = libConfig.keyAt(i);
2470                String path = libConfig.valueAt(i);
2471                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2472                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2473            }
2474
2475            SELinuxMMAC.readInstallPolicy();
2476
2477            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2478            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2479            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2480
2481            // Clean up orphaned packages for which the code path doesn't exist
2482            // and they are an update to a system app - caused by bug/32321269
2483            final int packageSettingCount = mSettings.mPackages.size();
2484            for (int i = packageSettingCount - 1; i >= 0; i--) {
2485                PackageSetting ps = mSettings.mPackages.valueAt(i);
2486                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2487                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2488                    mSettings.mPackages.removeAt(i);
2489                    mSettings.enableSystemPackageLPw(ps.name);
2490                }
2491            }
2492
2493            if (mFirstBoot) {
2494                requestCopyPreoptedFiles();
2495            }
2496
2497            String customResolverActivity = Resources.getSystem().getString(
2498                    R.string.config_customResolverActivity);
2499            if (TextUtils.isEmpty(customResolverActivity)) {
2500                customResolverActivity = null;
2501            } else {
2502                mCustomResolverComponentName = ComponentName.unflattenFromString(
2503                        customResolverActivity);
2504            }
2505
2506            long startTime = SystemClock.uptimeMillis();
2507
2508            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2509                    startTime);
2510
2511            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2512            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2513
2514            if (bootClassPath == null) {
2515                Slog.w(TAG, "No BOOTCLASSPATH found!");
2516            }
2517
2518            if (systemServerClassPath == null) {
2519                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2520            }
2521
2522            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2523
2524            final VersionInfo ver = mSettings.getInternalVersion();
2525            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2526            if (mIsUpgrade) {
2527                logCriticalInfo(Log.INFO,
2528                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2529            }
2530
2531            // when upgrading from pre-M, promote system app permissions from install to runtime
2532            mPromoteSystemApps =
2533                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2534
2535            // When upgrading from pre-N, we need to handle package extraction like first boot,
2536            // as there is no profiling data available.
2537            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2538
2539            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2540
2541            // save off the names of pre-existing system packages prior to scanning; we don't
2542            // want to automatically grant runtime permissions for new system apps
2543            if (mPromoteSystemApps) {
2544                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2545                while (pkgSettingIter.hasNext()) {
2546                    PackageSetting ps = pkgSettingIter.next();
2547                    if (isSystemApp(ps)) {
2548                        mExistingSystemPackages.add(ps.name);
2549                    }
2550                }
2551            }
2552
2553            mCacheDir = preparePackageParserCache(mIsUpgrade);
2554
2555            // Set flag to monitor and not change apk file paths when
2556            // scanning install directories.
2557            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2558
2559            if (mIsUpgrade || mFirstBoot) {
2560                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2561            }
2562
2563            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2564            // For security and version matching reason, only consider
2565            // overlay packages if they reside in the right directory.
2566            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2567                    mDefParseFlags
2568                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2569                    scanFlags
2570                    | SCAN_AS_SYSTEM
2571                    | SCAN_AS_VENDOR,
2572                    0);
2573            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2574                    mDefParseFlags
2575                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2576                    scanFlags
2577                    | SCAN_AS_SYSTEM
2578                    | SCAN_AS_PRODUCT,
2579                    0);
2580
2581            mParallelPackageParserCallback.findStaticOverlayPackages();
2582
2583            // Find base frameworks (resource packages without code).
2584            scanDirTracedLI(frameworkDir,
2585                    mDefParseFlags
2586                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2587                    scanFlags
2588                    | SCAN_NO_DEX
2589                    | SCAN_AS_SYSTEM
2590                    | SCAN_AS_PRIVILEGED,
2591                    0);
2592
2593            // Collected privileged system packages.
2594            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2595            scanDirTracedLI(privilegedAppDir,
2596                    mDefParseFlags
2597                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2598                    scanFlags
2599                    | SCAN_AS_SYSTEM
2600                    | SCAN_AS_PRIVILEGED,
2601                    0);
2602
2603            // Collect ordinary system packages.
2604            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2605            scanDirTracedLI(systemAppDir,
2606                    mDefParseFlags
2607                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2608                    scanFlags
2609                    | SCAN_AS_SYSTEM,
2610                    0);
2611
2612            // Collected privileged vendor packages.
2613            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2614            try {
2615                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2616            } catch (IOException e) {
2617                // failed to look up canonical path, continue with original one
2618            }
2619            scanDirTracedLI(privilegedVendorAppDir,
2620                    mDefParseFlags
2621                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2622                    scanFlags
2623                    | SCAN_AS_SYSTEM
2624                    | SCAN_AS_VENDOR
2625                    | SCAN_AS_PRIVILEGED,
2626                    0);
2627
2628            // Collect ordinary vendor packages.
2629            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2630            try {
2631                vendorAppDir = vendorAppDir.getCanonicalFile();
2632            } catch (IOException e) {
2633                // failed to look up canonical path, continue with original one
2634            }
2635            scanDirTracedLI(vendorAppDir,
2636                    mDefParseFlags
2637                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2638                    scanFlags
2639                    | SCAN_AS_SYSTEM
2640                    | SCAN_AS_VENDOR,
2641                    0);
2642
2643            // Collect all OEM packages.
2644            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2645            scanDirTracedLI(oemAppDir,
2646                    mDefParseFlags
2647                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2648                    scanFlags
2649                    | SCAN_AS_SYSTEM
2650                    | SCAN_AS_OEM,
2651                    0);
2652
2653            // Collected privileged product packages.
2654            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2655            try {
2656                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2657            } catch (IOException e) {
2658                // failed to look up canonical path, continue with original one
2659            }
2660            scanDirTracedLI(privilegedProductAppDir,
2661                    mDefParseFlags
2662                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2663                    scanFlags
2664                    | SCAN_AS_SYSTEM
2665                    | SCAN_AS_PRODUCT
2666                    | SCAN_AS_PRIVILEGED,
2667                    0);
2668
2669            // Collect ordinary product packages.
2670            File productAppDir = new File(Environment.getProductDirectory(), "app");
2671            try {
2672                productAppDir = productAppDir.getCanonicalFile();
2673            } catch (IOException e) {
2674                // failed to look up canonical path, continue with original one
2675            }
2676            scanDirTracedLI(productAppDir,
2677                    mDefParseFlags
2678                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2679                    scanFlags
2680                    | SCAN_AS_SYSTEM
2681                    | SCAN_AS_PRODUCT,
2682                    0);
2683
2684            // Prune any system packages that no longer exist.
2685            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2686            // Stub packages must either be replaced with full versions in the /data
2687            // partition or be disabled.
2688            final List<String> stubSystemApps = new ArrayList<>();
2689            if (!mOnlyCore) {
2690                // do this first before mucking with mPackages for the "expecting better" case
2691                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2692                while (pkgIterator.hasNext()) {
2693                    final PackageParser.Package pkg = pkgIterator.next();
2694                    if (pkg.isStub) {
2695                        stubSystemApps.add(pkg.packageName);
2696                    }
2697                }
2698
2699                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2700                while (psit.hasNext()) {
2701                    PackageSetting ps = psit.next();
2702
2703                    /*
2704                     * If this is not a system app, it can't be a
2705                     * disable system app.
2706                     */
2707                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2708                        continue;
2709                    }
2710
2711                    /*
2712                     * If the package is scanned, it's not erased.
2713                     */
2714                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2715                    if (scannedPkg != null) {
2716                        /*
2717                         * If the system app is both scanned and in the
2718                         * disabled packages list, then it must have been
2719                         * added via OTA. Remove it from the currently
2720                         * scanned package so the previously user-installed
2721                         * application can be scanned.
2722                         */
2723                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2724                            logCriticalInfo(Log.WARN,
2725                                    "Expecting better updated system app for " + ps.name
2726                                    + "; removing system app.  Last known"
2727                                    + " codePath=" + ps.codePathString
2728                                    + ", versionCode=" + ps.versionCode
2729                                    + "; scanned versionCode=" + scannedPkg.getLongVersionCode());
2730                            removePackageLI(scannedPkg, true);
2731                            mExpectingBetter.put(ps.name, ps.codePath);
2732                        }
2733
2734                        continue;
2735                    }
2736
2737                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2738                        psit.remove();
2739                        logCriticalInfo(Log.WARN, "System package " + ps.name
2740                                + " no longer exists; it's data will be wiped");
2741                        // Actual deletion of code and data will be handled by later
2742                        // reconciliation step
2743                    } else {
2744                        // we still have a disabled system package, but, it still might have
2745                        // been removed. check the code path still exists and check there's
2746                        // still a package. the latter can happen if an OTA keeps the same
2747                        // code path, but, changes the package name.
2748                        final PackageSetting disabledPs =
2749                                mSettings.getDisabledSystemPkgLPr(ps.name);
2750                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2751                                || disabledPs.pkg == null) {
2752                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2753                        }
2754                    }
2755                }
2756            }
2757
2758            //delete tmp files
2759            deleteTempPackageFiles();
2760
2761            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2762
2763            // Remove any shared userIDs that have no associated packages
2764            mSettings.pruneSharedUsersLPw();
2765            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2766            final int systemPackagesCount = mPackages.size();
2767            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2768                    + " ms, packageCount: " + systemPackagesCount
2769                    + " , timePerPackage: "
2770                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2771                    + " , cached: " + cachedSystemApps);
2772            if (mIsUpgrade && systemPackagesCount > 0) {
2773                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2774                        ((int) systemScanTime) / systemPackagesCount);
2775            }
2776            if (!mOnlyCore) {
2777                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2778                        SystemClock.uptimeMillis());
2779                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2780
2781                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2782                        | PackageParser.PARSE_FORWARD_LOCK,
2783                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2784
2785                // Remove disable package settings for updated system apps that were
2786                // removed via an OTA. If the update is no longer present, remove the
2787                // app completely. Otherwise, revoke their system privileges.
2788                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2789                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2790                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2791                    final String msg;
2792                    if (deletedPkg == null) {
2793                        // should have found an update, but, we didn't; remove everything
2794                        msg = "Updated system package " + deletedAppName
2795                                + " no longer exists; removing its data";
2796                        // Actual deletion of code and data will be handled by later
2797                        // reconciliation step
2798                    } else {
2799                        // found an update; revoke system privileges
2800                        msg = "Updated system package + " + deletedAppName
2801                                + " no longer exists; revoking system privileges";
2802
2803                        // Don't do anything if a stub is removed from the system image. If
2804                        // we were to remove the uncompressed version from the /data partition,
2805                        // this is where it'd be done.
2806
2807                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2808                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2809                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2810                    }
2811                    logCriticalInfo(Log.WARN, msg);
2812                }
2813
2814                /*
2815                 * Make sure all system apps that we expected to appear on
2816                 * the userdata partition actually showed up. If they never
2817                 * appeared, crawl back and revive the system version.
2818                 */
2819                for (int i = 0; i < mExpectingBetter.size(); i++) {
2820                    final String packageName = mExpectingBetter.keyAt(i);
2821                    if (!mPackages.containsKey(packageName)) {
2822                        final File scanFile = mExpectingBetter.valueAt(i);
2823
2824                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2825                                + " but never showed up; reverting to system");
2826
2827                        final @ParseFlags int reparseFlags;
2828                        final @ScanFlags int rescanFlags;
2829                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2830                            reparseFlags =
2831                                    mDefParseFlags |
2832                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2833                            rescanFlags =
2834                                    scanFlags
2835                                    | SCAN_AS_SYSTEM
2836                                    | SCAN_AS_PRIVILEGED;
2837                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2838                            reparseFlags =
2839                                    mDefParseFlags |
2840                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2841                            rescanFlags =
2842                                    scanFlags
2843                                    | SCAN_AS_SYSTEM;
2844                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)) {
2845                            reparseFlags =
2846                                    mDefParseFlags |
2847                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2848                            rescanFlags =
2849                                    scanFlags
2850                                    | SCAN_AS_SYSTEM
2851                                    | SCAN_AS_VENDOR
2852                                    | SCAN_AS_PRIVILEGED;
2853                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2854                            reparseFlags =
2855                                    mDefParseFlags |
2856                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2857                            rescanFlags =
2858                                    scanFlags
2859                                    | SCAN_AS_SYSTEM
2860                                    | SCAN_AS_VENDOR;
2861                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2862                            reparseFlags =
2863                                    mDefParseFlags |
2864                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2865                            rescanFlags =
2866                                    scanFlags
2867                                    | SCAN_AS_SYSTEM
2868                                    | SCAN_AS_OEM;
2869                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2870                            reparseFlags =
2871                                    mDefParseFlags |
2872                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2873                            rescanFlags =
2874                                    scanFlags
2875                                    | SCAN_AS_SYSTEM
2876                                    | SCAN_AS_PRODUCT
2877                                    | SCAN_AS_PRIVILEGED;
2878                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2879                            reparseFlags =
2880                                    mDefParseFlags |
2881                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2882                            rescanFlags =
2883                                    scanFlags
2884                                    | SCAN_AS_SYSTEM
2885                                    | SCAN_AS_PRODUCT;
2886                        } else {
2887                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2888                            continue;
2889                        }
2890
2891                        mSettings.enableSystemPackageLPw(packageName);
2892
2893                        try {
2894                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2895                        } catch (PackageManagerException e) {
2896                            Slog.e(TAG, "Failed to parse original system package: "
2897                                    + e.getMessage());
2898                        }
2899                    }
2900                }
2901
2902                // Uncompress and install any stubbed system applications.
2903                // This must be done last to ensure all stubs are replaced or disabled.
2904                decompressSystemApplications(stubSystemApps, scanFlags);
2905
2906                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2907                                - cachedSystemApps;
2908
2909                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2910                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2911                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2912                        + " ms, packageCount: " + dataPackagesCount
2913                        + " , timePerPackage: "
2914                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2915                        + " , cached: " + cachedNonSystemApps);
2916                if (mIsUpgrade && dataPackagesCount > 0) {
2917                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2918                            ((int) dataScanTime) / dataPackagesCount);
2919                }
2920            }
2921            mExpectingBetter.clear();
2922
2923            // Resolve the storage manager.
2924            mStorageManagerPackage = getStorageManagerPackageName();
2925
2926            // Resolve protected action filters. Only the setup wizard is allowed to
2927            // have a high priority filter for these actions.
2928            mSetupWizardPackage = getSetupWizardPackageName();
2929            if (mProtectedFilters.size() > 0) {
2930                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2931                    Slog.i(TAG, "No setup wizard;"
2932                        + " All protected intents capped to priority 0");
2933                }
2934                for (ActivityIntentInfo filter : mProtectedFilters) {
2935                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2936                        if (DEBUG_FILTERS) {
2937                            Slog.i(TAG, "Found setup wizard;"
2938                                + " allow priority " + filter.getPriority() + ";"
2939                                + " package: " + filter.activity.info.packageName
2940                                + " activity: " + filter.activity.className
2941                                + " priority: " + filter.getPriority());
2942                        }
2943                        // skip setup wizard; allow it to keep the high priority filter
2944                        continue;
2945                    }
2946                    if (DEBUG_FILTERS) {
2947                        Slog.i(TAG, "Protected action; cap priority to 0;"
2948                                + " package: " + filter.activity.info.packageName
2949                                + " activity: " + filter.activity.className
2950                                + " origPrio: " + filter.getPriority());
2951                    }
2952                    filter.setPriority(0);
2953                }
2954            }
2955            mDeferProtectedFilters = false;
2956            mProtectedFilters.clear();
2957
2958            // Now that we know all of the shared libraries, update all clients to have
2959            // the correct library paths.
2960            updateAllSharedLibrariesLPw(null);
2961
2962            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2963                // NOTE: We ignore potential failures here during a system scan (like
2964                // the rest of the commands above) because there's precious little we
2965                // can do about it. A settings error is reported, though.
2966                final List<String> changedAbiCodePath =
2967                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2968                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
2969                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
2970                        final String codePathString = changedAbiCodePath.get(i);
2971                        try {
2972                            mInstaller.rmdex(codePathString,
2973                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
2974                        } catch (InstallerException ignored) {
2975                        }
2976                    }
2977                }
2978            }
2979
2980            // Now that we know all the packages we are keeping,
2981            // read and update their last usage times.
2982            mPackageUsage.read(mPackages);
2983            mCompilerStats.read();
2984
2985            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2986                    SystemClock.uptimeMillis());
2987            Slog.i(TAG, "Time to scan packages: "
2988                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2989                    + " seconds");
2990
2991            // If the platform SDK has changed since the last time we booted,
2992            // we need to re-grant app permission to catch any new ones that
2993            // appear.  This is really a hack, and means that apps can in some
2994            // cases get permissions that the user didn't initially explicitly
2995            // allow...  it would be nice to have some better way to handle
2996            // this situation.
2997            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
2998            if (sdkUpdated) {
2999                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3000                        + mSdkVersion + "; regranting permissions for internal storage");
3001            }
3002            mPermissionManager.updateAllPermissions(
3003                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3004                    mPermissionCallback);
3005            ver.sdkVersion = mSdkVersion;
3006
3007            // If this is the first boot or an update from pre-M, and it is a normal
3008            // boot, then we need to initialize the default preferred apps across
3009            // all defined users.
3010            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3011                for (UserInfo user : sUserManager.getUsers(true)) {
3012                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3013                    applyFactoryDefaultBrowserLPw(user.id);
3014                    primeDomainVerificationsLPw(user.id);
3015                }
3016            }
3017
3018            // Prepare storage for system user really early during boot,
3019            // since core system apps like SettingsProvider and SystemUI
3020            // can't wait for user to start
3021            final int storageFlags;
3022            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3023                storageFlags = StorageManager.FLAG_STORAGE_DE;
3024            } else {
3025                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3026            }
3027            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3028                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3029                    true /* onlyCoreApps */);
3030            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3031                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3032                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3033                traceLog.traceBegin("AppDataFixup");
3034                try {
3035                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3036                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3037                } catch (InstallerException e) {
3038                    Slog.w(TAG, "Trouble fixing GIDs", e);
3039                }
3040                traceLog.traceEnd();
3041
3042                traceLog.traceBegin("AppDataPrepare");
3043                if (deferPackages == null || deferPackages.isEmpty()) {
3044                    return;
3045                }
3046                int count = 0;
3047                for (String pkgName : deferPackages) {
3048                    PackageParser.Package pkg = null;
3049                    synchronized (mPackages) {
3050                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3051                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3052                            pkg = ps.pkg;
3053                        }
3054                    }
3055                    if (pkg != null) {
3056                        synchronized (mInstallLock) {
3057                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3058                                    true /* maybeMigrateAppData */);
3059                        }
3060                        count++;
3061                    }
3062                }
3063                traceLog.traceEnd();
3064                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3065            }, "prepareAppData");
3066
3067            // If this is first boot after an OTA, and a normal boot, then
3068            // we need to clear code cache directories.
3069            // Note that we do *not* clear the application profiles. These remain valid
3070            // across OTAs and are used to drive profile verification (post OTA) and
3071            // profile compilation (without waiting to collect a fresh set of profiles).
3072            if (mIsUpgrade && !onlyCore) {
3073                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3074                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3075                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3076                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3077                        // No apps are running this early, so no need to freeze
3078                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3079                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3080                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3081                    }
3082                }
3083                ver.fingerprint = Build.FINGERPRINT;
3084            }
3085
3086            checkDefaultBrowser();
3087
3088            // clear only after permissions and other defaults have been updated
3089            mExistingSystemPackages.clear();
3090            mPromoteSystemApps = false;
3091
3092            // All the changes are done during package scanning.
3093            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3094
3095            // can downgrade to reader
3096            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3097            mSettings.writeLPr();
3098            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3099            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3100                    SystemClock.uptimeMillis());
3101
3102            if (!mOnlyCore) {
3103                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3104                mRequiredInstallerPackage = getRequiredInstallerLPr();
3105                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3106                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3107                if (mIntentFilterVerifierComponent != null) {
3108                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3109                            mIntentFilterVerifierComponent);
3110                } else {
3111                    mIntentFilterVerifier = null;
3112                }
3113                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3114                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3115                        SharedLibraryInfo.VERSION_UNDEFINED);
3116                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3117                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3118                        SharedLibraryInfo.VERSION_UNDEFINED);
3119            } else {
3120                mRequiredVerifierPackage = null;
3121                mRequiredInstallerPackage = null;
3122                mRequiredUninstallerPackage = null;
3123                mIntentFilterVerifierComponent = null;
3124                mIntentFilterVerifier = null;
3125                mServicesSystemSharedLibraryPackageName = null;
3126                mSharedSystemSharedLibraryPackageName = null;
3127            }
3128
3129            mInstallerService = new PackageInstallerService(context, this);
3130            final Pair<ComponentName, String> instantAppResolverComponent =
3131                    getInstantAppResolverLPr();
3132            if (instantAppResolverComponent != null) {
3133                if (DEBUG_INSTANT) {
3134                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3135                }
3136                mInstantAppResolverConnection = new InstantAppResolverConnection(
3137                        mContext, instantAppResolverComponent.first,
3138                        instantAppResolverComponent.second);
3139                mInstantAppResolverSettingsComponent =
3140                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3141            } else {
3142                mInstantAppResolverConnection = null;
3143                mInstantAppResolverSettingsComponent = null;
3144            }
3145            updateInstantAppInstallerLocked(null);
3146
3147            // Read and update the usage of dex files.
3148            // Do this at the end of PM init so that all the packages have their
3149            // data directory reconciled.
3150            // At this point we know the code paths of the packages, so we can validate
3151            // the disk file and build the internal cache.
3152            // The usage file is expected to be small so loading and verifying it
3153            // should take a fairly small time compare to the other activities (e.g. package
3154            // scanning).
3155            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3156            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3157            for (int userId : currentUserIds) {
3158                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3159            }
3160            mDexManager.load(userPackages);
3161            if (mIsUpgrade) {
3162                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3163                        (int) (SystemClock.uptimeMillis() - startTime));
3164            }
3165        } // synchronized (mPackages)
3166        } // synchronized (mInstallLock)
3167
3168        // Now after opening every single application zip, make sure they
3169        // are all flushed.  Not really needed, but keeps things nice and
3170        // tidy.
3171        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3172        Runtime.getRuntime().gc();
3173        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3174
3175        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3176        FallbackCategoryProvider.loadFallbacks();
3177        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3178
3179        // The initial scanning above does many calls into installd while
3180        // holding the mPackages lock, but we're mostly interested in yelling
3181        // once we have a booted system.
3182        mInstaller.setWarnIfHeld(mPackages);
3183
3184        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3185    }
3186
3187    /**
3188     * Uncompress and install stub applications.
3189     * <p>In order to save space on the system partition, some applications are shipped in a
3190     * compressed form. In addition the compressed bits for the full application, the
3191     * system image contains a tiny stub comprised of only the Android manifest.
3192     * <p>During the first boot, attempt to uncompress and install the full application. If
3193     * the application can't be installed for any reason, disable the stub and prevent
3194     * uncompressing the full application during future boots.
3195     * <p>In order to forcefully attempt an installation of a full application, go to app
3196     * settings and enable the application.
3197     */
3198    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3199        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3200            final String pkgName = stubSystemApps.get(i);
3201            // skip if the system package is already disabled
3202            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3203                stubSystemApps.remove(i);
3204                continue;
3205            }
3206            // skip if the package isn't installed (?!); this should never happen
3207            final PackageParser.Package pkg = mPackages.get(pkgName);
3208            if (pkg == null) {
3209                stubSystemApps.remove(i);
3210                continue;
3211            }
3212            // skip if the package has been disabled by the user
3213            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3214            if (ps != null) {
3215                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3216                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3217                    stubSystemApps.remove(i);
3218                    continue;
3219                }
3220            }
3221
3222            if (DEBUG_COMPRESSION) {
3223                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3224            }
3225
3226            // uncompress the binary to its eventual destination on /data
3227            final File scanFile = decompressPackage(pkg);
3228            if (scanFile == null) {
3229                continue;
3230            }
3231
3232            // install the package to replace the stub on /system
3233            try {
3234                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3235                removePackageLI(pkg, true /*chatty*/);
3236                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3237                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3238                        UserHandle.USER_SYSTEM, "android");
3239                stubSystemApps.remove(i);
3240                continue;
3241            } catch (PackageManagerException e) {
3242                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3243            }
3244
3245            // any failed attempt to install the package will be cleaned up later
3246        }
3247
3248        // disable any stub still left; these failed to install the full application
3249        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3250            final String pkgName = stubSystemApps.get(i);
3251            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3252            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3253                    UserHandle.USER_SYSTEM, "android");
3254            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3255        }
3256    }
3257
3258    /**
3259     * Decompresses the given package on the system image onto
3260     * the /data partition.
3261     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3262     */
3263    private File decompressPackage(PackageParser.Package pkg) {
3264        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3265        if (compressedFiles == null || compressedFiles.length == 0) {
3266            if (DEBUG_COMPRESSION) {
3267                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3268            }
3269            return null;
3270        }
3271        final File dstCodePath =
3272                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3273        int ret = PackageManager.INSTALL_SUCCEEDED;
3274        try {
3275            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3276            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3277            for (File srcFile : compressedFiles) {
3278                final String srcFileName = srcFile.getName();
3279                final String dstFileName = srcFileName.substring(
3280                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3281                final File dstFile = new File(dstCodePath, dstFileName);
3282                ret = decompressFile(srcFile, dstFile);
3283                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3284                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3285                            + "; pkg: " + pkg.packageName
3286                            + ", file: " + dstFileName);
3287                    break;
3288                }
3289            }
3290        } catch (ErrnoException e) {
3291            logCriticalInfo(Log.ERROR, "Failed to decompress"
3292                    + "; pkg: " + pkg.packageName
3293                    + ", err: " + e.errno);
3294        }
3295        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3296            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3297            NativeLibraryHelper.Handle handle = null;
3298            try {
3299                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3300                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3301                        null /*abiOverride*/);
3302            } catch (IOException e) {
3303                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3304                        + "; pkg: " + pkg.packageName);
3305                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3306            } finally {
3307                IoUtils.closeQuietly(handle);
3308            }
3309        }
3310        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3311            if (dstCodePath == null || !dstCodePath.exists()) {
3312                return null;
3313            }
3314            removeCodePathLI(dstCodePath);
3315            return null;
3316        }
3317
3318        return dstCodePath;
3319    }
3320
3321    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3322        // we're only interested in updating the installer appliction when 1) it's not
3323        // already set or 2) the modified package is the installer
3324        if (mInstantAppInstallerActivity != null
3325                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3326                        .equals(modifiedPackage)) {
3327            return;
3328        }
3329        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3330    }
3331
3332    private static File preparePackageParserCache(boolean isUpgrade) {
3333        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3334            return null;
3335        }
3336
3337        // Disable package parsing on eng builds to allow for faster incremental development.
3338        if (Build.IS_ENG) {
3339            return null;
3340        }
3341
3342        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3343            Slog.i(TAG, "Disabling package parser cache due to system property.");
3344            return null;
3345        }
3346
3347        // The base directory for the package parser cache lives under /data/system/.
3348        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3349                "package_cache");
3350        if (cacheBaseDir == null) {
3351            return null;
3352        }
3353
3354        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3355        // This also serves to "GC" unused entries when the package cache version changes (which
3356        // can only happen during upgrades).
3357        if (isUpgrade) {
3358            FileUtils.deleteContents(cacheBaseDir);
3359        }
3360
3361
3362        // Return the versioned package cache directory. This is something like
3363        // "/data/system/package_cache/1"
3364        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3365
3366        // The following is a workaround to aid development on non-numbered userdebug
3367        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3368        // the system partition is newer.
3369        //
3370        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3371        // that starts with "eng." to signify that this is an engineering build and not
3372        // destined for release.
3373        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3374            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3375
3376            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3377            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3378            // in general and should not be used for production changes. In this specific case,
3379            // we know that they will work.
3380            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3381            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3382                FileUtils.deleteContents(cacheBaseDir);
3383                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3384            }
3385        }
3386
3387        return cacheDir;
3388    }
3389
3390    @Override
3391    public boolean isFirstBoot() {
3392        // allow instant applications
3393        return mFirstBoot;
3394    }
3395
3396    @Override
3397    public boolean isOnlyCoreApps() {
3398        // allow instant applications
3399        return mOnlyCore;
3400    }
3401
3402    @Override
3403    public boolean isUpgrade() {
3404        // allow instant applications
3405        // The system property allows testing ota flow when upgraded to the same image.
3406        return mIsUpgrade || SystemProperties.getBoolean(
3407                "persist.pm.mock-upgrade", false /* default */);
3408    }
3409
3410    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3411        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3412
3413        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3414                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3415                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3416        if (matches.size() == 1) {
3417            return matches.get(0).getComponentInfo().packageName;
3418        } else if (matches.size() == 0) {
3419            Log.e(TAG, "There should probably be a verifier, but, none were found");
3420            return null;
3421        }
3422        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3423    }
3424
3425    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3426        synchronized (mPackages) {
3427            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3428            if (libraryEntry == null) {
3429                throw new IllegalStateException("Missing required shared library:" + name);
3430            }
3431            return libraryEntry.apk;
3432        }
3433    }
3434
3435    private @NonNull String getRequiredInstallerLPr() {
3436        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3437        intent.addCategory(Intent.CATEGORY_DEFAULT);
3438        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3439
3440        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3441                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3442                UserHandle.USER_SYSTEM);
3443        if (matches.size() == 1) {
3444            ResolveInfo resolveInfo = matches.get(0);
3445            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3446                throw new RuntimeException("The installer must be a privileged app");
3447            }
3448            return matches.get(0).getComponentInfo().packageName;
3449        } else {
3450            throw new RuntimeException("There must be exactly one installer; found " + matches);
3451        }
3452    }
3453
3454    private @NonNull String getRequiredUninstallerLPr() {
3455        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3456        intent.addCategory(Intent.CATEGORY_DEFAULT);
3457        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3458
3459        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3460                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3461                UserHandle.USER_SYSTEM);
3462        if (resolveInfo == null ||
3463                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3464            throw new RuntimeException("There must be exactly one uninstaller; found "
3465                    + resolveInfo);
3466        }
3467        return resolveInfo.getComponentInfo().packageName;
3468    }
3469
3470    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3471        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3472
3473        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3474                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3475                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3476        ResolveInfo best = null;
3477        final int N = matches.size();
3478        for (int i = 0; i < N; i++) {
3479            final ResolveInfo cur = matches.get(i);
3480            final String packageName = cur.getComponentInfo().packageName;
3481            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3482                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3483                continue;
3484            }
3485
3486            if (best == null || cur.priority > best.priority) {
3487                best = cur;
3488            }
3489        }
3490
3491        if (best != null) {
3492            return best.getComponentInfo().getComponentName();
3493        }
3494        Slog.w(TAG, "Intent filter verifier not found");
3495        return null;
3496    }
3497
3498    @Override
3499    public @Nullable ComponentName getInstantAppResolverComponent() {
3500        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3501            return null;
3502        }
3503        synchronized (mPackages) {
3504            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3505            if (instantAppResolver == null) {
3506                return null;
3507            }
3508            return instantAppResolver.first;
3509        }
3510    }
3511
3512    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3513        final String[] packageArray =
3514                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3515        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3516            if (DEBUG_INSTANT) {
3517                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3518            }
3519            return null;
3520        }
3521
3522        final int callingUid = Binder.getCallingUid();
3523        final int resolveFlags =
3524                MATCH_DIRECT_BOOT_AWARE
3525                | MATCH_DIRECT_BOOT_UNAWARE
3526                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3527        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3528        final Intent resolverIntent = new Intent(actionName);
3529        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3530                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3531        final int N = resolvers.size();
3532        if (N == 0) {
3533            if (DEBUG_INSTANT) {
3534                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3535            }
3536            return null;
3537        }
3538
3539        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3540        for (int i = 0; i < N; i++) {
3541            final ResolveInfo info = resolvers.get(i);
3542
3543            if (info.serviceInfo == null) {
3544                continue;
3545            }
3546
3547            final String packageName = info.serviceInfo.packageName;
3548            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3549                if (DEBUG_INSTANT) {
3550                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3551                            + " pkg: " + packageName + ", info:" + info);
3552                }
3553                continue;
3554            }
3555
3556            if (DEBUG_INSTANT) {
3557                Slog.v(TAG, "Ephemeral resolver found;"
3558                        + " pkg: " + packageName + ", info:" + info);
3559            }
3560            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3561        }
3562        if (DEBUG_INSTANT) {
3563            Slog.v(TAG, "Ephemeral resolver NOT found");
3564        }
3565        return null;
3566    }
3567
3568    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3569        String[] orderedActions = Build.IS_ENG
3570                ? new String[]{
3571                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3572                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3573                : new String[]{
3574                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3575
3576        final int resolveFlags =
3577                MATCH_DIRECT_BOOT_AWARE
3578                        | MATCH_DIRECT_BOOT_UNAWARE
3579                        | Intent.FLAG_IGNORE_EPHEMERAL
3580                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3581        final Intent intent = new Intent();
3582        intent.addCategory(Intent.CATEGORY_DEFAULT);
3583        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3584        List<ResolveInfo> matches = null;
3585        for (String action : orderedActions) {
3586            intent.setAction(action);
3587            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3588                    resolveFlags, UserHandle.USER_SYSTEM);
3589            if (matches.isEmpty()) {
3590                if (DEBUG_INSTANT) {
3591                    Slog.d(TAG, "Instant App installer not found with " + action);
3592                }
3593            } else {
3594                break;
3595            }
3596        }
3597        Iterator<ResolveInfo> iter = matches.iterator();
3598        while (iter.hasNext()) {
3599            final ResolveInfo rInfo = iter.next();
3600            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3601            if (ps != null) {
3602                final PermissionsState permissionsState = ps.getPermissionsState();
3603                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3604                        || Build.IS_ENG) {
3605                    continue;
3606                }
3607            }
3608            iter.remove();
3609        }
3610        if (matches.size() == 0) {
3611            return null;
3612        } else if (matches.size() == 1) {
3613            return (ActivityInfo) matches.get(0).getComponentInfo();
3614        } else {
3615            throw new RuntimeException(
3616                    "There must be at most one ephemeral installer; found " + matches);
3617        }
3618    }
3619
3620    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3621            @NonNull ComponentName resolver) {
3622        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3623                .addCategory(Intent.CATEGORY_DEFAULT)
3624                .setPackage(resolver.getPackageName());
3625        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3626        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3627                UserHandle.USER_SYSTEM);
3628        if (matches.isEmpty()) {
3629            return null;
3630        }
3631        return matches.get(0).getComponentInfo().getComponentName();
3632    }
3633
3634    private void primeDomainVerificationsLPw(int userId) {
3635        if (DEBUG_DOMAIN_VERIFICATION) {
3636            Slog.d(TAG, "Priming domain verifications in user " + userId);
3637        }
3638
3639        SystemConfig systemConfig = SystemConfig.getInstance();
3640        ArraySet<String> packages = systemConfig.getLinkedApps();
3641
3642        for (String packageName : packages) {
3643            PackageParser.Package pkg = mPackages.get(packageName);
3644            if (pkg != null) {
3645                if (!pkg.isSystem()) {
3646                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3647                    continue;
3648                }
3649
3650                ArraySet<String> domains = null;
3651                for (PackageParser.Activity a : pkg.activities) {
3652                    for (ActivityIntentInfo filter : a.intents) {
3653                        if (hasValidDomains(filter)) {
3654                            if (domains == null) {
3655                                domains = new ArraySet<String>();
3656                            }
3657                            domains.addAll(filter.getHostsList());
3658                        }
3659                    }
3660                }
3661
3662                if (domains != null && domains.size() > 0) {
3663                    if (DEBUG_DOMAIN_VERIFICATION) {
3664                        Slog.v(TAG, "      + " + packageName);
3665                    }
3666                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3667                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3668                    // and then 'always' in the per-user state actually used for intent resolution.
3669                    final IntentFilterVerificationInfo ivi;
3670                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3671                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3672                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3673                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3674                } else {
3675                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3676                            + "' does not handle web links");
3677                }
3678            } else {
3679                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3680            }
3681        }
3682
3683        scheduleWritePackageRestrictionsLocked(userId);
3684        scheduleWriteSettingsLocked();
3685    }
3686
3687    private void applyFactoryDefaultBrowserLPw(int userId) {
3688        // The default browser app's package name is stored in a string resource,
3689        // with a product-specific overlay used for vendor customization.
3690        String browserPkg = mContext.getResources().getString(
3691                com.android.internal.R.string.default_browser);
3692        if (!TextUtils.isEmpty(browserPkg)) {
3693            // non-empty string => required to be a known package
3694            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3695            if (ps == null) {
3696                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3697                browserPkg = null;
3698            } else {
3699                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3700            }
3701        }
3702
3703        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3704        // default.  If there's more than one, just leave everything alone.
3705        if (browserPkg == null) {
3706            calculateDefaultBrowserLPw(userId);
3707        }
3708    }
3709
3710    private void calculateDefaultBrowserLPw(int userId) {
3711        List<String> allBrowsers = resolveAllBrowserApps(userId);
3712        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3713        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3714    }
3715
3716    private List<String> resolveAllBrowserApps(int userId) {
3717        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3718        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3719                PackageManager.MATCH_ALL, userId);
3720
3721        final int count = list.size();
3722        List<String> result = new ArrayList<String>(count);
3723        for (int i=0; i<count; i++) {
3724            ResolveInfo info = list.get(i);
3725            if (info.activityInfo == null
3726                    || !info.handleAllWebDataURI
3727                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3728                    || result.contains(info.activityInfo.packageName)) {
3729                continue;
3730            }
3731            result.add(info.activityInfo.packageName);
3732        }
3733
3734        return result;
3735    }
3736
3737    private boolean packageIsBrowser(String packageName, int userId) {
3738        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3739                PackageManager.MATCH_ALL, userId);
3740        final int N = list.size();
3741        for (int i = 0; i < N; i++) {
3742            ResolveInfo info = list.get(i);
3743            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3744                return true;
3745            }
3746        }
3747        return false;
3748    }
3749
3750    private void checkDefaultBrowser() {
3751        final int myUserId = UserHandle.myUserId();
3752        final String packageName = getDefaultBrowserPackageName(myUserId);
3753        if (packageName != null) {
3754            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3755            if (info == null) {
3756                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3757                synchronized (mPackages) {
3758                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3759                }
3760            }
3761        }
3762    }
3763
3764    @Override
3765    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3766            throws RemoteException {
3767        try {
3768            return super.onTransact(code, data, reply, flags);
3769        } catch (RuntimeException e) {
3770            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3771                Slog.wtf(TAG, "Package Manager Crash", e);
3772            }
3773            throw e;
3774        }
3775    }
3776
3777    static int[] appendInts(int[] cur, int[] add) {
3778        if (add == null) return cur;
3779        if (cur == null) return add;
3780        final int N = add.length;
3781        for (int i=0; i<N; i++) {
3782            cur = appendInt(cur, add[i]);
3783        }
3784        return cur;
3785    }
3786
3787    /**
3788     * Returns whether or not a full application can see an instant application.
3789     * <p>
3790     * Currently, there are three cases in which this can occur:
3791     * <ol>
3792     * <li>The calling application is a "special" process. Special processes
3793     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3794     * <li>The calling application has the permission
3795     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3796     * <li>The calling application is the default launcher on the
3797     *     system partition.</li>
3798     * </ol>
3799     */
3800    private boolean canViewInstantApps(int callingUid, int userId) {
3801        if (callingUid < Process.FIRST_APPLICATION_UID) {
3802            return true;
3803        }
3804        if (mContext.checkCallingOrSelfPermission(
3805                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3806            return true;
3807        }
3808        if (mContext.checkCallingOrSelfPermission(
3809                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3810            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3811            if (homeComponent != null
3812                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3813                return true;
3814            }
3815        }
3816        return false;
3817    }
3818
3819    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3820        if (!sUserManager.exists(userId)) return null;
3821        if (ps == null) {
3822            return null;
3823        }
3824        final int callingUid = Binder.getCallingUid();
3825        // Filter out ephemeral app metadata:
3826        //   * The system/shell/root can see metadata for any app
3827        //   * An installed app can see metadata for 1) other installed apps
3828        //     and 2) ephemeral apps that have explicitly interacted with it
3829        //   * Ephemeral apps can only see their own data and exposed installed apps
3830        //   * Holding a signature permission allows seeing instant apps
3831        if (filterAppAccessLPr(ps, callingUid, userId)) {
3832            return null;
3833        }
3834
3835        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3836                && ps.isSystem()) {
3837            flags |= MATCH_ANY_USER;
3838        }
3839
3840        final PackageUserState state = ps.readUserState(userId);
3841        PackageParser.Package p = ps.pkg;
3842        if (p != null) {
3843            final PermissionsState permissionsState = ps.getPermissionsState();
3844
3845            // Compute GIDs only if requested
3846            final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3847                    ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3848            // Compute granted permissions only if package has requested permissions
3849            final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3850                    ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3851
3852            PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3853                    ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3854
3855            if (packageInfo == null) {
3856                return null;
3857            }
3858
3859            packageInfo.packageName = packageInfo.applicationInfo.packageName =
3860                    resolveExternalPackageNameLPr(p);
3861
3862            return packageInfo;
3863        } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
3864            PackageInfo pi = new PackageInfo();
3865            pi.packageName = ps.name;
3866            pi.setLongVersionCode(ps.versionCode);
3867            pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
3868            pi.firstInstallTime = ps.firstInstallTime;
3869            pi.lastUpdateTime = ps.lastUpdateTime;
3870
3871            ApplicationInfo ai = new ApplicationInfo();
3872            ai.packageName = ps.name;
3873            ai.uid = UserHandle.getUid(userId, ps.appId);
3874            ai.primaryCpuAbi = ps.primaryCpuAbiString;
3875            ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
3876            ai.versionCode = ps.versionCode;
3877            ai.flags = ps.pkgFlags;
3878            ai.privateFlags = ps.pkgPrivateFlags;
3879            pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
3880
3881            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
3882                    + ps.name + "]. Provides a minimum info.");
3883            return pi;
3884        } else {
3885            return null;
3886        }
3887    }
3888
3889    @Override
3890    public void checkPackageStartable(String packageName, int userId) {
3891        final int callingUid = Binder.getCallingUid();
3892        if (getInstantAppPackageName(callingUid) != null) {
3893            throw new SecurityException("Instant applications don't have access to this method");
3894        }
3895        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3896        synchronized (mPackages) {
3897            final PackageSetting ps = mSettings.mPackages.get(packageName);
3898            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3899                throw new SecurityException("Package " + packageName + " was not found!");
3900            }
3901
3902            if (!ps.getInstalled(userId)) {
3903                throw new SecurityException(
3904                        "Package " + packageName + " was not installed for user " + userId + "!");
3905            }
3906
3907            if (mSafeMode && !ps.isSystem()) {
3908                throw new SecurityException("Package " + packageName + " not a system app!");
3909            }
3910
3911            if (mFrozenPackages.contains(packageName)) {
3912                throw new SecurityException("Package " + packageName + " is currently frozen!");
3913            }
3914
3915            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3916                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3917            }
3918        }
3919    }
3920
3921    @Override
3922    public boolean isPackageAvailable(String packageName, int userId) {
3923        if (!sUserManager.exists(userId)) return false;
3924        final int callingUid = Binder.getCallingUid();
3925        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3926                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3927        synchronized (mPackages) {
3928            PackageParser.Package p = mPackages.get(packageName);
3929            if (p != null) {
3930                final PackageSetting ps = (PackageSetting) p.mExtras;
3931                if (filterAppAccessLPr(ps, callingUid, userId)) {
3932                    return false;
3933                }
3934                if (ps != null) {
3935                    final PackageUserState state = ps.readUserState(userId);
3936                    if (state != null) {
3937                        return PackageParser.isAvailable(state);
3938                    }
3939                }
3940            }
3941        }
3942        return false;
3943    }
3944
3945    @Override
3946    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3947        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3948                flags, Binder.getCallingUid(), userId);
3949    }
3950
3951    @Override
3952    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3953            int flags, int userId) {
3954        return getPackageInfoInternal(versionedPackage.getPackageName(),
3955                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
3956    }
3957
3958    /**
3959     * Important: The provided filterCallingUid is used exclusively to filter out packages
3960     * that can be seen based on user state. It's typically the original caller uid prior
3961     * to clearing. Because it can only be provided by trusted code, it's value can be
3962     * trusted and will be used as-is; unlike userId which will be validated by this method.
3963     */
3964    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
3965            int flags, int filterCallingUid, int userId) {
3966        if (!sUserManager.exists(userId)) return null;
3967        flags = updateFlagsForPackage(flags, userId, packageName);
3968        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3969                false /* requireFullPermission */, false /* checkShell */, "get package info");
3970
3971        // reader
3972        synchronized (mPackages) {
3973            // Normalize package name to handle renamed packages and static libs
3974            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3975
3976            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3977            if (matchFactoryOnly) {
3978                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3979                if (ps != null) {
3980                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3981                        return null;
3982                    }
3983                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3984                        return null;
3985                    }
3986                    return generatePackageInfo(ps, flags, userId);
3987                }
3988            }
3989
3990            PackageParser.Package p = mPackages.get(packageName);
3991            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3992                return null;
3993            }
3994            if (DEBUG_PACKAGE_INFO)
3995                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3996            if (p != null) {
3997                final PackageSetting ps = (PackageSetting) p.mExtras;
3998                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3999                    return null;
4000                }
4001                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4002                    return null;
4003                }
4004                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4005            }
4006            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4007                final PackageSetting ps = mSettings.mPackages.get(packageName);
4008                if (ps == null) return null;
4009                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4010                    return null;
4011                }
4012                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4013                    return null;
4014                }
4015                return generatePackageInfo(ps, flags, userId);
4016            }
4017        }
4018        return null;
4019    }
4020
4021    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4022        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4023            return true;
4024        }
4025        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4026            return true;
4027        }
4028        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4029            return true;
4030        }
4031        return false;
4032    }
4033
4034    private boolean isComponentVisibleToInstantApp(
4035            @Nullable ComponentName component, @ComponentType int type) {
4036        if (type == TYPE_ACTIVITY) {
4037            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4038            return activity != null
4039                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4040                    : false;
4041        } else if (type == TYPE_RECEIVER) {
4042            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4043            return activity != null
4044                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4045                    : false;
4046        } else if (type == TYPE_SERVICE) {
4047            final PackageParser.Service service = mServices.mServices.get(component);
4048            return service != null
4049                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4050                    : false;
4051        } else if (type == TYPE_PROVIDER) {
4052            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4053            return provider != null
4054                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4055                    : false;
4056        } else if (type == TYPE_UNKNOWN) {
4057            return isComponentVisibleToInstantApp(component);
4058        }
4059        return false;
4060    }
4061
4062    /**
4063     * Returns whether or not access to the application should be filtered.
4064     * <p>
4065     * Access may be limited based upon whether the calling or target applications
4066     * are instant applications.
4067     *
4068     * @see #canAccessInstantApps(int)
4069     */
4070    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4071            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4072        // if we're in an isolated process, get the real calling UID
4073        if (Process.isIsolated(callingUid)) {
4074            callingUid = mIsolatedOwners.get(callingUid);
4075        }
4076        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4077        final boolean callerIsInstantApp = instantAppPkgName != null;
4078        if (ps == null) {
4079            if (callerIsInstantApp) {
4080                // pretend the application exists, but, needs to be filtered
4081                return true;
4082            }
4083            return false;
4084        }
4085        // if the target and caller are the same application, don't filter
4086        if (isCallerSameApp(ps.name, callingUid)) {
4087            return false;
4088        }
4089        if (callerIsInstantApp) {
4090            // request for a specific component; if it hasn't been explicitly exposed, filter
4091            if (component != null) {
4092                return !isComponentVisibleToInstantApp(component, componentType);
4093            }
4094            // request for application; if no components have been explicitly exposed, filter
4095            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4096        }
4097        if (ps.getInstantApp(userId)) {
4098            // caller can see all components of all instant applications, don't filter
4099            if (canViewInstantApps(callingUid, userId)) {
4100                return false;
4101            }
4102            // request for a specific instant application component, filter
4103            if (component != null) {
4104                return true;
4105            }
4106            // request for an instant application; if the caller hasn't been granted access, filter
4107            return !mInstantAppRegistry.isInstantAccessGranted(
4108                    userId, UserHandle.getAppId(callingUid), ps.appId);
4109        }
4110        return false;
4111    }
4112
4113    /**
4114     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4115     */
4116    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4117        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4118    }
4119
4120    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4121            int flags) {
4122        // Callers can access only the libs they depend on, otherwise they need to explicitly
4123        // ask for the shared libraries given the caller is allowed to access all static libs.
4124        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4125            // System/shell/root get to see all static libs
4126            final int appId = UserHandle.getAppId(uid);
4127            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4128                    || appId == Process.ROOT_UID) {
4129                return false;
4130            }
4131        }
4132
4133        // No package means no static lib as it is always on internal storage
4134        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4135            return false;
4136        }
4137
4138        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4139                ps.pkg.staticSharedLibVersion);
4140        if (libEntry == null) {
4141            return false;
4142        }
4143
4144        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4145        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4146        if (uidPackageNames == null) {
4147            return true;
4148        }
4149
4150        for (String uidPackageName : uidPackageNames) {
4151            if (ps.name.equals(uidPackageName)) {
4152                return false;
4153            }
4154            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4155            if (uidPs != null) {
4156                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4157                        libEntry.info.getName());
4158                if (index < 0) {
4159                    continue;
4160                }
4161                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4162                    return false;
4163                }
4164            }
4165        }
4166        return true;
4167    }
4168
4169    @Override
4170    public String[] currentToCanonicalPackageNames(String[] names) {
4171        final int callingUid = Binder.getCallingUid();
4172        if (getInstantAppPackageName(callingUid) != null) {
4173            return names;
4174        }
4175        final String[] out = new String[names.length];
4176        // reader
4177        synchronized (mPackages) {
4178            final int callingUserId = UserHandle.getUserId(callingUid);
4179            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4180            for (int i=names.length-1; i>=0; i--) {
4181                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4182                boolean translateName = false;
4183                if (ps != null && ps.realName != null) {
4184                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4185                    translateName = !targetIsInstantApp
4186                            || canViewInstantApps
4187                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4188                                    UserHandle.getAppId(callingUid), ps.appId);
4189                }
4190                out[i] = translateName ? ps.realName : names[i];
4191            }
4192        }
4193        return out;
4194    }
4195
4196    @Override
4197    public String[] canonicalToCurrentPackageNames(String[] names) {
4198        final int callingUid = Binder.getCallingUid();
4199        if (getInstantAppPackageName(callingUid) != null) {
4200            return names;
4201        }
4202        final String[] out = new String[names.length];
4203        // reader
4204        synchronized (mPackages) {
4205            final int callingUserId = UserHandle.getUserId(callingUid);
4206            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4207            for (int i=names.length-1; i>=0; i--) {
4208                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4209                boolean translateName = false;
4210                if (cur != null) {
4211                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4212                    final boolean targetIsInstantApp =
4213                            ps != null && ps.getInstantApp(callingUserId);
4214                    translateName = !targetIsInstantApp
4215                            || canViewInstantApps
4216                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4217                                    UserHandle.getAppId(callingUid), ps.appId);
4218                }
4219                out[i] = translateName ? cur : names[i];
4220            }
4221        }
4222        return out;
4223    }
4224
4225    @Override
4226    public int getPackageUid(String packageName, int flags, int userId) {
4227        if (!sUserManager.exists(userId)) return -1;
4228        final int callingUid = Binder.getCallingUid();
4229        flags = updateFlagsForPackage(flags, userId, packageName);
4230        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4231                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4232
4233        // reader
4234        synchronized (mPackages) {
4235            final PackageParser.Package p = mPackages.get(packageName);
4236            if (p != null && p.isMatch(flags)) {
4237                PackageSetting ps = (PackageSetting) p.mExtras;
4238                if (filterAppAccessLPr(ps, callingUid, userId)) {
4239                    return -1;
4240                }
4241                return UserHandle.getUid(userId, p.applicationInfo.uid);
4242            }
4243            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4244                final PackageSetting ps = mSettings.mPackages.get(packageName);
4245                if (ps != null && ps.isMatch(flags)
4246                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4247                    return UserHandle.getUid(userId, ps.appId);
4248                }
4249            }
4250        }
4251
4252        return -1;
4253    }
4254
4255    @Override
4256    public int[] getPackageGids(String packageName, int flags, int userId) {
4257        if (!sUserManager.exists(userId)) return null;
4258        final int callingUid = Binder.getCallingUid();
4259        flags = updateFlagsForPackage(flags, userId, packageName);
4260        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4261                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4262
4263        // reader
4264        synchronized (mPackages) {
4265            final PackageParser.Package p = mPackages.get(packageName);
4266            if (p != null && p.isMatch(flags)) {
4267                PackageSetting ps = (PackageSetting) p.mExtras;
4268                if (filterAppAccessLPr(ps, callingUid, userId)) {
4269                    return null;
4270                }
4271                // TODO: Shouldn't this be checking for package installed state for userId and
4272                // return null?
4273                return ps.getPermissionsState().computeGids(userId);
4274            }
4275            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4276                final PackageSetting ps = mSettings.mPackages.get(packageName);
4277                if (ps != null && ps.isMatch(flags)
4278                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4279                    return ps.getPermissionsState().computeGids(userId);
4280                }
4281            }
4282        }
4283
4284        return null;
4285    }
4286
4287    @Override
4288    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4289        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4290    }
4291
4292    @Override
4293    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4294            int flags) {
4295        final List<PermissionInfo> permissionList =
4296                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4297        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4298    }
4299
4300    @Override
4301    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4302        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4303    }
4304
4305    @Override
4306    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4307        final List<PermissionGroupInfo> permissionList =
4308                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4309        return (permissionList == null)
4310                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4311    }
4312
4313    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4314            int filterCallingUid, int userId) {
4315        if (!sUserManager.exists(userId)) return null;
4316        PackageSetting ps = mSettings.mPackages.get(packageName);
4317        if (ps != null) {
4318            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4319                return null;
4320            }
4321            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4322                return null;
4323            }
4324            if (ps.pkg == null) {
4325                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4326                if (pInfo != null) {
4327                    return pInfo.applicationInfo;
4328                }
4329                return null;
4330            }
4331            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4332                    ps.readUserState(userId), userId);
4333            if (ai != null) {
4334                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4335            }
4336            return ai;
4337        }
4338        return null;
4339    }
4340
4341    @Override
4342    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4343        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4344    }
4345
4346    /**
4347     * Important: The provided filterCallingUid is used exclusively to filter out applications
4348     * that can be seen based on user state. It's typically the original caller uid prior
4349     * to clearing. Because it can only be provided by trusted code, it's value can be
4350     * trusted and will be used as-is; unlike userId which will be validated by this method.
4351     */
4352    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4353            int filterCallingUid, int userId) {
4354        if (!sUserManager.exists(userId)) return null;
4355        flags = updateFlagsForApplication(flags, userId, packageName);
4356        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4357                false /* requireFullPermission */, false /* checkShell */, "get application info");
4358
4359        // writer
4360        synchronized (mPackages) {
4361            // Normalize package name to handle renamed packages and static libs
4362            packageName = resolveInternalPackageNameLPr(packageName,
4363                    PackageManager.VERSION_CODE_HIGHEST);
4364
4365            PackageParser.Package p = mPackages.get(packageName);
4366            if (DEBUG_PACKAGE_INFO) Log.v(
4367                    TAG, "getApplicationInfo " + packageName
4368                    + ": " + p);
4369            if (p != null) {
4370                PackageSetting ps = mSettings.mPackages.get(packageName);
4371                if (ps == null) return null;
4372                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4373                    return null;
4374                }
4375                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4376                    return null;
4377                }
4378                // Note: isEnabledLP() does not apply here - always return info
4379                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4380                        p, flags, ps.readUserState(userId), userId);
4381                if (ai != null) {
4382                    ai.packageName = resolveExternalPackageNameLPr(p);
4383                }
4384                return ai;
4385            }
4386            if ("android".equals(packageName)||"system".equals(packageName)) {
4387                return mAndroidApplication;
4388            }
4389            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4390                // Already generates the external package name
4391                return generateApplicationInfoFromSettingsLPw(packageName,
4392                        flags, filterCallingUid, userId);
4393            }
4394        }
4395        return null;
4396    }
4397
4398    private String normalizePackageNameLPr(String packageName) {
4399        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4400        return normalizedPackageName != null ? normalizedPackageName : packageName;
4401    }
4402
4403    @Override
4404    public void deletePreloadsFileCache() {
4405        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4406            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4407        }
4408        File dir = Environment.getDataPreloadsFileCacheDirectory();
4409        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4410        FileUtils.deleteContents(dir);
4411    }
4412
4413    @Override
4414    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4415            final int storageFlags, final IPackageDataObserver observer) {
4416        mContext.enforceCallingOrSelfPermission(
4417                android.Manifest.permission.CLEAR_APP_CACHE, null);
4418        mHandler.post(() -> {
4419            boolean success = false;
4420            try {
4421                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4422                success = true;
4423            } catch (IOException e) {
4424                Slog.w(TAG, e);
4425            }
4426            if (observer != null) {
4427                try {
4428                    observer.onRemoveCompleted(null, success);
4429                } catch (RemoteException e) {
4430                    Slog.w(TAG, e);
4431                }
4432            }
4433        });
4434    }
4435
4436    @Override
4437    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4438            final int storageFlags, final IntentSender pi) {
4439        mContext.enforceCallingOrSelfPermission(
4440                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4441        mHandler.post(() -> {
4442            boolean success = false;
4443            try {
4444                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4445                success = true;
4446            } catch (IOException e) {
4447                Slog.w(TAG, e);
4448            }
4449            if (pi != null) {
4450                try {
4451                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4452                } catch (SendIntentException e) {
4453                    Slog.w(TAG, e);
4454                }
4455            }
4456        });
4457    }
4458
4459    /**
4460     * Blocking call to clear various types of cached data across the system
4461     * until the requested bytes are available.
4462     */
4463    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4464        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4465        final File file = storage.findPathForUuid(volumeUuid);
4466        if (file.getUsableSpace() >= bytes) return;
4467
4468        if (ENABLE_FREE_CACHE_V2) {
4469            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4470                    volumeUuid);
4471            final boolean aggressive = (storageFlags
4472                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4473            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4474
4475            // 1. Pre-flight to determine if we have any chance to succeed
4476            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4477            if (internalVolume && (aggressive || SystemProperties
4478                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4479                deletePreloadsFileCache();
4480                if (file.getUsableSpace() >= bytes) return;
4481            }
4482
4483            // 3. Consider parsed APK data (aggressive only)
4484            if (internalVolume && aggressive) {
4485                FileUtils.deleteContents(mCacheDir);
4486                if (file.getUsableSpace() >= bytes) return;
4487            }
4488
4489            // 4. Consider cached app data (above quotas)
4490            try {
4491                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4492                        Installer.FLAG_FREE_CACHE_V2);
4493            } catch (InstallerException ignored) {
4494            }
4495            if (file.getUsableSpace() >= bytes) return;
4496
4497            // 5. Consider shared libraries with refcount=0 and age>min cache period
4498            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4499                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4500                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4501                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4502                return;
4503            }
4504
4505            // 6. Consider dexopt output (aggressive only)
4506            // TODO: Implement
4507
4508            // 7. Consider installed instant apps unused longer than min cache period
4509            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4510                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4511                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4512                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4513                return;
4514            }
4515
4516            // 8. Consider cached app data (below quotas)
4517            try {
4518                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4519                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4520            } catch (InstallerException ignored) {
4521            }
4522            if (file.getUsableSpace() >= bytes) return;
4523
4524            // 9. Consider DropBox entries
4525            // TODO: Implement
4526
4527            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4528            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4529                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4530                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4531                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4532                return;
4533            }
4534        } else {
4535            try {
4536                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4537            } catch (InstallerException ignored) {
4538            }
4539            if (file.getUsableSpace() >= bytes) return;
4540        }
4541
4542        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4543    }
4544
4545    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4546            throws IOException {
4547        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4548        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4549
4550        List<VersionedPackage> packagesToDelete = null;
4551        final long now = System.currentTimeMillis();
4552
4553        synchronized (mPackages) {
4554            final int[] allUsers = sUserManager.getUserIds();
4555            final int libCount = mSharedLibraries.size();
4556            for (int i = 0; i < libCount; i++) {
4557                final LongSparseArray<SharedLibraryEntry> versionedLib
4558                        = mSharedLibraries.valueAt(i);
4559                if (versionedLib == null) {
4560                    continue;
4561                }
4562                final int versionCount = versionedLib.size();
4563                for (int j = 0; j < versionCount; j++) {
4564                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4565                    // Skip packages that are not static shared libs.
4566                    if (!libInfo.isStatic()) {
4567                        break;
4568                    }
4569                    // Important: We skip static shared libs used for some user since
4570                    // in such a case we need to keep the APK on the device. The check for
4571                    // a lib being used for any user is performed by the uninstall call.
4572                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4573                    // Resolve the package name - we use synthetic package names internally
4574                    final String internalPackageName = resolveInternalPackageNameLPr(
4575                            declaringPackage.getPackageName(),
4576                            declaringPackage.getLongVersionCode());
4577                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4578                    // Skip unused static shared libs cached less than the min period
4579                    // to prevent pruning a lib needed by a subsequently installed package.
4580                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4581                        continue;
4582                    }
4583                    if (packagesToDelete == null) {
4584                        packagesToDelete = new ArrayList<>();
4585                    }
4586                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4587                            declaringPackage.getLongVersionCode()));
4588                }
4589            }
4590        }
4591
4592        if (packagesToDelete != null) {
4593            final int packageCount = packagesToDelete.size();
4594            for (int i = 0; i < packageCount; i++) {
4595                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4596                // Delete the package synchronously (will fail of the lib used for any user).
4597                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4598                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4599                                == PackageManager.DELETE_SUCCEEDED) {
4600                    if (volume.getUsableSpace() >= neededSpace) {
4601                        return true;
4602                    }
4603                }
4604            }
4605        }
4606
4607        return false;
4608    }
4609
4610    /**
4611     * Update given flags based on encryption status of current user.
4612     */
4613    private int updateFlags(int flags, int userId) {
4614        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4615                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4616            // Caller expressed an explicit opinion about what encryption
4617            // aware/unaware components they want to see, so fall through and
4618            // give them what they want
4619        } else {
4620            // Caller expressed no opinion, so match based on user state
4621            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4622                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4623            } else {
4624                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4625            }
4626        }
4627        return flags;
4628    }
4629
4630    private UserManagerInternal getUserManagerInternal() {
4631        if (mUserManagerInternal == null) {
4632            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4633        }
4634        return mUserManagerInternal;
4635    }
4636
4637    private ActivityManagerInternal getActivityManagerInternal() {
4638        if (mActivityManagerInternal == null) {
4639            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4640        }
4641        return mActivityManagerInternal;
4642    }
4643
4644
4645    private DeviceIdleController.LocalService getDeviceIdleController() {
4646        if (mDeviceIdleController == null) {
4647            mDeviceIdleController =
4648                    LocalServices.getService(DeviceIdleController.LocalService.class);
4649        }
4650        return mDeviceIdleController;
4651    }
4652
4653    /**
4654     * Update given flags when being used to request {@link PackageInfo}.
4655     */
4656    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4657        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4658        boolean triaged = true;
4659        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4660                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4661            // Caller is asking for component details, so they'd better be
4662            // asking for specific encryption matching behavior, or be triaged
4663            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4664                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4665                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4666                triaged = false;
4667            }
4668        }
4669        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4670                | PackageManager.MATCH_SYSTEM_ONLY
4671                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4672            triaged = false;
4673        }
4674        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4675            mPermissionManager.enforceCrossUserPermission(
4676                    Binder.getCallingUid(), userId, false, false,
4677                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4678                    + Debug.getCallers(5));
4679        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4680                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4681            // If the caller wants all packages and has a restricted profile associated with it,
4682            // then match all users. This is to make sure that launchers that need to access work
4683            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4684            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4685            flags |= PackageManager.MATCH_ANY_USER;
4686        }
4687        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4688            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4689                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4690        }
4691        return updateFlags(flags, userId);
4692    }
4693
4694    /**
4695     * Update given flags when being used to request {@link ApplicationInfo}.
4696     */
4697    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4698        return updateFlagsForPackage(flags, userId, cookie);
4699    }
4700
4701    /**
4702     * Update given flags when being used to request {@link ComponentInfo}.
4703     */
4704    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4705        if (cookie instanceof Intent) {
4706            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4707                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4708            }
4709        }
4710
4711        boolean triaged = true;
4712        // Caller is asking for component details, so they'd better be
4713        // asking for specific encryption matching behavior, or be triaged
4714        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4715                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4716                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4717            triaged = false;
4718        }
4719        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4720            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4721                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4722        }
4723
4724        return updateFlags(flags, userId);
4725    }
4726
4727    /**
4728     * Update given intent when being used to request {@link ResolveInfo}.
4729     */
4730    private Intent updateIntentForResolve(Intent intent) {
4731        if (intent.getSelector() != null) {
4732            intent = intent.getSelector();
4733        }
4734        if (DEBUG_PREFERRED) {
4735            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4736        }
4737        return intent;
4738    }
4739
4740    /**
4741     * Update given flags when being used to request {@link ResolveInfo}.
4742     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4743     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4744     * flag set. However, this flag is only honoured in three circumstances:
4745     * <ul>
4746     * <li>when called from a system process</li>
4747     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4748     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4749     * action and a {@code android.intent.category.BROWSABLE} category</li>
4750     * </ul>
4751     */
4752    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4753        return updateFlagsForResolve(flags, userId, intent, callingUid,
4754                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4755    }
4756    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4757            boolean wantInstantApps) {
4758        return updateFlagsForResolve(flags, userId, intent, callingUid,
4759                wantInstantApps, false /*onlyExposedExplicitly*/);
4760    }
4761    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4762            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4763        // Safe mode means we shouldn't match any third-party components
4764        if (mSafeMode) {
4765            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4766        }
4767        if (getInstantAppPackageName(callingUid) != null) {
4768            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4769            if (onlyExposedExplicitly) {
4770                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4771            }
4772            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4773            flags |= PackageManager.MATCH_INSTANT;
4774        } else {
4775            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4776            final boolean allowMatchInstant = wantInstantApps
4777                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4778            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4779                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4780            if (!allowMatchInstant) {
4781                flags &= ~PackageManager.MATCH_INSTANT;
4782            }
4783        }
4784        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4785    }
4786
4787    @Override
4788    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4789        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4790    }
4791
4792    /**
4793     * Important: The provided filterCallingUid is used exclusively to filter out activities
4794     * that can be seen based on user state. It's typically the original caller uid prior
4795     * to clearing. Because it can only be provided by trusted code, it's value can be
4796     * trusted and will be used as-is; unlike userId which will be validated by this method.
4797     */
4798    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4799            int filterCallingUid, int userId) {
4800        if (!sUserManager.exists(userId)) return null;
4801        flags = updateFlagsForComponent(flags, userId, component);
4802
4803        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4804            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4805                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4806        }
4807
4808        synchronized (mPackages) {
4809            PackageParser.Activity a = mActivities.mActivities.get(component);
4810
4811            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4812            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4813                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4814                if (ps == null) return null;
4815                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4816                    return null;
4817                }
4818                return PackageParser.generateActivityInfo(
4819                        a, flags, ps.readUserState(userId), userId);
4820            }
4821            if (mResolveComponentName.equals(component)) {
4822                return PackageParser.generateActivityInfo(
4823                        mResolveActivity, flags, new PackageUserState(), userId);
4824            }
4825        }
4826        return null;
4827    }
4828
4829    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4830        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4831            return false;
4832        }
4833        final long token = Binder.clearCallingIdentity();
4834        try {
4835            final int callingUserId = UserHandle.getUserId(callingUid);
4836            if (ActivityManager.getCurrentUser() != callingUserId) {
4837                return false;
4838            }
4839            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4840        } finally {
4841            Binder.restoreCallingIdentity(token);
4842        }
4843    }
4844
4845    @Override
4846    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4847            String resolvedType) {
4848        synchronized (mPackages) {
4849            if (component.equals(mResolveComponentName)) {
4850                // The resolver supports EVERYTHING!
4851                return true;
4852            }
4853            final int callingUid = Binder.getCallingUid();
4854            final int callingUserId = UserHandle.getUserId(callingUid);
4855            PackageParser.Activity a = mActivities.mActivities.get(component);
4856            if (a == null) {
4857                return false;
4858            }
4859            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4860            if (ps == null) {
4861                return false;
4862            }
4863            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4864                return false;
4865            }
4866            for (int i=0; i<a.intents.size(); i++) {
4867                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4868                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4869                    return true;
4870                }
4871            }
4872            return false;
4873        }
4874    }
4875
4876    @Override
4877    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4878        if (!sUserManager.exists(userId)) return null;
4879        final int callingUid = Binder.getCallingUid();
4880        flags = updateFlagsForComponent(flags, userId, component);
4881        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4882                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4883        synchronized (mPackages) {
4884            PackageParser.Activity a = mReceivers.mActivities.get(component);
4885            if (DEBUG_PACKAGE_INFO) Log.v(
4886                TAG, "getReceiverInfo " + component + ": " + a);
4887            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4888                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4889                if (ps == null) return null;
4890                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4891                    return null;
4892                }
4893                return PackageParser.generateActivityInfo(
4894                        a, flags, ps.readUserState(userId), userId);
4895            }
4896        }
4897        return null;
4898    }
4899
4900    @Override
4901    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4902            int flags, int userId) {
4903        if (!sUserManager.exists(userId)) return null;
4904        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4905        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4906            return null;
4907        }
4908
4909        flags = updateFlagsForPackage(flags, userId, null);
4910
4911        final boolean canSeeStaticLibraries =
4912                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4913                        == PERMISSION_GRANTED
4914                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4915                        == PERMISSION_GRANTED
4916                || canRequestPackageInstallsInternal(packageName,
4917                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4918                        false  /* throwIfPermNotDeclared*/)
4919                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4920                        == PERMISSION_GRANTED;
4921
4922        synchronized (mPackages) {
4923            List<SharedLibraryInfo> result = null;
4924
4925            final int libCount = mSharedLibraries.size();
4926            for (int i = 0; i < libCount; i++) {
4927                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4928                if (versionedLib == null) {
4929                    continue;
4930                }
4931
4932                final int versionCount = versionedLib.size();
4933                for (int j = 0; j < versionCount; j++) {
4934                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4935                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4936                        break;
4937                    }
4938                    final long identity = Binder.clearCallingIdentity();
4939                    try {
4940                        PackageInfo packageInfo = getPackageInfoVersioned(
4941                                libInfo.getDeclaringPackage(), flags
4942                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4943                        if (packageInfo == null) {
4944                            continue;
4945                        }
4946                    } finally {
4947                        Binder.restoreCallingIdentity(identity);
4948                    }
4949
4950                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4951                            libInfo.getLongVersion(), libInfo.getType(),
4952                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4953                            flags, userId));
4954
4955                    if (result == null) {
4956                        result = new ArrayList<>();
4957                    }
4958                    result.add(resLibInfo);
4959                }
4960            }
4961
4962            return result != null ? new ParceledListSlice<>(result) : null;
4963        }
4964    }
4965
4966    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4967            SharedLibraryInfo libInfo, int flags, int userId) {
4968        List<VersionedPackage> versionedPackages = null;
4969        final int packageCount = mSettings.mPackages.size();
4970        for (int i = 0; i < packageCount; i++) {
4971            PackageSetting ps = mSettings.mPackages.valueAt(i);
4972
4973            if (ps == null) {
4974                continue;
4975            }
4976
4977            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4978                continue;
4979            }
4980
4981            final String libName = libInfo.getName();
4982            if (libInfo.isStatic()) {
4983                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4984                if (libIdx < 0) {
4985                    continue;
4986                }
4987                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
4988                    continue;
4989                }
4990                if (versionedPackages == null) {
4991                    versionedPackages = new ArrayList<>();
4992                }
4993                // If the dependent is a static shared lib, use the public package name
4994                String dependentPackageName = ps.name;
4995                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4996                    dependentPackageName = ps.pkg.manifestPackageName;
4997                }
4998                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4999            } else if (ps.pkg != null) {
5000                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5001                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5002                    if (versionedPackages == null) {
5003                        versionedPackages = new ArrayList<>();
5004                    }
5005                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5006                }
5007            }
5008        }
5009
5010        return versionedPackages;
5011    }
5012
5013    @Override
5014    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5015        if (!sUserManager.exists(userId)) return null;
5016        final int callingUid = Binder.getCallingUid();
5017        flags = updateFlagsForComponent(flags, userId, component);
5018        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5019                false /* requireFullPermission */, false /* checkShell */, "get service info");
5020        synchronized (mPackages) {
5021            PackageParser.Service s = mServices.mServices.get(component);
5022            if (DEBUG_PACKAGE_INFO) Log.v(
5023                TAG, "getServiceInfo " + component + ": " + s);
5024            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5025                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5026                if (ps == null) return null;
5027                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5028                    return null;
5029                }
5030                return PackageParser.generateServiceInfo(
5031                        s, flags, ps.readUserState(userId), userId);
5032            }
5033        }
5034        return null;
5035    }
5036
5037    @Override
5038    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5039        if (!sUserManager.exists(userId)) return null;
5040        final int callingUid = Binder.getCallingUid();
5041        flags = updateFlagsForComponent(flags, userId, component);
5042        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5043                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5044        synchronized (mPackages) {
5045            PackageParser.Provider p = mProviders.mProviders.get(component);
5046            if (DEBUG_PACKAGE_INFO) Log.v(
5047                TAG, "getProviderInfo " + component + ": " + p);
5048            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5049                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5050                if (ps == null) return null;
5051                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5052                    return null;
5053                }
5054                return PackageParser.generateProviderInfo(
5055                        p, flags, ps.readUserState(userId), userId);
5056            }
5057        }
5058        return null;
5059    }
5060
5061    @Override
5062    public String[] getSystemSharedLibraryNames() {
5063        // allow instant applications
5064        synchronized (mPackages) {
5065            Set<String> libs = null;
5066            final int libCount = mSharedLibraries.size();
5067            for (int i = 0; i < libCount; i++) {
5068                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5069                if (versionedLib == null) {
5070                    continue;
5071                }
5072                final int versionCount = versionedLib.size();
5073                for (int j = 0; j < versionCount; j++) {
5074                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5075                    if (!libEntry.info.isStatic()) {
5076                        if (libs == null) {
5077                            libs = new ArraySet<>();
5078                        }
5079                        libs.add(libEntry.info.getName());
5080                        break;
5081                    }
5082                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5083                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5084                            UserHandle.getUserId(Binder.getCallingUid()),
5085                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5086                        if (libs == null) {
5087                            libs = new ArraySet<>();
5088                        }
5089                        libs.add(libEntry.info.getName());
5090                        break;
5091                    }
5092                }
5093            }
5094
5095            if (libs != null) {
5096                String[] libsArray = new String[libs.size()];
5097                libs.toArray(libsArray);
5098                return libsArray;
5099            }
5100
5101            return null;
5102        }
5103    }
5104
5105    @Override
5106    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5107        // allow instant applications
5108        synchronized (mPackages) {
5109            return mServicesSystemSharedLibraryPackageName;
5110        }
5111    }
5112
5113    @Override
5114    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5115        // allow instant applications
5116        synchronized (mPackages) {
5117            return mSharedSystemSharedLibraryPackageName;
5118        }
5119    }
5120
5121    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5122        for (int i = userList.length - 1; i >= 0; --i) {
5123            final int userId = userList[i];
5124            // don't add instant app to the list of updates
5125            if (pkgSetting.getInstantApp(userId)) {
5126                continue;
5127            }
5128            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5129            if (changedPackages == null) {
5130                changedPackages = new SparseArray<>();
5131                mChangedPackages.put(userId, changedPackages);
5132            }
5133            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5134            if (sequenceNumbers == null) {
5135                sequenceNumbers = new HashMap<>();
5136                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5137            }
5138            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5139            if (sequenceNumber != null) {
5140                changedPackages.remove(sequenceNumber);
5141            }
5142            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5143            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5144        }
5145        mChangedPackagesSequenceNumber++;
5146    }
5147
5148    @Override
5149    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5150        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5151            return null;
5152        }
5153        synchronized (mPackages) {
5154            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5155                return null;
5156            }
5157            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5158            if (changedPackages == null) {
5159                return null;
5160            }
5161            final List<String> packageNames =
5162                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5163            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5164                final String packageName = changedPackages.get(i);
5165                if (packageName != null) {
5166                    packageNames.add(packageName);
5167                }
5168            }
5169            return packageNames.isEmpty()
5170                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5171        }
5172    }
5173
5174    @Override
5175    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5176        // allow instant applications
5177        ArrayList<FeatureInfo> res;
5178        synchronized (mAvailableFeatures) {
5179            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5180            res.addAll(mAvailableFeatures.values());
5181        }
5182        final FeatureInfo fi = new FeatureInfo();
5183        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5184                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5185        res.add(fi);
5186
5187        return new ParceledListSlice<>(res);
5188    }
5189
5190    @Override
5191    public boolean hasSystemFeature(String name, int version) {
5192        // allow instant applications
5193        synchronized (mAvailableFeatures) {
5194            final FeatureInfo feat = mAvailableFeatures.get(name);
5195            if (feat == null) {
5196                return false;
5197            } else {
5198                return feat.version >= version;
5199            }
5200        }
5201    }
5202
5203    @Override
5204    public int checkPermission(String permName, String pkgName, int userId) {
5205        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5206    }
5207
5208    @Override
5209    public int checkUidPermission(String permName, int uid) {
5210        synchronized (mPackages) {
5211            final String[] packageNames = getPackagesForUid(uid);
5212            final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0)
5213                    ? mPackages.get(packageNames[0])
5214                    : null;
5215            return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid());
5216        }
5217    }
5218
5219    @Override
5220    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5221        if (UserHandle.getCallingUserId() != userId) {
5222            mContext.enforceCallingPermission(
5223                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5224                    "isPermissionRevokedByPolicy for user " + userId);
5225        }
5226
5227        if (checkPermission(permission, packageName, userId)
5228                == PackageManager.PERMISSION_GRANTED) {
5229            return false;
5230        }
5231
5232        final int callingUid = Binder.getCallingUid();
5233        if (getInstantAppPackageName(callingUid) != null) {
5234            if (!isCallerSameApp(packageName, callingUid)) {
5235                return false;
5236            }
5237        } else {
5238            if (isInstantApp(packageName, userId)) {
5239                return false;
5240            }
5241        }
5242
5243        final long identity = Binder.clearCallingIdentity();
5244        try {
5245            final int flags = getPermissionFlags(permission, packageName, userId);
5246            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5247        } finally {
5248            Binder.restoreCallingIdentity(identity);
5249        }
5250    }
5251
5252    @Override
5253    public String getPermissionControllerPackageName() {
5254        synchronized (mPackages) {
5255            return mRequiredInstallerPackage;
5256        }
5257    }
5258
5259    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5260        return mPermissionManager.addDynamicPermission(
5261                info, async, getCallingUid(), new PermissionCallback() {
5262                    @Override
5263                    public void onPermissionChanged() {
5264                        if (!async) {
5265                            mSettings.writeLPr();
5266                        } else {
5267                            scheduleWriteSettingsLocked();
5268                        }
5269                    }
5270                });
5271    }
5272
5273    @Override
5274    public boolean addPermission(PermissionInfo info) {
5275        synchronized (mPackages) {
5276            return addDynamicPermission(info, false);
5277        }
5278    }
5279
5280    @Override
5281    public boolean addPermissionAsync(PermissionInfo info) {
5282        synchronized (mPackages) {
5283            return addDynamicPermission(info, true);
5284        }
5285    }
5286
5287    @Override
5288    public void removePermission(String permName) {
5289        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5290    }
5291
5292    @Override
5293    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5294        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5295                getCallingUid(), userId, mPermissionCallback);
5296    }
5297
5298    @Override
5299    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5300        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5301                getCallingUid(), userId, mPermissionCallback);
5302    }
5303
5304    @Override
5305    public void resetRuntimePermissions() {
5306        mContext.enforceCallingOrSelfPermission(
5307                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5308                "revokeRuntimePermission");
5309
5310        int callingUid = Binder.getCallingUid();
5311        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5312            mContext.enforceCallingOrSelfPermission(
5313                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5314                    "resetRuntimePermissions");
5315        }
5316
5317        synchronized (mPackages) {
5318            mPermissionManager.updateAllPermissions(
5319                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5320                    mPermissionCallback);
5321            for (int userId : UserManagerService.getInstance().getUserIds()) {
5322                final int packageCount = mPackages.size();
5323                for (int i = 0; i < packageCount; i++) {
5324                    PackageParser.Package pkg = mPackages.valueAt(i);
5325                    if (!(pkg.mExtras instanceof PackageSetting)) {
5326                        continue;
5327                    }
5328                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5329                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5330                }
5331            }
5332        }
5333    }
5334
5335    @Override
5336    public int getPermissionFlags(String permName, String packageName, int userId) {
5337        return mPermissionManager.getPermissionFlags(
5338                permName, packageName, getCallingUid(), userId);
5339    }
5340
5341    @Override
5342    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5343            int flagValues, int userId) {
5344        mPermissionManager.updatePermissionFlags(
5345                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5346                mPermissionCallback);
5347    }
5348
5349    /**
5350     * Update the permission flags for all packages and runtime permissions of a user in order
5351     * to allow device or profile owner to remove POLICY_FIXED.
5352     */
5353    @Override
5354    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5355        synchronized (mPackages) {
5356            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5357                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5358                    mPermissionCallback);
5359            if (changed) {
5360                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5361            }
5362        }
5363    }
5364
5365    @Override
5366    public boolean shouldShowRequestPermissionRationale(String permissionName,
5367            String packageName, int userId) {
5368        if (UserHandle.getCallingUserId() != userId) {
5369            mContext.enforceCallingPermission(
5370                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5371                    "canShowRequestPermissionRationale for user " + userId);
5372        }
5373
5374        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5375        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5376            return false;
5377        }
5378
5379        if (checkPermission(permissionName, packageName, userId)
5380                == PackageManager.PERMISSION_GRANTED) {
5381            return false;
5382        }
5383
5384        final int flags;
5385
5386        final long identity = Binder.clearCallingIdentity();
5387        try {
5388            flags = getPermissionFlags(permissionName,
5389                    packageName, userId);
5390        } finally {
5391            Binder.restoreCallingIdentity(identity);
5392        }
5393
5394        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5395                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5396                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5397
5398        if ((flags & fixedFlags) != 0) {
5399            return false;
5400        }
5401
5402        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5403    }
5404
5405    @Override
5406    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5407        mContext.enforceCallingOrSelfPermission(
5408                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5409                "addOnPermissionsChangeListener");
5410
5411        synchronized (mPackages) {
5412            mOnPermissionChangeListeners.addListenerLocked(listener);
5413        }
5414    }
5415
5416    @Override
5417    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5418        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5419            throw new SecurityException("Instant applications don't have access to this method");
5420        }
5421        synchronized (mPackages) {
5422            mOnPermissionChangeListeners.removeListenerLocked(listener);
5423        }
5424    }
5425
5426    @Override
5427    public boolean isProtectedBroadcast(String actionName) {
5428        // allow instant applications
5429        synchronized (mProtectedBroadcasts) {
5430            if (mProtectedBroadcasts.contains(actionName)) {
5431                return true;
5432            } else if (actionName != null) {
5433                // TODO: remove these terrible hacks
5434                if (actionName.startsWith("android.net.netmon.lingerExpired")
5435                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5436                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5437                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5438                    return true;
5439                }
5440            }
5441        }
5442        return false;
5443    }
5444
5445    @Override
5446    public int checkSignatures(String pkg1, String pkg2) {
5447        synchronized (mPackages) {
5448            final PackageParser.Package p1 = mPackages.get(pkg1);
5449            final PackageParser.Package p2 = mPackages.get(pkg2);
5450            if (p1 == null || p1.mExtras == null
5451                    || p2 == null || p2.mExtras == null) {
5452                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5453            }
5454            final int callingUid = Binder.getCallingUid();
5455            final int callingUserId = UserHandle.getUserId(callingUid);
5456            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5457            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5458            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5459                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5460                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5461            }
5462            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5463        }
5464    }
5465
5466    @Override
5467    public int checkUidSignatures(int uid1, int uid2) {
5468        final int callingUid = Binder.getCallingUid();
5469        final int callingUserId = UserHandle.getUserId(callingUid);
5470        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5471        // Map to base uids.
5472        uid1 = UserHandle.getAppId(uid1);
5473        uid2 = UserHandle.getAppId(uid2);
5474        // reader
5475        synchronized (mPackages) {
5476            Signature[] s1;
5477            Signature[] s2;
5478            Object obj = mSettings.getUserIdLPr(uid1);
5479            if (obj != null) {
5480                if (obj instanceof SharedUserSetting) {
5481                    if (isCallerInstantApp) {
5482                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5483                    }
5484                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5485                } else if (obj instanceof PackageSetting) {
5486                    final PackageSetting ps = (PackageSetting) obj;
5487                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5488                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5489                    }
5490                    s1 = ps.signatures.mSigningDetails.signatures;
5491                } else {
5492                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5493                }
5494            } else {
5495                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5496            }
5497            obj = mSettings.getUserIdLPr(uid2);
5498            if (obj != null) {
5499                if (obj instanceof SharedUserSetting) {
5500                    if (isCallerInstantApp) {
5501                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5502                    }
5503                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5504                } else if (obj instanceof PackageSetting) {
5505                    final PackageSetting ps = (PackageSetting) obj;
5506                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5507                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5508                    }
5509                    s2 = ps.signatures.mSigningDetails.signatures;
5510                } else {
5511                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5512                }
5513            } else {
5514                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5515            }
5516            return compareSignatures(s1, s2);
5517        }
5518    }
5519
5520    @Override
5521    public boolean hasSigningCertificate(
5522            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5523
5524        synchronized (mPackages) {
5525            final PackageParser.Package p = mPackages.get(packageName);
5526            if (p == null || p.mExtras == null) {
5527                return false;
5528            }
5529            final int callingUid = Binder.getCallingUid();
5530            final int callingUserId = UserHandle.getUserId(callingUid);
5531            final PackageSetting ps = (PackageSetting) p.mExtras;
5532            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5533                return false;
5534            }
5535            switch (type) {
5536                case CERT_INPUT_RAW_X509:
5537                    return p.mSigningDetails.hasCertificate(certificate);
5538                case CERT_INPUT_SHA256:
5539                    return p.mSigningDetails.hasSha256Certificate(certificate);
5540                default:
5541                    return false;
5542            }
5543        }
5544    }
5545
5546    @Override
5547    public boolean hasUidSigningCertificate(
5548            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5549        final int callingUid = Binder.getCallingUid();
5550        final int callingUserId = UserHandle.getUserId(callingUid);
5551        // Map to base uids.
5552        uid = UserHandle.getAppId(uid);
5553        // reader
5554        synchronized (mPackages) {
5555            final PackageParser.SigningDetails signingDetails;
5556            final Object obj = mSettings.getUserIdLPr(uid);
5557            if (obj != null) {
5558                if (obj instanceof SharedUserSetting) {
5559                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5560                    if (isCallerInstantApp) {
5561                        return false;
5562                    }
5563                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5564                } else if (obj instanceof PackageSetting) {
5565                    final PackageSetting ps = (PackageSetting) obj;
5566                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5567                        return false;
5568                    }
5569                    signingDetails = ps.signatures.mSigningDetails;
5570                } else {
5571                    return false;
5572                }
5573            } else {
5574                return false;
5575            }
5576            switch (type) {
5577                case CERT_INPUT_RAW_X509:
5578                    return signingDetails.hasCertificate(certificate);
5579                case CERT_INPUT_SHA256:
5580                    return signingDetails.hasSha256Certificate(certificate);
5581                default:
5582                    return false;
5583            }
5584        }
5585    }
5586
5587    /**
5588     * This method should typically only be used when granting or revoking
5589     * permissions, since the app may immediately restart after this call.
5590     * <p>
5591     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5592     * guard your work against the app being relaunched.
5593     */
5594    private void killUid(int appId, int userId, String reason) {
5595        final long identity = Binder.clearCallingIdentity();
5596        try {
5597            IActivityManager am = ActivityManager.getService();
5598            if (am != null) {
5599                try {
5600                    am.killUid(appId, userId, reason);
5601                } catch (RemoteException e) {
5602                    /* ignore - same process */
5603                }
5604            }
5605        } finally {
5606            Binder.restoreCallingIdentity(identity);
5607        }
5608    }
5609
5610    /**
5611     * If the database version for this type of package (internal storage or
5612     * external storage) is less than the version where package signatures
5613     * were updated, return true.
5614     */
5615    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5616        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5617        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5618    }
5619
5620    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5621        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5622        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5623    }
5624
5625    @Override
5626    public List<String> getAllPackages() {
5627        final int callingUid = Binder.getCallingUid();
5628        final int callingUserId = UserHandle.getUserId(callingUid);
5629        synchronized (mPackages) {
5630            if (canViewInstantApps(callingUid, callingUserId)) {
5631                return new ArrayList<String>(mPackages.keySet());
5632            }
5633            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5634            final List<String> result = new ArrayList<>();
5635            if (instantAppPkgName != null) {
5636                // caller is an instant application; filter unexposed applications
5637                for (PackageParser.Package pkg : mPackages.values()) {
5638                    if (!pkg.visibleToInstantApps) {
5639                        continue;
5640                    }
5641                    result.add(pkg.packageName);
5642                }
5643            } else {
5644                // caller is a normal application; filter instant applications
5645                for (PackageParser.Package pkg : mPackages.values()) {
5646                    final PackageSetting ps =
5647                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5648                    if (ps != null
5649                            && ps.getInstantApp(callingUserId)
5650                            && !mInstantAppRegistry.isInstantAccessGranted(
5651                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5652                        continue;
5653                    }
5654                    result.add(pkg.packageName);
5655                }
5656            }
5657            return result;
5658        }
5659    }
5660
5661    @Override
5662    public String[] getPackagesForUid(int uid) {
5663        final int callingUid = Binder.getCallingUid();
5664        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5665        final int userId = UserHandle.getUserId(uid);
5666        uid = UserHandle.getAppId(uid);
5667        // reader
5668        synchronized (mPackages) {
5669            Object obj = mSettings.getUserIdLPr(uid);
5670            if (obj instanceof SharedUserSetting) {
5671                if (isCallerInstantApp) {
5672                    return null;
5673                }
5674                final SharedUserSetting sus = (SharedUserSetting) obj;
5675                final int N = sus.packages.size();
5676                String[] res = new String[N];
5677                final Iterator<PackageSetting> it = sus.packages.iterator();
5678                int i = 0;
5679                while (it.hasNext()) {
5680                    PackageSetting ps = it.next();
5681                    if (ps.getInstalled(userId)) {
5682                        res[i++] = ps.name;
5683                    } else {
5684                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5685                    }
5686                }
5687                return res;
5688            } else if (obj instanceof PackageSetting) {
5689                final PackageSetting ps = (PackageSetting) obj;
5690                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5691                    return new String[]{ps.name};
5692                }
5693            }
5694        }
5695        return null;
5696    }
5697
5698    @Override
5699    public String getNameForUid(int uid) {
5700        final int callingUid = Binder.getCallingUid();
5701        if (getInstantAppPackageName(callingUid) != null) {
5702            return null;
5703        }
5704        synchronized (mPackages) {
5705            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5706            if (obj instanceof SharedUserSetting) {
5707                final SharedUserSetting sus = (SharedUserSetting) obj;
5708                return sus.name + ":" + sus.userId;
5709            } else if (obj instanceof PackageSetting) {
5710                final PackageSetting ps = (PackageSetting) obj;
5711                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5712                    return null;
5713                }
5714                return ps.name;
5715            }
5716            return null;
5717        }
5718    }
5719
5720    @Override
5721    public String[] getNamesForUids(int[] uids) {
5722        if (uids == null || uids.length == 0) {
5723            return null;
5724        }
5725        final int callingUid = Binder.getCallingUid();
5726        if (getInstantAppPackageName(callingUid) != null) {
5727            return null;
5728        }
5729        final String[] names = new String[uids.length];
5730        synchronized (mPackages) {
5731            for (int i = uids.length - 1; i >= 0; i--) {
5732                final int uid = uids[i];
5733                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5734                if (obj instanceof SharedUserSetting) {
5735                    final SharedUserSetting sus = (SharedUserSetting) obj;
5736                    names[i] = "shared:" + sus.name;
5737                } else if (obj instanceof PackageSetting) {
5738                    final PackageSetting ps = (PackageSetting) obj;
5739                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5740                        names[i] = null;
5741                    } else {
5742                        names[i] = ps.name;
5743                    }
5744                } else {
5745                    names[i] = null;
5746                }
5747            }
5748        }
5749        return names;
5750    }
5751
5752    @Override
5753    public int getUidForSharedUser(String sharedUserName) {
5754        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5755            return -1;
5756        }
5757        if (sharedUserName == null) {
5758            return -1;
5759        }
5760        // reader
5761        synchronized (mPackages) {
5762            SharedUserSetting suid;
5763            try {
5764                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5765                if (suid != null) {
5766                    return suid.userId;
5767                }
5768            } catch (PackageManagerException ignore) {
5769                // can't happen, but, still need to catch it
5770            }
5771            return -1;
5772        }
5773    }
5774
5775    @Override
5776    public int getFlagsForUid(int uid) {
5777        final int callingUid = Binder.getCallingUid();
5778        if (getInstantAppPackageName(callingUid) != null) {
5779            return 0;
5780        }
5781        synchronized (mPackages) {
5782            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5783            if (obj instanceof SharedUserSetting) {
5784                final SharedUserSetting sus = (SharedUserSetting) obj;
5785                return sus.pkgFlags;
5786            } else if (obj instanceof PackageSetting) {
5787                final PackageSetting ps = (PackageSetting) obj;
5788                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5789                    return 0;
5790                }
5791                return ps.pkgFlags;
5792            }
5793        }
5794        return 0;
5795    }
5796
5797    @Override
5798    public int getPrivateFlagsForUid(int uid) {
5799        final int callingUid = Binder.getCallingUid();
5800        if (getInstantAppPackageName(callingUid) != null) {
5801            return 0;
5802        }
5803        synchronized (mPackages) {
5804            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5805            if (obj instanceof SharedUserSetting) {
5806                final SharedUserSetting sus = (SharedUserSetting) obj;
5807                return sus.pkgPrivateFlags;
5808            } else if (obj instanceof PackageSetting) {
5809                final PackageSetting ps = (PackageSetting) obj;
5810                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5811                    return 0;
5812                }
5813                return ps.pkgPrivateFlags;
5814            }
5815        }
5816        return 0;
5817    }
5818
5819    @Override
5820    public boolean isUidPrivileged(int uid) {
5821        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5822            return false;
5823        }
5824        uid = UserHandle.getAppId(uid);
5825        // reader
5826        synchronized (mPackages) {
5827            Object obj = mSettings.getUserIdLPr(uid);
5828            if (obj instanceof SharedUserSetting) {
5829                final SharedUserSetting sus = (SharedUserSetting) obj;
5830                final Iterator<PackageSetting> it = sus.packages.iterator();
5831                while (it.hasNext()) {
5832                    if (it.next().isPrivileged()) {
5833                        return true;
5834                    }
5835                }
5836            } else if (obj instanceof PackageSetting) {
5837                final PackageSetting ps = (PackageSetting) obj;
5838                return ps.isPrivileged();
5839            }
5840        }
5841        return false;
5842    }
5843
5844    @Override
5845    public String[] getAppOpPermissionPackages(String permName) {
5846        return mPermissionManager.getAppOpPermissionPackages(permName);
5847    }
5848
5849    @Override
5850    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5851            int flags, int userId) {
5852        return resolveIntentInternal(
5853                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5854    }
5855
5856    /**
5857     * Normally instant apps can only be resolved when they're visible to the caller.
5858     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5859     * since we need to allow the system to start any installed application.
5860     */
5861    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5862            int flags, int userId, boolean resolveForStart) {
5863        try {
5864            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5865
5866            if (!sUserManager.exists(userId)) return null;
5867            final int callingUid = Binder.getCallingUid();
5868            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5869            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5870                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5871
5872            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5873            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5874                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5875            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5876
5877            final ResolveInfo bestChoice =
5878                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5879            return bestChoice;
5880        } finally {
5881            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5882        }
5883    }
5884
5885    @Override
5886    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5887        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5888            throw new SecurityException(
5889                    "findPersistentPreferredActivity can only be run by the system");
5890        }
5891        if (!sUserManager.exists(userId)) {
5892            return null;
5893        }
5894        final int callingUid = Binder.getCallingUid();
5895        intent = updateIntentForResolve(intent);
5896        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5897        final int flags = updateFlagsForResolve(
5898                0, userId, intent, callingUid, false /*includeInstantApps*/);
5899        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5900                userId);
5901        synchronized (mPackages) {
5902            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5903                    userId);
5904        }
5905    }
5906
5907    @Override
5908    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5909            IntentFilter filter, int match, ComponentName activity) {
5910        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5911            return;
5912        }
5913        final int userId = UserHandle.getCallingUserId();
5914        if (DEBUG_PREFERRED) {
5915            Log.v(TAG, "setLastChosenActivity intent=" + intent
5916                + " resolvedType=" + resolvedType
5917                + " flags=" + flags
5918                + " filter=" + filter
5919                + " match=" + match
5920                + " activity=" + activity);
5921            filter.dump(new PrintStreamPrinter(System.out), "    ");
5922        }
5923        intent.setComponent(null);
5924        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5925                userId);
5926        // Find any earlier preferred or last chosen entries and nuke them
5927        findPreferredActivity(intent, resolvedType,
5928                flags, query, 0, false, true, false, userId);
5929        // Add the new activity as the last chosen for this filter
5930        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5931                "Setting last chosen");
5932    }
5933
5934    @Override
5935    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5936        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5937            return null;
5938        }
5939        final int userId = UserHandle.getCallingUserId();
5940        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5941        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5942                userId);
5943        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5944                false, false, false, userId);
5945    }
5946
5947    /**
5948     * Returns whether or not instant apps have been disabled remotely.
5949     */
5950    private boolean areWebInstantAppsDisabled() {
5951        return mWebInstantAppsDisabled;
5952    }
5953
5954    private boolean isInstantAppResolutionAllowed(
5955            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5956            boolean skipPackageCheck) {
5957        if (mInstantAppResolverConnection == null) {
5958            return false;
5959        }
5960        if (mInstantAppInstallerActivity == null) {
5961            return false;
5962        }
5963        if (intent.getComponent() != null) {
5964            return false;
5965        }
5966        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5967            return false;
5968        }
5969        if (!skipPackageCheck && intent.getPackage() != null) {
5970            return false;
5971        }
5972        if (!intent.isWebIntent()) {
5973            // for non web intents, we should not resolve externally if an app already exists to
5974            // handle it or if the caller didn't explicitly request it.
5975            if ((resolvedActivities != null && resolvedActivities.size() != 0)
5976                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
5977                return false;
5978            }
5979        } else {
5980            if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
5981                return false;
5982            } else if (areWebInstantAppsDisabled()) {
5983                return false;
5984            }
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, intent);
6516        }
6517
6518        // reader
6519        boolean sortResult = false;
6520        boolean addInstant = false;
6521        List<ResolveInfo> result;
6522        synchronized (mPackages) {
6523            if (pkgName == null) {
6524                List<CrossProfileIntentFilter> matchingFilters =
6525                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6526                // Check for results that need to skip the current profile.
6527                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6528                        resolvedType, flags, userId);
6529                if (xpResolveInfo != null) {
6530                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6531                    xpResult.add(xpResolveInfo);
6532                    return applyPostResolutionFilter(
6533                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6534                            allowDynamicSplits, filterCallingUid, userId, intent);
6535                }
6536
6537                // Check for results in the current profile.
6538                result = filterIfNotSystemUser(mActivities.queryIntent(
6539                        intent, resolvedType, flags, userId), userId);
6540                addInstant = isInstantAppResolutionAllowed(intent, result, userId,
6541                        false /*skipPackageCheck*/);
6542                // Check for cross profile results.
6543                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6544                xpResolveInfo = queryCrossProfileIntents(
6545                        matchingFilters, intent, resolvedType, flags, userId,
6546                        hasNonNegativePriorityResult);
6547                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6548                    boolean isVisibleToUser = filterIfNotSystemUser(
6549                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6550                    if (isVisibleToUser) {
6551                        result.add(xpResolveInfo);
6552                        sortResult = true;
6553                    }
6554                }
6555                if (intent.hasWebURI()) {
6556                    CrossProfileDomainInfo xpDomainInfo = null;
6557                    final UserInfo parent = getProfileParent(userId);
6558                    if (parent != null) {
6559                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6560                                flags, userId, parent.id);
6561                    }
6562                    if (xpDomainInfo != null) {
6563                        if (xpResolveInfo != null) {
6564                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6565                            // in the result.
6566                            result.remove(xpResolveInfo);
6567                        }
6568                        if (result.size() == 0 && !addInstant) {
6569                            // No result in current profile, but found candidate in parent user.
6570                            // And we are not going to add emphemeral app, so we can return the
6571                            // result straight away.
6572                            result.add(xpDomainInfo.resolveInfo);
6573                            return applyPostResolutionFilter(result, instantAppPkgName,
6574                                    allowDynamicSplits, filterCallingUid, userId, intent);
6575                        }
6576                    } else if (result.size() <= 1 && !addInstant) {
6577                        // No result in parent user and <= 1 result in current profile, and we
6578                        // are not going to add emphemeral app, so we can return the result without
6579                        // further processing.
6580                        return applyPostResolutionFilter(result, instantAppPkgName,
6581                                allowDynamicSplits, filterCallingUid, userId, intent);
6582                    }
6583                    // We have more than one candidate (combining results from current and parent
6584                    // profile), so we need filtering and sorting.
6585                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6586                            intent, flags, result, xpDomainInfo, userId);
6587                    sortResult = true;
6588                }
6589            } else {
6590                final PackageParser.Package pkg = mPackages.get(pkgName);
6591                result = null;
6592                if (pkg != null) {
6593                    result = filterIfNotSystemUser(
6594                            mActivities.queryIntentForPackage(
6595                                    intent, resolvedType, flags, pkg.activities, userId),
6596                            userId);
6597                }
6598                if (result == null || result.size() == 0) {
6599                    // the caller wants to resolve for a particular package; however, there
6600                    // were no installed results, so, try to find an ephemeral result
6601                    addInstant = isInstantAppResolutionAllowed(
6602                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6603                    if (result == null) {
6604                        result = new ArrayList<>();
6605                    }
6606                }
6607            }
6608        }
6609        if (addInstant) {
6610            result = maybeAddInstantAppInstaller(
6611                    result, intent, resolvedType, flags, userId, resolveForStart);
6612        }
6613        if (sortResult) {
6614            Collections.sort(result, mResolvePrioritySorter);
6615        }
6616        return applyPostResolutionFilter(
6617                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6618    }
6619
6620    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6621            String resolvedType, int flags, int userId, boolean resolveForStart) {
6622        // first, check to see if we've got an instant app already installed
6623        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6624        ResolveInfo localInstantApp = null;
6625        boolean blockResolution = false;
6626        if (!alreadyResolvedLocally) {
6627            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6628                    flags
6629                        | PackageManager.GET_RESOLVED_FILTER
6630                        | PackageManager.MATCH_INSTANT
6631                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6632                    userId);
6633            for (int i = instantApps.size() - 1; i >= 0; --i) {
6634                final ResolveInfo info = instantApps.get(i);
6635                final String packageName = info.activityInfo.packageName;
6636                final PackageSetting ps = mSettings.mPackages.get(packageName);
6637                if (ps.getInstantApp(userId)) {
6638                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6639                    final int status = (int)(packedStatus >> 32);
6640                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6641                        // there's a local instant application installed, but, the user has
6642                        // chosen to never use it; skip resolution and don't acknowledge
6643                        // an instant application is even available
6644                        if (DEBUG_INSTANT) {
6645                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6646                        }
6647                        blockResolution = true;
6648                        break;
6649                    } else {
6650                        // we have a locally installed instant application; skip resolution
6651                        // but acknowledge there's an instant application available
6652                        if (DEBUG_INSTANT) {
6653                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6654                        }
6655                        localInstantApp = info;
6656                        break;
6657                    }
6658                }
6659            }
6660        }
6661        // no app installed, let's see if one's available
6662        AuxiliaryResolveInfo auxiliaryResponse = null;
6663        if (!blockResolution) {
6664            if (localInstantApp == null) {
6665                // we don't have an instant app locally, resolve externally
6666                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6667                final InstantAppRequest requestObject = new InstantAppRequest(
6668                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6669                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6670                        resolveForStart);
6671                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6672                        mInstantAppResolverConnection, requestObject);
6673                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6674            } else {
6675                // we have an instant application locally, but, we can't admit that since
6676                // callers shouldn't be able to determine prior browsing. create a dummy
6677                // auxiliary response so the downstream code behaves as if there's an
6678                // instant application available externally. when it comes time to start
6679                // the instant application, we'll do the right thing.
6680                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6681                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6682                                        ai.packageName, ai.versionCode, null /* splitName */);
6683            }
6684        }
6685        if (intent.isWebIntent() && auxiliaryResponse == null) {
6686            return result;
6687        }
6688        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6689        if (ps == null) {
6690            return result;
6691        }
6692        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6693        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6694                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6695        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6696                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6697        // add a non-generic filter
6698        ephemeralInstaller.filter = new IntentFilter();
6699        if (intent.getAction() != null) {
6700            ephemeralInstaller.filter.addAction(intent.getAction());
6701        }
6702        if (intent.getData() != null && intent.getData().getPath() != null) {
6703            ephemeralInstaller.filter.addDataPath(
6704                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6705        }
6706        ephemeralInstaller.isInstantAppAvailable = true;
6707        // make sure this resolver is the default
6708        ephemeralInstaller.isDefault = true;
6709        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6710        if (DEBUG_INSTANT) {
6711            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6712        }
6713
6714        result.add(ephemeralInstaller);
6715        return result;
6716    }
6717
6718    private static class CrossProfileDomainInfo {
6719        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6720        ResolveInfo resolveInfo;
6721        /* Best domain verification status of the activities found in the other profile */
6722        int bestDomainVerificationStatus;
6723    }
6724
6725    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6726            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6727        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6728                sourceUserId)) {
6729            return null;
6730        }
6731        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6732                resolvedType, flags, parentUserId);
6733
6734        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6735            return null;
6736        }
6737        CrossProfileDomainInfo result = null;
6738        int size = resultTargetUser.size();
6739        for (int i = 0; i < size; i++) {
6740            ResolveInfo riTargetUser = resultTargetUser.get(i);
6741            // Intent filter verification is only for filters that specify a host. So don't return
6742            // those that handle all web uris.
6743            if (riTargetUser.handleAllWebDataURI) {
6744                continue;
6745            }
6746            String packageName = riTargetUser.activityInfo.packageName;
6747            PackageSetting ps = mSettings.mPackages.get(packageName);
6748            if (ps == null) {
6749                continue;
6750            }
6751            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6752            int status = (int)(verificationState >> 32);
6753            if (result == null) {
6754                result = new CrossProfileDomainInfo();
6755                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6756                        sourceUserId, parentUserId);
6757                result.bestDomainVerificationStatus = status;
6758            } else {
6759                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6760                        result.bestDomainVerificationStatus);
6761            }
6762        }
6763        // Don't consider matches with status NEVER across profiles.
6764        if (result != null && result.bestDomainVerificationStatus
6765                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6766            return null;
6767        }
6768        return result;
6769    }
6770
6771    /**
6772     * Verification statuses are ordered from the worse to the best, except for
6773     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6774     */
6775    private int bestDomainVerificationStatus(int status1, int status2) {
6776        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6777            return status2;
6778        }
6779        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6780            return status1;
6781        }
6782        return (int) MathUtils.max(status1, status2);
6783    }
6784
6785    private boolean isUserEnabled(int userId) {
6786        long callingId = Binder.clearCallingIdentity();
6787        try {
6788            UserInfo userInfo = sUserManager.getUserInfo(userId);
6789            return userInfo != null && userInfo.isEnabled();
6790        } finally {
6791            Binder.restoreCallingIdentity(callingId);
6792        }
6793    }
6794
6795    /**
6796     * Filter out activities with systemUserOnly flag set, when current user is not System.
6797     *
6798     * @return filtered list
6799     */
6800    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6801        if (userId == UserHandle.USER_SYSTEM) {
6802            return resolveInfos;
6803        }
6804        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6805            ResolveInfo info = resolveInfos.get(i);
6806            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6807                resolveInfos.remove(i);
6808            }
6809        }
6810        return resolveInfos;
6811    }
6812
6813    /**
6814     * Filters out ephemeral activities.
6815     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6816     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6817     *
6818     * @param resolveInfos The pre-filtered list of resolved activities
6819     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6820     *          is performed.
6821     * @param intent
6822     * @return A filtered list of resolved activities.
6823     */
6824    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6825            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId,
6826            Intent intent) {
6827        final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled();
6828        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6829            final ResolveInfo info = resolveInfos.get(i);
6830            // remove locally resolved instant app web results when disabled
6831            if (info.isInstantAppAvailable && blockInstant) {
6832                resolveInfos.remove(i);
6833                continue;
6834            }
6835            // allow activities that are defined in the provided package
6836            if (allowDynamicSplits
6837                    && info.activityInfo != null
6838                    && info.activityInfo.splitName != null
6839                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6840                            info.activityInfo.splitName)) {
6841                if (mInstantAppInstallerActivity == null) {
6842                    if (DEBUG_INSTALL) {
6843                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6844                    }
6845                    resolveInfos.remove(i);
6846                    continue;
6847                }
6848                // requested activity is defined in a split that hasn't been installed yet.
6849                // add the installer to the resolve list
6850                if (DEBUG_INSTALL) {
6851                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6852                }
6853                final ResolveInfo installerInfo = new ResolveInfo(
6854                        mInstantAppInstallerInfo);
6855                final ComponentName installFailureActivity = findInstallFailureActivity(
6856                        info.activityInfo.packageName,  filterCallingUid, userId);
6857                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6858                        installFailureActivity,
6859                        info.activityInfo.packageName,
6860                        info.activityInfo.applicationInfo.versionCode,
6861                        info.activityInfo.splitName);
6862                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6863                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6864                // add a non-generic filter
6865                installerInfo.filter = new IntentFilter();
6866
6867                // This resolve info may appear in the chooser UI, so let us make it
6868                // look as the one it replaces as far as the user is concerned which
6869                // requires loading the correct label and icon for the resolve info.
6870                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6871                installerInfo.labelRes = info.resolveLabelResId();
6872                installerInfo.icon = info.resolveIconResId();
6873
6874                // propagate priority/preferred order/default
6875                installerInfo.priority = info.priority;
6876                installerInfo.preferredOrder = info.preferredOrder;
6877                installerInfo.isDefault = info.isDefault;
6878                installerInfo.isInstantAppAvailable = true;
6879                resolveInfos.set(i, installerInfo);
6880                continue;
6881            }
6882            // caller is a full app, don't need to apply any other filtering
6883            if (ephemeralPkgName == null) {
6884                continue;
6885            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6886                // caller is same app; don't need to apply any other filtering
6887                continue;
6888            }
6889            // allow activities that have been explicitly exposed to ephemeral apps
6890            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6891            if (!isEphemeralApp
6892                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6893                continue;
6894            }
6895            resolveInfos.remove(i);
6896        }
6897        return resolveInfos;
6898    }
6899
6900    /**
6901     * Returns the activity component that can handle install failures.
6902     * <p>By default, the instant application installer handles failures. However, an
6903     * application may want to handle failures on its own. Applications do this by
6904     * creating an activity with an intent filter that handles the action
6905     * {@link Intent#ACTION_INSTALL_FAILURE}.
6906     */
6907    private @Nullable ComponentName findInstallFailureActivity(
6908            String packageName, int filterCallingUid, int userId) {
6909        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6910        failureActivityIntent.setPackage(packageName);
6911        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6912        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6913                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6914                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6915        final int NR = result.size();
6916        if (NR > 0) {
6917            for (int i = 0; i < NR; i++) {
6918                final ResolveInfo info = result.get(i);
6919                if (info.activityInfo.splitName != null) {
6920                    continue;
6921                }
6922                return new ComponentName(packageName, info.activityInfo.name);
6923            }
6924        }
6925        return null;
6926    }
6927
6928    /**
6929     * @param resolveInfos list of resolve infos in descending priority order
6930     * @return if the list contains a resolve info with non-negative priority
6931     */
6932    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6933        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6934    }
6935
6936    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6937            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6938            int userId) {
6939        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6940
6941        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6942            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6943                    candidates.size());
6944        }
6945
6946        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6947        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6948        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6949        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6950        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6951        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6952
6953        synchronized (mPackages) {
6954            final int count = candidates.size();
6955            // First, try to use linked apps. Partition the candidates into four lists:
6956            // one for the final results, one for the "do not use ever", one for "undefined status"
6957            // and finally one for "browser app type".
6958            for (int n=0; n<count; n++) {
6959                ResolveInfo info = candidates.get(n);
6960                String packageName = info.activityInfo.packageName;
6961                PackageSetting ps = mSettings.mPackages.get(packageName);
6962                if (ps != null) {
6963                    // Add to the special match all list (Browser use case)
6964                    if (info.handleAllWebDataURI) {
6965                        matchAllList.add(info);
6966                        continue;
6967                    }
6968                    // Try to get the status from User settings first
6969                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6970                    int status = (int)(packedStatus >> 32);
6971                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6972                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6973                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6974                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6975                                    + " : linkgen=" + linkGeneration);
6976                        }
6977                        // Use link-enabled generation as preferredOrder, i.e.
6978                        // prefer newly-enabled over earlier-enabled.
6979                        info.preferredOrder = linkGeneration;
6980                        alwaysList.add(info);
6981                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6982                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6983                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6984                        }
6985                        neverList.add(info);
6986                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6987                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6988                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6989                        }
6990                        alwaysAskList.add(info);
6991                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6992                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6993                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6994                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6995                        }
6996                        undefinedList.add(info);
6997                    }
6998                }
6999            }
7000
7001            // We'll want to include browser possibilities in a few cases
7002            boolean includeBrowser = false;
7003
7004            // First try to add the "always" resolution(s) for the current user, if any
7005            if (alwaysList.size() > 0) {
7006                result.addAll(alwaysList);
7007            } else {
7008                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7009                result.addAll(undefinedList);
7010                // Maybe add one for the other profile.
7011                if (xpDomainInfo != null && (
7012                        xpDomainInfo.bestDomainVerificationStatus
7013                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7014                    result.add(xpDomainInfo.resolveInfo);
7015                }
7016                includeBrowser = true;
7017            }
7018
7019            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7020            // If there were 'always' entries their preferred order has been set, so we also
7021            // back that off to make the alternatives equivalent
7022            if (alwaysAskList.size() > 0) {
7023                for (ResolveInfo i : result) {
7024                    i.preferredOrder = 0;
7025                }
7026                result.addAll(alwaysAskList);
7027                includeBrowser = true;
7028            }
7029
7030            if (includeBrowser) {
7031                // Also add browsers (all of them or only the default one)
7032                if (DEBUG_DOMAIN_VERIFICATION) {
7033                    Slog.v(TAG, "   ...including browsers in candidate set");
7034                }
7035                if ((matchFlags & MATCH_ALL) != 0) {
7036                    result.addAll(matchAllList);
7037                } else {
7038                    // Browser/generic handling case.  If there's a default browser, go straight
7039                    // to that (but only if there is no other higher-priority match).
7040                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7041                    int maxMatchPrio = 0;
7042                    ResolveInfo defaultBrowserMatch = null;
7043                    final int numCandidates = matchAllList.size();
7044                    for (int n = 0; n < numCandidates; n++) {
7045                        ResolveInfo info = matchAllList.get(n);
7046                        // track the highest overall match priority...
7047                        if (info.priority > maxMatchPrio) {
7048                            maxMatchPrio = info.priority;
7049                        }
7050                        // ...and the highest-priority default browser match
7051                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7052                            if (defaultBrowserMatch == null
7053                                    || (defaultBrowserMatch.priority < info.priority)) {
7054                                if (debug) {
7055                                    Slog.v(TAG, "Considering default browser match " + info);
7056                                }
7057                                defaultBrowserMatch = info;
7058                            }
7059                        }
7060                    }
7061                    if (defaultBrowserMatch != null
7062                            && defaultBrowserMatch.priority >= maxMatchPrio
7063                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7064                    {
7065                        if (debug) {
7066                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7067                        }
7068                        result.add(defaultBrowserMatch);
7069                    } else {
7070                        result.addAll(matchAllList);
7071                    }
7072                }
7073
7074                // If there is nothing selected, add all candidates and remove the ones that the user
7075                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7076                if (result.size() == 0) {
7077                    result.addAll(candidates);
7078                    result.removeAll(neverList);
7079                }
7080            }
7081        }
7082        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7083            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7084                    result.size());
7085            for (ResolveInfo info : result) {
7086                Slog.v(TAG, "  + " + info.activityInfo);
7087            }
7088        }
7089        return result;
7090    }
7091
7092    // Returns a packed value as a long:
7093    //
7094    // high 'int'-sized word: link status: undefined/ask/never/always.
7095    // low 'int'-sized word: relative priority among 'always' results.
7096    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7097        long result = ps.getDomainVerificationStatusForUser(userId);
7098        // if none available, get the master status
7099        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7100            if (ps.getIntentFilterVerificationInfo() != null) {
7101                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7102            }
7103        }
7104        return result;
7105    }
7106
7107    private ResolveInfo querySkipCurrentProfileIntents(
7108            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7109            int flags, int sourceUserId) {
7110        if (matchingFilters != null) {
7111            int size = matchingFilters.size();
7112            for (int i = 0; i < size; i ++) {
7113                CrossProfileIntentFilter filter = matchingFilters.get(i);
7114                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7115                    // Checking if there are activities in the target user that can handle the
7116                    // intent.
7117                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7118                            resolvedType, flags, sourceUserId);
7119                    if (resolveInfo != null) {
7120                        return resolveInfo;
7121                    }
7122                }
7123            }
7124        }
7125        return null;
7126    }
7127
7128    // Return matching ResolveInfo in target user if any.
7129    private ResolveInfo queryCrossProfileIntents(
7130            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7131            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7132        if (matchingFilters != null) {
7133            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7134            // match the same intent. For performance reasons, it is better not to
7135            // run queryIntent twice for the same userId
7136            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7137            int size = matchingFilters.size();
7138            for (int i = 0; i < size; i++) {
7139                CrossProfileIntentFilter filter = matchingFilters.get(i);
7140                int targetUserId = filter.getTargetUserId();
7141                boolean skipCurrentProfile =
7142                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7143                boolean skipCurrentProfileIfNoMatchFound =
7144                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7145                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7146                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7147                    // Checking if there are activities in the target user that can handle the
7148                    // intent.
7149                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7150                            resolvedType, flags, sourceUserId);
7151                    if (resolveInfo != null) return resolveInfo;
7152                    alreadyTriedUserIds.put(targetUserId, true);
7153                }
7154            }
7155        }
7156        return null;
7157    }
7158
7159    /**
7160     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7161     * will forward the intent to the filter's target user.
7162     * Otherwise, returns null.
7163     */
7164    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7165            String resolvedType, int flags, int sourceUserId) {
7166        int targetUserId = filter.getTargetUserId();
7167        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7168                resolvedType, flags, targetUserId);
7169        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7170            // If all the matches in the target profile are suspended, return null.
7171            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7172                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7173                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7174                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7175                            targetUserId);
7176                }
7177            }
7178        }
7179        return null;
7180    }
7181
7182    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7183            int sourceUserId, int targetUserId) {
7184        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7185        long ident = Binder.clearCallingIdentity();
7186        boolean targetIsProfile;
7187        try {
7188            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7189        } finally {
7190            Binder.restoreCallingIdentity(ident);
7191        }
7192        String className;
7193        if (targetIsProfile) {
7194            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7195        } else {
7196            className = FORWARD_INTENT_TO_PARENT;
7197        }
7198        ComponentName forwardingActivityComponentName = new ComponentName(
7199                mAndroidApplication.packageName, className);
7200        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7201                sourceUserId);
7202        if (!targetIsProfile) {
7203            forwardingActivityInfo.showUserIcon = targetUserId;
7204            forwardingResolveInfo.noResourceId = true;
7205        }
7206        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7207        forwardingResolveInfo.priority = 0;
7208        forwardingResolveInfo.preferredOrder = 0;
7209        forwardingResolveInfo.match = 0;
7210        forwardingResolveInfo.isDefault = true;
7211        forwardingResolveInfo.filter = filter;
7212        forwardingResolveInfo.targetUserId = targetUserId;
7213        return forwardingResolveInfo;
7214    }
7215
7216    @Override
7217    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7218            Intent[] specifics, String[] specificTypes, Intent intent,
7219            String resolvedType, int flags, int userId) {
7220        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7221                specificTypes, intent, resolvedType, flags, userId));
7222    }
7223
7224    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7225            Intent[] specifics, String[] specificTypes, Intent intent,
7226            String resolvedType, int flags, int userId) {
7227        if (!sUserManager.exists(userId)) return Collections.emptyList();
7228        final int callingUid = Binder.getCallingUid();
7229        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7230                false /*includeInstantApps*/);
7231        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7232                false /*requireFullPermission*/, false /*checkShell*/,
7233                "query intent activity options");
7234        final String resultsAction = intent.getAction();
7235
7236        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7237                | PackageManager.GET_RESOLVED_FILTER, userId);
7238
7239        if (DEBUG_INTENT_MATCHING) {
7240            Log.v(TAG, "Query " + intent + ": " + results);
7241        }
7242
7243        int specificsPos = 0;
7244        int N;
7245
7246        // todo: note that the algorithm used here is O(N^2).  This
7247        // isn't a problem in our current environment, but if we start running
7248        // into situations where we have more than 5 or 10 matches then this
7249        // should probably be changed to something smarter...
7250
7251        // First we go through and resolve each of the specific items
7252        // that were supplied, taking care of removing any corresponding
7253        // duplicate items in the generic resolve list.
7254        if (specifics != null) {
7255            for (int i=0; i<specifics.length; i++) {
7256                final Intent sintent = specifics[i];
7257                if (sintent == null) {
7258                    continue;
7259                }
7260
7261                if (DEBUG_INTENT_MATCHING) {
7262                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7263                }
7264
7265                String action = sintent.getAction();
7266                if (resultsAction != null && resultsAction.equals(action)) {
7267                    // If this action was explicitly requested, then don't
7268                    // remove things that have it.
7269                    action = null;
7270                }
7271
7272                ResolveInfo ri = null;
7273                ActivityInfo ai = null;
7274
7275                ComponentName comp = sintent.getComponent();
7276                if (comp == null) {
7277                    ri = resolveIntent(
7278                        sintent,
7279                        specificTypes != null ? specificTypes[i] : null,
7280                            flags, userId);
7281                    if (ri == null) {
7282                        continue;
7283                    }
7284                    if (ri == mResolveInfo) {
7285                        // ACK!  Must do something better with this.
7286                    }
7287                    ai = ri.activityInfo;
7288                    comp = new ComponentName(ai.applicationInfo.packageName,
7289                            ai.name);
7290                } else {
7291                    ai = getActivityInfo(comp, flags, userId);
7292                    if (ai == null) {
7293                        continue;
7294                    }
7295                }
7296
7297                // Look for any generic query activities that are duplicates
7298                // of this specific one, and remove them from the results.
7299                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7300                N = results.size();
7301                int j;
7302                for (j=specificsPos; j<N; j++) {
7303                    ResolveInfo sri = results.get(j);
7304                    if ((sri.activityInfo.name.equals(comp.getClassName())
7305                            && sri.activityInfo.applicationInfo.packageName.equals(
7306                                    comp.getPackageName()))
7307                        || (action != null && sri.filter.matchAction(action))) {
7308                        results.remove(j);
7309                        if (DEBUG_INTENT_MATCHING) Log.v(
7310                            TAG, "Removing duplicate item from " + j
7311                            + " due to specific " + specificsPos);
7312                        if (ri == null) {
7313                            ri = sri;
7314                        }
7315                        j--;
7316                        N--;
7317                    }
7318                }
7319
7320                // Add this specific item to its proper place.
7321                if (ri == null) {
7322                    ri = new ResolveInfo();
7323                    ri.activityInfo = ai;
7324                }
7325                results.add(specificsPos, ri);
7326                ri.specificIndex = i;
7327                specificsPos++;
7328            }
7329        }
7330
7331        // Now we go through the remaining generic results and remove any
7332        // duplicate actions that are found here.
7333        N = results.size();
7334        for (int i=specificsPos; i<N-1; i++) {
7335            final ResolveInfo rii = results.get(i);
7336            if (rii.filter == null) {
7337                continue;
7338            }
7339
7340            // Iterate over all of the actions of this result's intent
7341            // filter...  typically this should be just one.
7342            final Iterator<String> it = rii.filter.actionsIterator();
7343            if (it == null) {
7344                continue;
7345            }
7346            while (it.hasNext()) {
7347                final String action = it.next();
7348                if (resultsAction != null && resultsAction.equals(action)) {
7349                    // If this action was explicitly requested, then don't
7350                    // remove things that have it.
7351                    continue;
7352                }
7353                for (int j=i+1; j<N; j++) {
7354                    final ResolveInfo rij = results.get(j);
7355                    if (rij.filter != null && rij.filter.hasAction(action)) {
7356                        results.remove(j);
7357                        if (DEBUG_INTENT_MATCHING) Log.v(
7358                            TAG, "Removing duplicate item from " + j
7359                            + " due to action " + action + " at " + i);
7360                        j--;
7361                        N--;
7362                    }
7363                }
7364            }
7365
7366            // If the caller didn't request filter information, drop it now
7367            // so we don't have to marshall/unmarshall it.
7368            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7369                rii.filter = null;
7370            }
7371        }
7372
7373        // Filter out the caller activity if so requested.
7374        if (caller != null) {
7375            N = results.size();
7376            for (int i=0; i<N; i++) {
7377                ActivityInfo ainfo = results.get(i).activityInfo;
7378                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7379                        && caller.getClassName().equals(ainfo.name)) {
7380                    results.remove(i);
7381                    break;
7382                }
7383            }
7384        }
7385
7386        // If the caller didn't request filter information,
7387        // drop them now so we don't have to
7388        // marshall/unmarshall it.
7389        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7390            N = results.size();
7391            for (int i=0; i<N; i++) {
7392                results.get(i).filter = null;
7393            }
7394        }
7395
7396        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7397        return results;
7398    }
7399
7400    @Override
7401    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7402            String resolvedType, int flags, int userId) {
7403        return new ParceledListSlice<>(
7404                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7405                        false /*allowDynamicSplits*/));
7406    }
7407
7408    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7409            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7410        if (!sUserManager.exists(userId)) return Collections.emptyList();
7411        final int callingUid = Binder.getCallingUid();
7412        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7413                false /*requireFullPermission*/, false /*checkShell*/,
7414                "query intent receivers");
7415        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7416        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7417                false /*includeInstantApps*/);
7418        ComponentName comp = intent.getComponent();
7419        if (comp == null) {
7420            if (intent.getSelector() != null) {
7421                intent = intent.getSelector();
7422                comp = intent.getComponent();
7423            }
7424        }
7425        if (comp != null) {
7426            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7427            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7428            if (ai != null) {
7429                // When specifying an explicit component, we prevent the activity from being
7430                // used when either 1) the calling package is normal and the activity is within
7431                // an instant application or 2) the calling package is ephemeral and the
7432                // activity is not visible to instant applications.
7433                final boolean matchInstantApp =
7434                        (flags & PackageManager.MATCH_INSTANT) != 0;
7435                final boolean matchVisibleToInstantAppOnly =
7436                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7437                final boolean matchExplicitlyVisibleOnly =
7438                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7439                final boolean isCallerInstantApp =
7440                        instantAppPkgName != null;
7441                final boolean isTargetSameInstantApp =
7442                        comp.getPackageName().equals(instantAppPkgName);
7443                final boolean isTargetInstantApp =
7444                        (ai.applicationInfo.privateFlags
7445                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7446                final boolean isTargetVisibleToInstantApp =
7447                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7448                final boolean isTargetExplicitlyVisibleToInstantApp =
7449                        isTargetVisibleToInstantApp
7450                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7451                final boolean isTargetHiddenFromInstantApp =
7452                        !isTargetVisibleToInstantApp
7453                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7454                final boolean blockResolution =
7455                        !isTargetSameInstantApp
7456                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7457                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7458                                        && isTargetHiddenFromInstantApp));
7459                if (!blockResolution) {
7460                    ResolveInfo ri = new ResolveInfo();
7461                    ri.activityInfo = ai;
7462                    list.add(ri);
7463                }
7464            }
7465            return applyPostResolutionFilter(
7466                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7467        }
7468
7469        // reader
7470        synchronized (mPackages) {
7471            String pkgName = intent.getPackage();
7472            if (pkgName == null) {
7473                final List<ResolveInfo> result =
7474                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7475                return applyPostResolutionFilter(
7476                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7477            }
7478            final PackageParser.Package pkg = mPackages.get(pkgName);
7479            if (pkg != null) {
7480                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7481                        intent, resolvedType, flags, pkg.receivers, userId);
7482                return applyPostResolutionFilter(
7483                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7484            }
7485            return Collections.emptyList();
7486        }
7487    }
7488
7489    @Override
7490    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7491        final int callingUid = Binder.getCallingUid();
7492        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7493    }
7494
7495    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7496            int userId, int callingUid) {
7497        if (!sUserManager.exists(userId)) return null;
7498        flags = updateFlagsForResolve(
7499                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7500        List<ResolveInfo> query = queryIntentServicesInternal(
7501                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7502        if (query != null) {
7503            if (query.size() >= 1) {
7504                // If there is more than one service with the same priority,
7505                // just arbitrarily pick the first one.
7506                return query.get(0);
7507            }
7508        }
7509        return null;
7510    }
7511
7512    @Override
7513    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7514            String resolvedType, int flags, int userId) {
7515        final int callingUid = Binder.getCallingUid();
7516        return new ParceledListSlice<>(queryIntentServicesInternal(
7517                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7518    }
7519
7520    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7521            String resolvedType, int flags, int userId, int callingUid,
7522            boolean includeInstantApps) {
7523        if (!sUserManager.exists(userId)) return Collections.emptyList();
7524        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7525                false /*requireFullPermission*/, false /*checkShell*/,
7526                "query intent receivers");
7527        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7528        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7529        ComponentName comp = intent.getComponent();
7530        if (comp == null) {
7531            if (intent.getSelector() != null) {
7532                intent = intent.getSelector();
7533                comp = intent.getComponent();
7534            }
7535        }
7536        if (comp != null) {
7537            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7538            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7539            if (si != null) {
7540                // When specifying an explicit component, we prevent the service from being
7541                // used when either 1) the service is in an instant application and the
7542                // caller is not the same instant application or 2) the calling package is
7543                // ephemeral and the activity is not visible to ephemeral applications.
7544                final boolean matchInstantApp =
7545                        (flags & PackageManager.MATCH_INSTANT) != 0;
7546                final boolean matchVisibleToInstantAppOnly =
7547                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7548                final boolean isCallerInstantApp =
7549                        instantAppPkgName != null;
7550                final boolean isTargetSameInstantApp =
7551                        comp.getPackageName().equals(instantAppPkgName);
7552                final boolean isTargetInstantApp =
7553                        (si.applicationInfo.privateFlags
7554                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7555                final boolean isTargetHiddenFromInstantApp =
7556                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7557                final boolean blockResolution =
7558                        !isTargetSameInstantApp
7559                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7560                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7561                                        && isTargetHiddenFromInstantApp));
7562                if (!blockResolution) {
7563                    final ResolveInfo ri = new ResolveInfo();
7564                    ri.serviceInfo = si;
7565                    list.add(ri);
7566                }
7567            }
7568            return list;
7569        }
7570
7571        // reader
7572        synchronized (mPackages) {
7573            String pkgName = intent.getPackage();
7574            if (pkgName == null) {
7575                return applyPostServiceResolutionFilter(
7576                        mServices.queryIntent(intent, resolvedType, flags, userId),
7577                        instantAppPkgName);
7578            }
7579            final PackageParser.Package pkg = mPackages.get(pkgName);
7580            if (pkg != null) {
7581                return applyPostServiceResolutionFilter(
7582                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7583                                userId),
7584                        instantAppPkgName);
7585            }
7586            return Collections.emptyList();
7587        }
7588    }
7589
7590    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7591            String instantAppPkgName) {
7592        if (instantAppPkgName == null) {
7593            return resolveInfos;
7594        }
7595        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7596            final ResolveInfo info = resolveInfos.get(i);
7597            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7598            // allow services that are defined in the provided package
7599            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7600                if (info.serviceInfo.splitName != null
7601                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7602                                info.serviceInfo.splitName)) {
7603                    // requested service is defined in a split that hasn't been installed yet.
7604                    // add the installer to the resolve list
7605                    if (DEBUG_INSTANT) {
7606                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7607                    }
7608                    final ResolveInfo installerInfo = new ResolveInfo(
7609                            mInstantAppInstallerInfo);
7610                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7611                            null /* installFailureActivity */,
7612                            info.serviceInfo.packageName,
7613                            info.serviceInfo.applicationInfo.versionCode,
7614                            info.serviceInfo.splitName);
7615                    // make sure this resolver is the default
7616                    installerInfo.isDefault = true;
7617                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7618                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7619                    // add a non-generic filter
7620                    installerInfo.filter = new IntentFilter();
7621                    // load resources from the correct package
7622                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7623                    resolveInfos.set(i, installerInfo);
7624                }
7625                continue;
7626            }
7627            // allow services that have been explicitly exposed to ephemeral apps
7628            if (!isEphemeralApp
7629                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7630                continue;
7631            }
7632            resolveInfos.remove(i);
7633        }
7634        return resolveInfos;
7635    }
7636
7637    @Override
7638    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7639            String resolvedType, int flags, int userId) {
7640        return new ParceledListSlice<>(
7641                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7642    }
7643
7644    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7645            Intent intent, String resolvedType, int flags, int userId) {
7646        if (!sUserManager.exists(userId)) return Collections.emptyList();
7647        final int callingUid = Binder.getCallingUid();
7648        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7649        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7650                false /*includeInstantApps*/);
7651        ComponentName comp = intent.getComponent();
7652        if (comp == null) {
7653            if (intent.getSelector() != null) {
7654                intent = intent.getSelector();
7655                comp = intent.getComponent();
7656            }
7657        }
7658        if (comp != null) {
7659            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7660            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7661            if (pi != null) {
7662                // When specifying an explicit component, we prevent the provider from being
7663                // used when either 1) the provider is in an instant application and the
7664                // caller is not the same instant application or 2) the calling package is an
7665                // instant application and the provider is not visible to instant applications.
7666                final boolean matchInstantApp =
7667                        (flags & PackageManager.MATCH_INSTANT) != 0;
7668                final boolean matchVisibleToInstantAppOnly =
7669                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7670                final boolean isCallerInstantApp =
7671                        instantAppPkgName != null;
7672                final boolean isTargetSameInstantApp =
7673                        comp.getPackageName().equals(instantAppPkgName);
7674                final boolean isTargetInstantApp =
7675                        (pi.applicationInfo.privateFlags
7676                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7677                final boolean isTargetHiddenFromInstantApp =
7678                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7679                final boolean blockResolution =
7680                        !isTargetSameInstantApp
7681                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7682                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7683                                        && isTargetHiddenFromInstantApp));
7684                if (!blockResolution) {
7685                    final ResolveInfo ri = new ResolveInfo();
7686                    ri.providerInfo = pi;
7687                    list.add(ri);
7688                }
7689            }
7690            return list;
7691        }
7692
7693        // reader
7694        synchronized (mPackages) {
7695            String pkgName = intent.getPackage();
7696            if (pkgName == null) {
7697                return applyPostContentProviderResolutionFilter(
7698                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7699                        instantAppPkgName);
7700            }
7701            final PackageParser.Package pkg = mPackages.get(pkgName);
7702            if (pkg != null) {
7703                return applyPostContentProviderResolutionFilter(
7704                        mProviders.queryIntentForPackage(
7705                        intent, resolvedType, flags, pkg.providers, userId),
7706                        instantAppPkgName);
7707            }
7708            return Collections.emptyList();
7709        }
7710    }
7711
7712    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7713            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7714        if (instantAppPkgName == null) {
7715            return resolveInfos;
7716        }
7717        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7718            final ResolveInfo info = resolveInfos.get(i);
7719            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7720            // allow providers that are defined in the provided package
7721            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7722                if (info.providerInfo.splitName != null
7723                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7724                                info.providerInfo.splitName)) {
7725                    // requested provider is defined in a split that hasn't been installed yet.
7726                    // add the installer to the resolve list
7727                    if (DEBUG_INSTANT) {
7728                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7729                    }
7730                    final ResolveInfo installerInfo = new ResolveInfo(
7731                            mInstantAppInstallerInfo);
7732                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7733                            null /*failureActivity*/,
7734                            info.providerInfo.packageName,
7735                            info.providerInfo.applicationInfo.versionCode,
7736                            info.providerInfo.splitName);
7737                    // make sure this resolver is the default
7738                    installerInfo.isDefault = true;
7739                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7740                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7741                    // add a non-generic filter
7742                    installerInfo.filter = new IntentFilter();
7743                    // load resources from the correct package
7744                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7745                    resolveInfos.set(i, installerInfo);
7746                }
7747                continue;
7748            }
7749            // allow providers that have been explicitly exposed to instant applications
7750            if (!isEphemeralApp
7751                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7752                continue;
7753            }
7754            resolveInfos.remove(i);
7755        }
7756        return resolveInfos;
7757    }
7758
7759    @Override
7760    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7761        final int callingUid = Binder.getCallingUid();
7762        if (getInstantAppPackageName(callingUid) != null) {
7763            return ParceledListSlice.emptyList();
7764        }
7765        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7766        flags = updateFlagsForPackage(flags, userId, null);
7767        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7768        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7769                true /* requireFullPermission */, false /* checkShell */,
7770                "get installed packages");
7771
7772        // writer
7773        synchronized (mPackages) {
7774            ArrayList<PackageInfo> list;
7775            if (listUninstalled) {
7776                list = new ArrayList<>(mSettings.mPackages.size());
7777                for (PackageSetting ps : mSettings.mPackages.values()) {
7778                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7779                        continue;
7780                    }
7781                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7782                        continue;
7783                    }
7784                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7785                    if (pi != null) {
7786                        list.add(pi);
7787                    }
7788                }
7789            } else {
7790                list = new ArrayList<>(mPackages.size());
7791                for (PackageParser.Package p : mPackages.values()) {
7792                    final PackageSetting ps = (PackageSetting) p.mExtras;
7793                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7794                        continue;
7795                    }
7796                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7797                        continue;
7798                    }
7799                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7800                            p.mExtras, flags, userId);
7801                    if (pi != null) {
7802                        list.add(pi);
7803                    }
7804                }
7805            }
7806
7807            return new ParceledListSlice<>(list);
7808        }
7809    }
7810
7811    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7812            String[] permissions, boolean[] tmp, int flags, int userId) {
7813        int numMatch = 0;
7814        final PermissionsState permissionsState = ps.getPermissionsState();
7815        for (int i=0; i<permissions.length; i++) {
7816            final String permission = permissions[i];
7817            if (permissionsState.hasPermission(permission, userId)) {
7818                tmp[i] = true;
7819                numMatch++;
7820            } else {
7821                tmp[i] = false;
7822            }
7823        }
7824        if (numMatch == 0) {
7825            return;
7826        }
7827        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7828
7829        // The above might return null in cases of uninstalled apps or install-state
7830        // skew across users/profiles.
7831        if (pi != null) {
7832            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7833                if (numMatch == permissions.length) {
7834                    pi.requestedPermissions = permissions;
7835                } else {
7836                    pi.requestedPermissions = new String[numMatch];
7837                    numMatch = 0;
7838                    for (int i=0; i<permissions.length; i++) {
7839                        if (tmp[i]) {
7840                            pi.requestedPermissions[numMatch] = permissions[i];
7841                            numMatch++;
7842                        }
7843                    }
7844                }
7845            }
7846            list.add(pi);
7847        }
7848    }
7849
7850    @Override
7851    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7852            String[] permissions, int flags, int userId) {
7853        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7854        flags = updateFlagsForPackage(flags, userId, permissions);
7855        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7856                true /* requireFullPermission */, false /* checkShell */,
7857                "get packages holding permissions");
7858        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7859
7860        // writer
7861        synchronized (mPackages) {
7862            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7863            boolean[] tmpBools = new boolean[permissions.length];
7864            if (listUninstalled) {
7865                for (PackageSetting ps : mSettings.mPackages.values()) {
7866                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7867                            userId);
7868                }
7869            } else {
7870                for (PackageParser.Package pkg : mPackages.values()) {
7871                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7872                    if (ps != null) {
7873                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7874                                userId);
7875                    }
7876                }
7877            }
7878
7879            return new ParceledListSlice<PackageInfo>(list);
7880        }
7881    }
7882
7883    @Override
7884    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7885        final int callingUid = Binder.getCallingUid();
7886        if (getInstantAppPackageName(callingUid) != null) {
7887            return ParceledListSlice.emptyList();
7888        }
7889        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7890        flags = updateFlagsForApplication(flags, userId, null);
7891        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7892
7893        // writer
7894        synchronized (mPackages) {
7895            ArrayList<ApplicationInfo> list;
7896            if (listUninstalled) {
7897                list = new ArrayList<>(mSettings.mPackages.size());
7898                for (PackageSetting ps : mSettings.mPackages.values()) {
7899                    ApplicationInfo ai;
7900                    int effectiveFlags = flags;
7901                    if (ps.isSystem()) {
7902                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7903                    }
7904                    if (ps.pkg != null) {
7905                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7906                            continue;
7907                        }
7908                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7909                            continue;
7910                        }
7911                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7912                                ps.readUserState(userId), userId);
7913                        if (ai != null) {
7914                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7915                        }
7916                    } else {
7917                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7918                        // and already converts to externally visible package name
7919                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7920                                callingUid, effectiveFlags, userId);
7921                    }
7922                    if (ai != null) {
7923                        list.add(ai);
7924                    }
7925                }
7926            } else {
7927                list = new ArrayList<>(mPackages.size());
7928                for (PackageParser.Package p : mPackages.values()) {
7929                    if (p.mExtras != null) {
7930                        PackageSetting ps = (PackageSetting) p.mExtras;
7931                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7932                            continue;
7933                        }
7934                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7935                            continue;
7936                        }
7937                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7938                                ps.readUserState(userId), userId);
7939                        if (ai != null) {
7940                            ai.packageName = resolveExternalPackageNameLPr(p);
7941                            list.add(ai);
7942                        }
7943                    }
7944                }
7945            }
7946
7947            return new ParceledListSlice<>(list);
7948        }
7949    }
7950
7951    @Override
7952    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7953        if (HIDE_EPHEMERAL_APIS) {
7954            return null;
7955        }
7956        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7957            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7958                    "getEphemeralApplications");
7959        }
7960        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7961                true /* requireFullPermission */, false /* checkShell */,
7962                "getEphemeralApplications");
7963        synchronized (mPackages) {
7964            List<InstantAppInfo> instantApps = mInstantAppRegistry
7965                    .getInstantAppsLPr(userId);
7966            if (instantApps != null) {
7967                return new ParceledListSlice<>(instantApps);
7968            }
7969        }
7970        return null;
7971    }
7972
7973    @Override
7974    public boolean isInstantApp(String packageName, int userId) {
7975        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7976                true /* requireFullPermission */, false /* checkShell */,
7977                "isInstantApp");
7978        if (HIDE_EPHEMERAL_APIS) {
7979            return false;
7980        }
7981
7982        synchronized (mPackages) {
7983            int callingUid = Binder.getCallingUid();
7984            if (Process.isIsolated(callingUid)) {
7985                callingUid = mIsolatedOwners.get(callingUid);
7986            }
7987            final PackageSetting ps = mSettings.mPackages.get(packageName);
7988            PackageParser.Package pkg = mPackages.get(packageName);
7989            final boolean returnAllowed =
7990                    ps != null
7991                    && (isCallerSameApp(packageName, callingUid)
7992                            || canViewInstantApps(callingUid, userId)
7993                            || mInstantAppRegistry.isInstantAccessGranted(
7994                                    userId, UserHandle.getAppId(callingUid), ps.appId));
7995            if (returnAllowed) {
7996                return ps.getInstantApp(userId);
7997            }
7998        }
7999        return false;
8000    }
8001
8002    @Override
8003    public byte[] getInstantAppCookie(String packageName, int userId) {
8004        if (HIDE_EPHEMERAL_APIS) {
8005            return null;
8006        }
8007
8008        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8009                true /* requireFullPermission */, false /* checkShell */,
8010                "getInstantAppCookie");
8011        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8012            return null;
8013        }
8014        synchronized (mPackages) {
8015            return mInstantAppRegistry.getInstantAppCookieLPw(
8016                    packageName, userId);
8017        }
8018    }
8019
8020    @Override
8021    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8022        if (HIDE_EPHEMERAL_APIS) {
8023            return true;
8024        }
8025
8026        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8027                true /* requireFullPermission */, true /* checkShell */,
8028                "setInstantAppCookie");
8029        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8030            return false;
8031        }
8032        synchronized (mPackages) {
8033            return mInstantAppRegistry.setInstantAppCookieLPw(
8034                    packageName, cookie, userId);
8035        }
8036    }
8037
8038    @Override
8039    public Bitmap getInstantAppIcon(String packageName, int userId) {
8040        if (HIDE_EPHEMERAL_APIS) {
8041            return null;
8042        }
8043
8044        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8045            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8046                    "getInstantAppIcon");
8047        }
8048        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8049                true /* requireFullPermission */, false /* checkShell */,
8050                "getInstantAppIcon");
8051
8052        synchronized (mPackages) {
8053            return mInstantAppRegistry.getInstantAppIconLPw(
8054                    packageName, userId);
8055        }
8056    }
8057
8058    private boolean isCallerSameApp(String packageName, int uid) {
8059        PackageParser.Package pkg = mPackages.get(packageName);
8060        return pkg != null
8061                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8062    }
8063
8064    @Override
8065    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8066        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8067            return ParceledListSlice.emptyList();
8068        }
8069        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8070    }
8071
8072    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8073        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8074
8075        // reader
8076        synchronized (mPackages) {
8077            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8078            final int userId = UserHandle.getCallingUserId();
8079            while (i.hasNext()) {
8080                final PackageParser.Package p = i.next();
8081                if (p.applicationInfo == null) continue;
8082
8083                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8084                        && !p.applicationInfo.isDirectBootAware();
8085                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8086                        && p.applicationInfo.isDirectBootAware();
8087
8088                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8089                        && (!mSafeMode || isSystemApp(p))
8090                        && (matchesUnaware || matchesAware)) {
8091                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8092                    if (ps != null) {
8093                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8094                                ps.readUserState(userId), userId);
8095                        if (ai != null) {
8096                            finalList.add(ai);
8097                        }
8098                    }
8099                }
8100            }
8101        }
8102
8103        return finalList;
8104    }
8105
8106    @Override
8107    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8108        return resolveContentProviderInternal(name, flags, userId);
8109    }
8110
8111    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8112        if (!sUserManager.exists(userId)) return null;
8113        flags = updateFlagsForComponent(flags, userId, name);
8114        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8115        // reader
8116        synchronized (mPackages) {
8117            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8118            PackageSetting ps = provider != null
8119                    ? mSettings.mPackages.get(provider.owner.packageName)
8120                    : null;
8121            if (ps != null) {
8122                final boolean isInstantApp = ps.getInstantApp(userId);
8123                // normal application; filter out instant application provider
8124                if (instantAppPkgName == null && isInstantApp) {
8125                    return null;
8126                }
8127                // instant application; filter out other instant applications
8128                if (instantAppPkgName != null
8129                        && isInstantApp
8130                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8131                    return null;
8132                }
8133                // instant application; filter out non-exposed provider
8134                if (instantAppPkgName != null
8135                        && !isInstantApp
8136                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8137                    return null;
8138                }
8139                // provider not enabled
8140                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8141                    return null;
8142                }
8143                return PackageParser.generateProviderInfo(
8144                        provider, flags, ps.readUserState(userId), userId);
8145            }
8146            return null;
8147        }
8148    }
8149
8150    /**
8151     * @deprecated
8152     */
8153    @Deprecated
8154    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8155        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8156            return;
8157        }
8158        // reader
8159        synchronized (mPackages) {
8160            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8161                    .entrySet().iterator();
8162            final int userId = UserHandle.getCallingUserId();
8163            while (i.hasNext()) {
8164                Map.Entry<String, PackageParser.Provider> entry = i.next();
8165                PackageParser.Provider p = entry.getValue();
8166                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8167
8168                if (ps != null && p.syncable
8169                        && (!mSafeMode || (p.info.applicationInfo.flags
8170                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8171                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8172                            ps.readUserState(userId), userId);
8173                    if (info != null) {
8174                        outNames.add(entry.getKey());
8175                        outInfo.add(info);
8176                    }
8177                }
8178            }
8179        }
8180    }
8181
8182    @Override
8183    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8184            int uid, int flags, String metaDataKey) {
8185        final int callingUid = Binder.getCallingUid();
8186        final int userId = processName != null ? UserHandle.getUserId(uid)
8187                : UserHandle.getCallingUserId();
8188        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8189        flags = updateFlagsForComponent(flags, userId, processName);
8190        ArrayList<ProviderInfo> finalList = null;
8191        // reader
8192        synchronized (mPackages) {
8193            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8194            while (i.hasNext()) {
8195                final PackageParser.Provider p = i.next();
8196                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8197                if (ps != null && p.info.authority != null
8198                        && (processName == null
8199                                || (p.info.processName.equals(processName)
8200                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8201                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8202
8203                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8204                    // parameter.
8205                    if (metaDataKey != null
8206                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8207                        continue;
8208                    }
8209                    final ComponentName component =
8210                            new ComponentName(p.info.packageName, p.info.name);
8211                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8212                        continue;
8213                    }
8214                    if (finalList == null) {
8215                        finalList = new ArrayList<ProviderInfo>(3);
8216                    }
8217                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8218                            ps.readUserState(userId), userId);
8219                    if (info != null) {
8220                        finalList.add(info);
8221                    }
8222                }
8223            }
8224        }
8225
8226        if (finalList != null) {
8227            Collections.sort(finalList, mProviderInitOrderSorter);
8228            return new ParceledListSlice<ProviderInfo>(finalList);
8229        }
8230
8231        return ParceledListSlice.emptyList();
8232    }
8233
8234    @Override
8235    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8236        // reader
8237        synchronized (mPackages) {
8238            final int callingUid = Binder.getCallingUid();
8239            final int callingUserId = UserHandle.getUserId(callingUid);
8240            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8241            if (ps == null) return null;
8242            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8243                return null;
8244            }
8245            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8246            return PackageParser.generateInstrumentationInfo(i, flags);
8247        }
8248    }
8249
8250    @Override
8251    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8252            String targetPackage, int flags) {
8253        final int callingUid = Binder.getCallingUid();
8254        final int callingUserId = UserHandle.getUserId(callingUid);
8255        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8256        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8257            return ParceledListSlice.emptyList();
8258        }
8259        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8260    }
8261
8262    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8263            int flags) {
8264        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8265
8266        // reader
8267        synchronized (mPackages) {
8268            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8269            while (i.hasNext()) {
8270                final PackageParser.Instrumentation p = i.next();
8271                if (targetPackage == null
8272                        || targetPackage.equals(p.info.targetPackage)) {
8273                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8274                            flags);
8275                    if (ii != null) {
8276                        finalList.add(ii);
8277                    }
8278                }
8279            }
8280        }
8281
8282        return finalList;
8283    }
8284
8285    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8286        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8287        try {
8288            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8289        } finally {
8290            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8291        }
8292    }
8293
8294    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8295        final File[] files = scanDir.listFiles();
8296        if (ArrayUtils.isEmpty(files)) {
8297            Log.d(TAG, "No files in app dir " + scanDir);
8298            return;
8299        }
8300
8301        if (DEBUG_PACKAGE_SCANNING) {
8302            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8303                    + " flags=0x" + Integer.toHexString(parseFlags));
8304        }
8305        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8306                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8307                mParallelPackageParserCallback)) {
8308            // Submit files for parsing in parallel
8309            int fileCount = 0;
8310            for (File file : files) {
8311                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8312                        && !PackageInstallerService.isStageName(file.getName());
8313                if (!isPackage) {
8314                    // Ignore entries which are not packages
8315                    continue;
8316                }
8317                parallelPackageParser.submit(file, parseFlags);
8318                fileCount++;
8319            }
8320
8321            // Process results one by one
8322            for (; fileCount > 0; fileCount--) {
8323                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8324                Throwable throwable = parseResult.throwable;
8325                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8326
8327                if (throwable == null) {
8328                    // TODO(toddke): move lower in the scan chain
8329                    // Static shared libraries have synthetic package names
8330                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8331                        renameStaticSharedLibraryPackage(parseResult.pkg);
8332                    }
8333                    try {
8334                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8335                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8336                                    currentTime, null);
8337                        }
8338                    } catch (PackageManagerException e) {
8339                        errorCode = e.error;
8340                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8341                    }
8342                } else if (throwable instanceof PackageParser.PackageParserException) {
8343                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8344                            throwable;
8345                    errorCode = e.error;
8346                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8347                } else {
8348                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8349                            + parseResult.scanFile, throwable);
8350                }
8351
8352                // Delete invalid userdata apps
8353                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8354                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8355                    logCriticalInfo(Log.WARN,
8356                            "Deleting invalid package at " + parseResult.scanFile);
8357                    removeCodePathLI(parseResult.scanFile);
8358                }
8359            }
8360        }
8361    }
8362
8363    public static void reportSettingsProblem(int priority, String msg) {
8364        logCriticalInfo(priority, msg);
8365    }
8366
8367    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8368            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8369        // When upgrading from pre-N MR1, verify the package time stamp using the package
8370        // directory and not the APK file.
8371        final long lastModifiedTime = mIsPreNMR1Upgrade
8372                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8373        if (ps != null && !forceCollect
8374                && ps.codePathString.equals(pkg.codePath)
8375                && ps.timeStamp == lastModifiedTime
8376                && !isCompatSignatureUpdateNeeded(pkg)
8377                && !isRecoverSignatureUpdateNeeded(pkg)) {
8378            if (ps.signatures.mSigningDetails.signatures != null
8379                    && ps.signatures.mSigningDetails.signatures.length != 0
8380                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8381                            != SignatureSchemeVersion.UNKNOWN) {
8382                // Optimization: reuse the existing cached signing data
8383                // if the package appears to be unchanged.
8384                pkg.mSigningDetails =
8385                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8386                return;
8387            }
8388
8389            Slog.w(TAG, "PackageSetting for " + ps.name
8390                    + " is missing signatures.  Collecting certs again to recover them.");
8391        } else {
8392            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8393                    (forceCollect ? " (forced)" : ""));
8394        }
8395
8396        try {
8397            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8398            PackageParser.collectCertificates(pkg, skipVerify);
8399        } catch (PackageParserException e) {
8400            throw PackageManagerException.from(e);
8401        } finally {
8402            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8403        }
8404    }
8405
8406    /**
8407     *  Traces a package scan.
8408     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8409     */
8410    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8411            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8412        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8413        try {
8414            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8415        } finally {
8416            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8417        }
8418    }
8419
8420    /**
8421     *  Scans a package and returns the newly parsed package.
8422     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8423     */
8424    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8425            long currentTime, UserHandle user) throws PackageManagerException {
8426        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8427        PackageParser pp = new PackageParser();
8428        pp.setSeparateProcesses(mSeparateProcesses);
8429        pp.setOnlyCoreApps(mOnlyCore);
8430        pp.setDisplayMetrics(mMetrics);
8431        pp.setCallback(mPackageParserCallback);
8432
8433        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8434        final PackageParser.Package pkg;
8435        try {
8436            pkg = pp.parsePackage(scanFile, parseFlags);
8437        } catch (PackageParserException e) {
8438            throw PackageManagerException.from(e);
8439        } finally {
8440            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8441        }
8442
8443        // Static shared libraries have synthetic package names
8444        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8445            renameStaticSharedLibraryPackage(pkg);
8446        }
8447
8448        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8449    }
8450
8451    /**
8452     *  Scans a package and returns the newly parsed package.
8453     *  @throws PackageManagerException on a parse error.
8454     */
8455    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8456            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8457            @Nullable UserHandle user)
8458                    throws PackageManagerException {
8459        // If the package has children and this is the first dive in the function
8460        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8461        // packages (parent and children) would be successfully scanned before the
8462        // actual scan since scanning mutates internal state and we want to atomically
8463        // install the package and its children.
8464        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8465            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8466                scanFlags |= SCAN_CHECK_ONLY;
8467            }
8468        } else {
8469            scanFlags &= ~SCAN_CHECK_ONLY;
8470        }
8471
8472        // Scan the parent
8473        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8474                scanFlags, currentTime, user);
8475
8476        // Scan the children
8477        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8478        for (int i = 0; i < childCount; i++) {
8479            PackageParser.Package childPackage = pkg.childPackages.get(i);
8480            addForInitLI(childPackage, parseFlags, scanFlags,
8481                    currentTime, user);
8482        }
8483
8484
8485        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8486            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8487        }
8488
8489        return scannedPkg;
8490    }
8491
8492    /**
8493     * Returns if full apk verification can be skipped for the whole package, including the splits.
8494     */
8495    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8496        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8497            return false;
8498        }
8499        // TODO: Allow base and splits to be verified individually.
8500        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8501            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8502                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8503                    return false;
8504                }
8505            }
8506        }
8507        return true;
8508    }
8509
8510    /**
8511     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8512     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8513     * match one in a trusted source, and should be done separately.
8514     */
8515    private boolean canSkipFullApkVerification(String apkPath) {
8516        byte[] rootHashObserved = null;
8517        try {
8518            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8519            if (rootHashObserved == null) {
8520                return false;  // APK does not contain Merkle tree root hash.
8521            }
8522            synchronized (mInstallLock) {
8523                // Returns whether the observed root hash matches what kernel has.
8524                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8525                return true;
8526            }
8527        } catch (InstallerException | IOException | DigestException |
8528                NoSuchAlgorithmException e) {
8529            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8530        }
8531        return false;
8532    }
8533
8534    /**
8535     * Adds a new package to the internal data structures during platform initialization.
8536     * <p>After adding, the package is known to the system and available for querying.
8537     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8538     * etc...], additional checks are performed. Basic verification [such as ensuring
8539     * matching signatures, checking version codes, etc...] occurs if the package is
8540     * identical to a previously known package. If the package fails a signature check,
8541     * the version installed on /data will be removed. If the version of the new package
8542     * is less than or equal than the version on /data, it will be ignored.
8543     * <p>Regardless of the package location, the results are applied to the internal
8544     * structures and the package is made available to the rest of the system.
8545     * <p>NOTE: The return value should be removed. It's the passed in package object.
8546     */
8547    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8548            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8549            @Nullable UserHandle user)
8550                    throws PackageManagerException {
8551        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8552        final String renamedPkgName;
8553        final PackageSetting disabledPkgSetting;
8554        final boolean isSystemPkgUpdated;
8555        final boolean pkgAlreadyExists;
8556        PackageSetting pkgSetting;
8557
8558        // NOTE: installPackageLI() has the same code to setup the package's
8559        // application info. This probably should be done lower in the call
8560        // stack [such as scanPackageOnly()]. However, we verify the application
8561        // info prior to that [in scanPackageNew()] and thus have to setup
8562        // the application info early.
8563        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8564        pkg.setApplicationInfoCodePath(pkg.codePath);
8565        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8566        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8567        pkg.setApplicationInfoResourcePath(pkg.codePath);
8568        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8569        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8570
8571        synchronized (mPackages) {
8572            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8573            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8574            if (realPkgName != null) {
8575                ensurePackageRenamed(pkg, renamedPkgName);
8576            }
8577            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8578            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8579            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8580            pkgAlreadyExists = pkgSetting != null;
8581            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8582            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8583            isSystemPkgUpdated = disabledPkgSetting != null;
8584
8585            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8586                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8587            }
8588
8589            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8590                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8591                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8592                    : null;
8593            if (DEBUG_PACKAGE_SCANNING
8594                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8595                    && sharedUserSetting != null) {
8596                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8597                        + " (uid=" + sharedUserSetting.userId + "):"
8598                        + " packages=" + sharedUserSetting.packages);
8599            }
8600
8601            if (scanSystemPartition) {
8602                // Potentially prune child packages. If the application on the /system
8603                // partition has been updated via OTA, but, is still disabled by a
8604                // version on /data, cycle through all of its children packages and
8605                // remove children that are no longer defined.
8606                if (isSystemPkgUpdated) {
8607                    final int scannedChildCount = (pkg.childPackages != null)
8608                            ? pkg.childPackages.size() : 0;
8609                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8610                            ? disabledPkgSetting.childPackageNames.size() : 0;
8611                    for (int i = 0; i < disabledChildCount; i++) {
8612                        String disabledChildPackageName =
8613                                disabledPkgSetting.childPackageNames.get(i);
8614                        boolean disabledPackageAvailable = false;
8615                        for (int j = 0; j < scannedChildCount; j++) {
8616                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8617                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8618                                disabledPackageAvailable = true;
8619                                break;
8620                            }
8621                        }
8622                        if (!disabledPackageAvailable) {
8623                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8624                        }
8625                    }
8626                    // we're updating the disabled package, so, scan it as the package setting
8627                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
8628                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8629                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8630                            (pkg == mPlatformPackage), user);
8631                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8632                }
8633            }
8634        }
8635
8636        final boolean newPkgChangedPaths =
8637                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8638        final boolean newPkgVersionGreater =
8639                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8640        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8641                && newPkgChangedPaths && newPkgVersionGreater;
8642        if (isSystemPkgBetter) {
8643            // The version of the application on /system is greater than the version on
8644            // /data. Switch back to the application on /system.
8645            // It's safe to assume the application on /system will correctly scan. If not,
8646            // there won't be a working copy of the application.
8647            synchronized (mPackages) {
8648                // just remove the loaded entries from package lists
8649                mPackages.remove(pkgSetting.name);
8650            }
8651
8652            logCriticalInfo(Log.WARN,
8653                    "System package updated;"
8654                    + " name: " + pkgSetting.name
8655                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8656                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8657
8658            final InstallArgs args = createInstallArgsForExisting(
8659                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8660                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8661            args.cleanUpResourcesLI();
8662            synchronized (mPackages) {
8663                mSettings.enableSystemPackageLPw(pkgSetting.name);
8664            }
8665        }
8666
8667        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8668            // The version of the application on the /system partition is less than or
8669            // equal to the version on the /data partition. Throw an exception and use
8670            // the application already installed on the /data partition.
8671            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8672                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8673                    + " better than this " + pkg.getLongVersionCode());
8674        }
8675
8676        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8677        // force re-collecting certificate.
8678        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8679                disabledPkgSetting);
8680        // Full APK verification can be skipped during certificate collection, only if the file is
8681        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8682        // cases, only data in Signing Block is verified instead of the whole file.
8683        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8684                (forceCollect && canSkipFullPackageVerification(pkg));
8685        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8686
8687        boolean shouldHideSystemApp = false;
8688        // A new application appeared on /system, but, we already have a copy of
8689        // the application installed on /data.
8690        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8691                && !pkgSetting.isSystem()) {
8692
8693            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8694                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
8695                logCriticalInfo(Log.WARN,
8696                        "System package signature mismatch;"
8697                        + " name: " + pkgSetting.name);
8698                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8699                        "scanPackageInternalLI")) {
8700                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8701                }
8702                pkgSetting = null;
8703            } else if (newPkgVersionGreater) {
8704                // The application on /system is newer than the application on /data.
8705                // Simply remove the application on /data [keeping application data]
8706                // and replace it with the version on /system.
8707                logCriticalInfo(Log.WARN,
8708                        "System package enabled;"
8709                        + " name: " + pkgSetting.name
8710                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8711                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8712                InstallArgs args = createInstallArgsForExisting(
8713                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8714                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8715                synchronized (mInstallLock) {
8716                    args.cleanUpResourcesLI();
8717                }
8718            } else {
8719                // The application on /system is older than the application on /data. Hide
8720                // the application on /system and the version on /data will be scanned later
8721                // and re-added like an update.
8722                shouldHideSystemApp = true;
8723                logCriticalInfo(Log.INFO,
8724                        "System package disabled;"
8725                        + " name: " + pkgSetting.name
8726                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8727                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8728            }
8729        }
8730
8731        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8732                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8733
8734        if (shouldHideSystemApp) {
8735            synchronized (mPackages) {
8736                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8737            }
8738        }
8739        return scannedPkg;
8740    }
8741
8742    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8743        // Derive the new package synthetic package name
8744        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8745                + pkg.staticSharedLibVersion);
8746    }
8747
8748    private static String fixProcessName(String defProcessName,
8749            String processName) {
8750        if (processName == null) {
8751            return defProcessName;
8752        }
8753        return processName;
8754    }
8755
8756    /**
8757     * Enforces that only the system UID or root's UID can call a method exposed
8758     * via Binder.
8759     *
8760     * @param message used as message if SecurityException is thrown
8761     * @throws SecurityException if the caller is not system or root
8762     */
8763    private static final void enforceSystemOrRoot(String message) {
8764        final int uid = Binder.getCallingUid();
8765        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8766            throw new SecurityException(message);
8767        }
8768    }
8769
8770    @Override
8771    public void performFstrimIfNeeded() {
8772        enforceSystemOrRoot("Only the system can request fstrim");
8773
8774        // Before everything else, see whether we need to fstrim.
8775        try {
8776            IStorageManager sm = PackageHelper.getStorageManager();
8777            if (sm != null) {
8778                boolean doTrim = false;
8779                final long interval = android.provider.Settings.Global.getLong(
8780                        mContext.getContentResolver(),
8781                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8782                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8783                if (interval > 0) {
8784                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8785                    if (timeSinceLast > interval) {
8786                        doTrim = true;
8787                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8788                                + "; running immediately");
8789                    }
8790                }
8791                if (doTrim) {
8792                    final boolean dexOptDialogShown;
8793                    synchronized (mPackages) {
8794                        dexOptDialogShown = mDexOptDialogShown;
8795                    }
8796                    if (!isFirstBoot() && dexOptDialogShown) {
8797                        try {
8798                            ActivityManager.getService().showBootMessage(
8799                                    mContext.getResources().getString(
8800                                            R.string.android_upgrading_fstrim), true);
8801                        } catch (RemoteException e) {
8802                        }
8803                    }
8804                    sm.runMaintenance();
8805                }
8806            } else {
8807                Slog.e(TAG, "storageManager service unavailable!");
8808            }
8809        } catch (RemoteException e) {
8810            // Can't happen; StorageManagerService is local
8811        }
8812    }
8813
8814    @Override
8815    public void updatePackagesIfNeeded() {
8816        enforceSystemOrRoot("Only the system can request package update");
8817
8818        // We need to re-extract after an OTA.
8819        boolean causeUpgrade = isUpgrade();
8820
8821        // First boot or factory reset.
8822        // Note: we also handle devices that are upgrading to N right now as if it is their
8823        //       first boot, as they do not have profile data.
8824        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8825
8826        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8827        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8828
8829        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8830            return;
8831        }
8832
8833        List<PackageParser.Package> pkgs;
8834        synchronized (mPackages) {
8835            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8836        }
8837
8838        final long startTime = System.nanoTime();
8839        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8840                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
8841                    false /* bootComplete */);
8842
8843        final int elapsedTimeSeconds =
8844                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8845
8846        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8847        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8848        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8849        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8850        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8851    }
8852
8853    /*
8854     * Return the prebuilt profile path given a package base code path.
8855     */
8856    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8857        return pkg.baseCodePath + ".prof";
8858    }
8859
8860    /**
8861     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8862     * containing statistics about the invocation. The array consists of three elements,
8863     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8864     * and {@code numberOfPackagesFailed}.
8865     */
8866    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8867            final int compilationReason, boolean bootComplete) {
8868
8869        int numberOfPackagesVisited = 0;
8870        int numberOfPackagesOptimized = 0;
8871        int numberOfPackagesSkipped = 0;
8872        int numberOfPackagesFailed = 0;
8873        final int numberOfPackagesToDexopt = pkgs.size();
8874
8875        for (PackageParser.Package pkg : pkgs) {
8876            numberOfPackagesVisited++;
8877
8878            boolean useProfileForDexopt = false;
8879
8880            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8881                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8882                // that are already compiled.
8883                File profileFile = new File(getPrebuildProfilePath(pkg));
8884                // Copy profile if it exists.
8885                if (profileFile.exists()) {
8886                    try {
8887                        // We could also do this lazily before calling dexopt in
8888                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8889                        // is that we don't have a good way to say "do this only once".
8890                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8891                                pkg.applicationInfo.uid, pkg.packageName,
8892                                ArtManager.getProfileName(null))) {
8893                            Log.e(TAG, "Installer failed to copy system profile!");
8894                        } else {
8895                            // Disabled as this causes speed-profile compilation during first boot
8896                            // even if things are already compiled.
8897                            // useProfileForDexopt = true;
8898                        }
8899                    } catch (Exception e) {
8900                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8901                                e);
8902                    }
8903                } else {
8904                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8905                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8906                    // minimize the number off apps being speed-profile compiled during first boot.
8907                    // The other paths will not change the filter.
8908                    if (disabledPs != null && disabledPs.pkg.isStub) {
8909                        // The package is the stub one, remove the stub suffix to get the normal
8910                        // package and APK names.
8911                        String systemProfilePath =
8912                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8913                        profileFile = new File(systemProfilePath);
8914                        // If we have a profile for a compressed APK, copy it to the reference
8915                        // location.
8916                        // Note that copying the profile here will cause it to override the
8917                        // reference profile every OTA even though the existing reference profile
8918                        // may have more data. We can't copy during decompression since the
8919                        // directories are not set up at that point.
8920                        if (profileFile.exists()) {
8921                            try {
8922                                // We could also do this lazily before calling dexopt in
8923                                // PackageDexOptimizer to prevent this happening on first boot. The
8924                                // issue is that we don't have a good way to say "do this only
8925                                // once".
8926                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8927                                        pkg.applicationInfo.uid, pkg.packageName,
8928                                        ArtManager.getProfileName(null))) {
8929                                    Log.e(TAG, "Failed to copy system profile for stub package!");
8930                                } else {
8931                                    useProfileForDexopt = true;
8932                                }
8933                            } catch (Exception e) {
8934                                Log.e(TAG, "Failed to copy profile " +
8935                                        profileFile.getAbsolutePath() + " ", e);
8936                            }
8937                        }
8938                    }
8939                }
8940            }
8941
8942            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8943                if (DEBUG_DEXOPT) {
8944                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8945                }
8946                numberOfPackagesSkipped++;
8947                continue;
8948            }
8949
8950            if (DEBUG_DEXOPT) {
8951                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8952                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8953            }
8954
8955            if (showDialog) {
8956                try {
8957                    ActivityManager.getService().showBootMessage(
8958                            mContext.getResources().getString(R.string.android_upgrading_apk,
8959                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8960                } catch (RemoteException e) {
8961                }
8962                synchronized (mPackages) {
8963                    mDexOptDialogShown = true;
8964                }
8965            }
8966
8967            int pkgCompilationReason = compilationReason;
8968            if (useProfileForDexopt) {
8969                // Use background dexopt mode to try and use the profile. Note that this does not
8970                // guarantee usage of the profile.
8971                pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT;
8972            }
8973
8974            // checkProfiles is false to avoid merging profiles during boot which
8975            // might interfere with background compilation (b/28612421).
8976            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8977            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8978            // trade-off worth doing to save boot time work.
8979            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
8980            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
8981                    pkg.packageName,
8982                    pkgCompilationReason,
8983                    dexoptFlags));
8984
8985            switch (primaryDexOptStaus) {
8986                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8987                    numberOfPackagesOptimized++;
8988                    break;
8989                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8990                    numberOfPackagesSkipped++;
8991                    break;
8992                case PackageDexOptimizer.DEX_OPT_FAILED:
8993                    numberOfPackagesFailed++;
8994                    break;
8995                default:
8996                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
8997                    break;
8998            }
8999        }
9000
9001        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9002                numberOfPackagesFailed };
9003    }
9004
9005    @Override
9006    public void notifyPackageUse(String packageName, int reason) {
9007        synchronized (mPackages) {
9008            final int callingUid = Binder.getCallingUid();
9009            final int callingUserId = UserHandle.getUserId(callingUid);
9010            if (getInstantAppPackageName(callingUid) != null) {
9011                if (!isCallerSameApp(packageName, callingUid)) {
9012                    return;
9013                }
9014            } else {
9015                if (isInstantApp(packageName, callingUserId)) {
9016                    return;
9017                }
9018            }
9019            notifyPackageUseLocked(packageName, reason);
9020        }
9021    }
9022
9023    @GuardedBy("mPackages")
9024    private void notifyPackageUseLocked(String packageName, int reason) {
9025        final PackageParser.Package p = mPackages.get(packageName);
9026        if (p == null) {
9027            return;
9028        }
9029        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9030    }
9031
9032    @Override
9033    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9034            List<String> classPaths, String loaderIsa) {
9035        int userId = UserHandle.getCallingUserId();
9036        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9037        if (ai == null) {
9038            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9039                + loadingPackageName + ", user=" + userId);
9040            return;
9041        }
9042        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9043    }
9044
9045    @Override
9046    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9047            IDexModuleRegisterCallback callback) {
9048        int userId = UserHandle.getCallingUserId();
9049        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9050        DexManager.RegisterDexModuleResult result;
9051        if (ai == null) {
9052            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9053                     " calling user. package=" + packageName + ", user=" + userId);
9054            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9055        } else {
9056            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9057        }
9058
9059        if (callback != null) {
9060            mHandler.post(() -> {
9061                try {
9062                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9063                } catch (RemoteException e) {
9064                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9065                }
9066            });
9067        }
9068    }
9069
9070    /**
9071     * Ask the package manager to perform a dex-opt with the given compiler filter.
9072     *
9073     * Note: exposed only for the shell command to allow moving packages explicitly to a
9074     *       definite state.
9075     */
9076    @Override
9077    public boolean performDexOptMode(String packageName,
9078            boolean checkProfiles, String targetCompilerFilter, boolean force,
9079            boolean bootComplete, String splitName) {
9080        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9081                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9082                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9083        return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN,
9084                targetCompilerFilter, splitName, flags));
9085    }
9086
9087    /**
9088     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9089     * secondary dex files belonging to the given package.
9090     *
9091     * Note: exposed only for the shell command to allow moving packages explicitly to a
9092     *       definite state.
9093     */
9094    @Override
9095    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9096            boolean force) {
9097        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9098                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9099                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9100                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9101        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9102    }
9103
9104    /*package*/ boolean performDexOpt(DexoptOptions options) {
9105        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9106            return false;
9107        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9108            return false;
9109        }
9110
9111        if (options.isDexoptOnlySecondaryDex()) {
9112            return mDexManager.dexoptSecondaryDex(options);
9113        } else {
9114            int dexoptStatus = performDexOptWithStatus(options);
9115            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9116        }
9117    }
9118
9119    /**
9120     * Perform dexopt on the given package and return one of following result:
9121     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9122     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9123     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9124     */
9125    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9126        return performDexOptTraced(options);
9127    }
9128
9129    private int performDexOptTraced(DexoptOptions options) {
9130        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9131        try {
9132            return performDexOptInternal(options);
9133        } finally {
9134            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9135        }
9136    }
9137
9138    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9139    // if the package can now be considered up to date for the given filter.
9140    private int performDexOptInternal(DexoptOptions options) {
9141        PackageParser.Package p;
9142        synchronized (mPackages) {
9143            p = mPackages.get(options.getPackageName());
9144            if (p == null) {
9145                // Package could not be found. Report failure.
9146                return PackageDexOptimizer.DEX_OPT_FAILED;
9147            }
9148            mPackageUsage.maybeWriteAsync(mPackages);
9149            mCompilerStats.maybeWriteAsync();
9150        }
9151        long callingId = Binder.clearCallingIdentity();
9152        try {
9153            synchronized (mInstallLock) {
9154                return performDexOptInternalWithDependenciesLI(p, options);
9155            }
9156        } finally {
9157            Binder.restoreCallingIdentity(callingId);
9158        }
9159    }
9160
9161    public ArraySet<String> getOptimizablePackages() {
9162        ArraySet<String> pkgs = new ArraySet<String>();
9163        synchronized (mPackages) {
9164            for (PackageParser.Package p : mPackages.values()) {
9165                if (PackageDexOptimizer.canOptimizePackage(p)) {
9166                    pkgs.add(p.packageName);
9167                }
9168            }
9169        }
9170        return pkgs;
9171    }
9172
9173    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9174            DexoptOptions options) {
9175        // Select the dex optimizer based on the force parameter.
9176        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9177        //       allocate an object here.
9178        PackageDexOptimizer pdo = options.isForce()
9179                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9180                : mPackageDexOptimizer;
9181
9182        // Dexopt all dependencies first. Note: we ignore the return value and march on
9183        // on errors.
9184        // Note that we are going to call performDexOpt on those libraries as many times as
9185        // they are referenced in packages. When we do a batch of performDexOpt (for example
9186        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9187        // and the first package that uses the library will dexopt it. The
9188        // others will see that the compiled code for the library is up to date.
9189        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9190        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9191        if (!deps.isEmpty()) {
9192            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9193                    options.getCompilationReason(), options.getCompilerFilter(),
9194                    options.getSplitName(),
9195                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9196            for (PackageParser.Package depPackage : deps) {
9197                // TODO: Analyze and investigate if we (should) profile libraries.
9198                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9199                        getOrCreateCompilerPackageStats(depPackage),
9200                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9201            }
9202        }
9203        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9204                getOrCreateCompilerPackageStats(p),
9205                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9206    }
9207
9208    /**
9209     * Reconcile the information we have about the secondary dex files belonging to
9210     * {@code packagName} and the actual dex files. For all dex files that were
9211     * deleted, update the internal records and delete the generated oat files.
9212     */
9213    @Override
9214    public void reconcileSecondaryDexFiles(String packageName) {
9215        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9216            return;
9217        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9218            return;
9219        }
9220        mDexManager.reconcileSecondaryDexFiles(packageName);
9221    }
9222
9223    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9224    // a reference there.
9225    /*package*/ DexManager getDexManager() {
9226        return mDexManager;
9227    }
9228
9229    /**
9230     * Execute the background dexopt job immediately.
9231     */
9232    @Override
9233    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9234        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9235            return false;
9236        }
9237        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9238    }
9239
9240    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9241        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9242                || p.usesStaticLibraries != null) {
9243            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9244            Set<String> collectedNames = new HashSet<>();
9245            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9246
9247            retValue.remove(p);
9248
9249            return retValue;
9250        } else {
9251            return Collections.emptyList();
9252        }
9253    }
9254
9255    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9256            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9257        if (!collectedNames.contains(p.packageName)) {
9258            collectedNames.add(p.packageName);
9259            collected.add(p);
9260
9261            if (p.usesLibraries != null) {
9262                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9263                        null, collected, collectedNames);
9264            }
9265            if (p.usesOptionalLibraries != null) {
9266                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9267                        null, collected, collectedNames);
9268            }
9269            if (p.usesStaticLibraries != null) {
9270                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9271                        p.usesStaticLibrariesVersions, collected, collectedNames);
9272            }
9273        }
9274    }
9275
9276    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9277            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9278        final int libNameCount = libs.size();
9279        for (int i = 0; i < libNameCount; i++) {
9280            String libName = libs.get(i);
9281            long version = (versions != null && versions.length == libNameCount)
9282                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9283            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9284            if (libPkg != null) {
9285                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9286            }
9287        }
9288    }
9289
9290    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9291        synchronized (mPackages) {
9292            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9293            if (libEntry != null) {
9294                return mPackages.get(libEntry.apk);
9295            }
9296            return null;
9297        }
9298    }
9299
9300    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9301        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9302        if (versionedLib == null) {
9303            return null;
9304        }
9305        return versionedLib.get(version);
9306    }
9307
9308    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9309        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9310                pkg.staticSharedLibName);
9311        if (versionedLib == null) {
9312            return null;
9313        }
9314        long previousLibVersion = -1;
9315        final int versionCount = versionedLib.size();
9316        for (int i = 0; i < versionCount; i++) {
9317            final long libVersion = versionedLib.keyAt(i);
9318            if (libVersion < pkg.staticSharedLibVersion) {
9319                previousLibVersion = Math.max(previousLibVersion, libVersion);
9320            }
9321        }
9322        if (previousLibVersion >= 0) {
9323            return versionedLib.get(previousLibVersion);
9324        }
9325        return null;
9326    }
9327
9328    public void shutdown() {
9329        mPackageUsage.writeNow(mPackages);
9330        mCompilerStats.writeNow();
9331        mDexManager.writePackageDexUsageNow();
9332    }
9333
9334    @Override
9335    public void dumpProfiles(String packageName) {
9336        PackageParser.Package pkg;
9337        synchronized (mPackages) {
9338            pkg = mPackages.get(packageName);
9339            if (pkg == null) {
9340                throw new IllegalArgumentException("Unknown package: " + packageName);
9341            }
9342        }
9343        /* Only the shell, root, or the app user should be able to dump profiles. */
9344        int callingUid = Binder.getCallingUid();
9345        if (callingUid != Process.SHELL_UID &&
9346            callingUid != Process.ROOT_UID &&
9347            callingUid != pkg.applicationInfo.uid) {
9348            throw new SecurityException("dumpProfiles");
9349        }
9350
9351        synchronized (mInstallLock) {
9352            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9353            mArtManagerService.dumpProfiles(pkg);
9354            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9355        }
9356    }
9357
9358    @Override
9359    public void forceDexOpt(String packageName) {
9360        enforceSystemOrRoot("forceDexOpt");
9361
9362        PackageParser.Package pkg;
9363        synchronized (mPackages) {
9364            pkg = mPackages.get(packageName);
9365            if (pkg == null) {
9366                throw new IllegalArgumentException("Unknown package: " + packageName);
9367            }
9368        }
9369
9370        synchronized (mInstallLock) {
9371            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9372
9373            // Whoever is calling forceDexOpt wants a compiled package.
9374            // Don't use profiles since that may cause compilation to be skipped.
9375            final int res = performDexOptInternalWithDependenciesLI(
9376                    pkg,
9377                    new DexoptOptions(packageName,
9378                            getDefaultCompilerFilter(),
9379                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9380
9381            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9382            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9383                throw new IllegalStateException("Failed to dexopt: " + res);
9384            }
9385        }
9386    }
9387
9388    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9389        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9390            Slog.w(TAG, "Unable to update from " + oldPkg.name
9391                    + " to " + newPkg.packageName
9392                    + ": old package not in system partition");
9393            return false;
9394        } else if (mPackages.get(oldPkg.name) != null) {
9395            Slog.w(TAG, "Unable to update from " + oldPkg.name
9396                    + " to " + newPkg.packageName
9397                    + ": old package still exists");
9398            return false;
9399        }
9400        return true;
9401    }
9402
9403    void removeCodePathLI(File codePath) {
9404        if (codePath.isDirectory()) {
9405            try {
9406                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9407            } catch (InstallerException e) {
9408                Slog.w(TAG, "Failed to remove code path", e);
9409            }
9410        } else {
9411            codePath.delete();
9412        }
9413    }
9414
9415    private int[] resolveUserIds(int userId) {
9416        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9417    }
9418
9419    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9420        if (pkg == null) {
9421            Slog.wtf(TAG, "Package was null!", new Throwable());
9422            return;
9423        }
9424        clearAppDataLeafLIF(pkg, userId, flags);
9425        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9426        for (int i = 0; i < childCount; i++) {
9427            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9428        }
9429
9430        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9431    }
9432
9433    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9434        final PackageSetting ps;
9435        synchronized (mPackages) {
9436            ps = mSettings.mPackages.get(pkg.packageName);
9437        }
9438        for (int realUserId : resolveUserIds(userId)) {
9439            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9440            try {
9441                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9442                        ceDataInode);
9443            } catch (InstallerException e) {
9444                Slog.w(TAG, String.valueOf(e));
9445            }
9446        }
9447    }
9448
9449    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9450        if (pkg == null) {
9451            Slog.wtf(TAG, "Package was null!", new Throwable());
9452            return;
9453        }
9454        destroyAppDataLeafLIF(pkg, userId, flags);
9455        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9456        for (int i = 0; i < childCount; i++) {
9457            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9458        }
9459    }
9460
9461    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9462        final PackageSetting ps;
9463        synchronized (mPackages) {
9464            ps = mSettings.mPackages.get(pkg.packageName);
9465        }
9466        for (int realUserId : resolveUserIds(userId)) {
9467            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9468            try {
9469                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9470                        ceDataInode);
9471            } catch (InstallerException e) {
9472                Slog.w(TAG, String.valueOf(e));
9473            }
9474            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9475        }
9476    }
9477
9478    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9479        if (pkg == null) {
9480            Slog.wtf(TAG, "Package was null!", new Throwable());
9481            return;
9482        }
9483        destroyAppProfilesLeafLIF(pkg);
9484        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9485        for (int i = 0; i < childCount; i++) {
9486            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9487        }
9488    }
9489
9490    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9491        try {
9492            mInstaller.destroyAppProfiles(pkg.packageName);
9493        } catch (InstallerException e) {
9494            Slog.w(TAG, String.valueOf(e));
9495        }
9496    }
9497
9498    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9499        if (pkg == null) {
9500            Slog.wtf(TAG, "Package was null!", new Throwable());
9501            return;
9502        }
9503        mArtManagerService.clearAppProfiles(pkg);
9504        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9505        for (int i = 0; i < childCount; i++) {
9506            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9507        }
9508    }
9509
9510    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9511            long lastUpdateTime) {
9512        // Set parent install/update time
9513        PackageSetting ps = (PackageSetting) pkg.mExtras;
9514        if (ps != null) {
9515            ps.firstInstallTime = firstInstallTime;
9516            ps.lastUpdateTime = lastUpdateTime;
9517        }
9518        // Set children install/update time
9519        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9520        for (int i = 0; i < childCount; i++) {
9521            PackageParser.Package childPkg = pkg.childPackages.get(i);
9522            ps = (PackageSetting) childPkg.mExtras;
9523            if (ps != null) {
9524                ps.firstInstallTime = firstInstallTime;
9525                ps.lastUpdateTime = lastUpdateTime;
9526            }
9527        }
9528    }
9529
9530    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9531            SharedLibraryEntry file,
9532            PackageParser.Package changingLib) {
9533        if (file.path != null) {
9534            usesLibraryFiles.add(file.path);
9535            return;
9536        }
9537        PackageParser.Package p = mPackages.get(file.apk);
9538        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9539            // If we are doing this while in the middle of updating a library apk,
9540            // then we need to make sure to use that new apk for determining the
9541            // dependencies here.  (We haven't yet finished committing the new apk
9542            // to the package manager state.)
9543            if (p == null || p.packageName.equals(changingLib.packageName)) {
9544                p = changingLib;
9545            }
9546        }
9547        if (p != null) {
9548            usesLibraryFiles.addAll(p.getAllCodePaths());
9549            if (p.usesLibraryFiles != null) {
9550                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9551            }
9552        }
9553    }
9554
9555    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9556            PackageParser.Package changingLib) throws PackageManagerException {
9557        if (pkg == null) {
9558            return;
9559        }
9560        // The collection used here must maintain the order of addition (so
9561        // that libraries are searched in the correct order) and must have no
9562        // duplicates.
9563        Set<String> usesLibraryFiles = null;
9564        if (pkg.usesLibraries != null) {
9565            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9566                    null, null, pkg.packageName, changingLib, true,
9567                    pkg.applicationInfo.targetSdkVersion, null);
9568        }
9569        if (pkg.usesStaticLibraries != null) {
9570            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9571                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9572                    pkg.packageName, changingLib, true,
9573                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9574        }
9575        if (pkg.usesOptionalLibraries != null) {
9576            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9577                    null, null, pkg.packageName, changingLib, false,
9578                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9579        }
9580        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9581            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9582        } else {
9583            pkg.usesLibraryFiles = null;
9584        }
9585    }
9586
9587    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9588            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9589            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9590            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9591            throws PackageManagerException {
9592        final int libCount = requestedLibraries.size();
9593        for (int i = 0; i < libCount; i++) {
9594            final String libName = requestedLibraries.get(i);
9595            final long libVersion = requiredVersions != null ? requiredVersions[i]
9596                    : SharedLibraryInfo.VERSION_UNDEFINED;
9597            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9598            if (libEntry == null) {
9599                if (required) {
9600                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9601                            "Package " + packageName + " requires unavailable shared library "
9602                                    + libName + "; failing!");
9603                } else if (DEBUG_SHARED_LIBRARIES) {
9604                    Slog.i(TAG, "Package " + packageName
9605                            + " desires unavailable shared library "
9606                            + libName + "; ignoring!");
9607                }
9608            } else {
9609                if (requiredVersions != null && requiredCertDigests != null) {
9610                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9611                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9612                            "Package " + packageName + " requires unavailable static shared"
9613                                    + " library " + libName + " version "
9614                                    + libEntry.info.getLongVersion() + "; failing!");
9615                    }
9616
9617                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9618                    if (libPkg == null) {
9619                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9620                                "Package " + packageName + " requires unavailable static shared"
9621                                        + " library; failing!");
9622                    }
9623
9624                    final String[] expectedCertDigests = requiredCertDigests[i];
9625
9626
9627                    if (expectedCertDigests.length > 1) {
9628
9629                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9630                        final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9631                                ? PackageUtils.computeSignaturesSha256Digests(
9632                                libPkg.mSigningDetails.signatures)
9633                                : PackageUtils.computeSignaturesSha256Digests(
9634                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9635
9636                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9637                        // target O we don't parse the "additional-certificate" tags similarly
9638                        // how we only consider all certs only for apps targeting O (see above).
9639                        // Therefore, the size check is safe to make.
9640                        if (expectedCertDigests.length != libCertDigests.length) {
9641                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9642                                    "Package " + packageName + " requires differently signed" +
9643                                            " static shared library; failing!");
9644                        }
9645
9646                        // Use a predictable order as signature order may vary
9647                        Arrays.sort(libCertDigests);
9648                        Arrays.sort(expectedCertDigests);
9649
9650                        final int certCount = libCertDigests.length;
9651                        for (int j = 0; j < certCount; j++) {
9652                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9653                                throw new PackageManagerException(
9654                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9655                                        "Package " + packageName + " requires differently signed" +
9656                                                " static shared library; failing!");
9657                            }
9658                        }
9659                    } else {
9660
9661                        // lib signing cert could have rotated beyond the one expected, check to see
9662                        // if the new one has been blessed by the old
9663                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9664                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9665                            throw new PackageManagerException(
9666                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9667                                    "Package " + packageName + " requires differently signed" +
9668                                            " static shared library; failing!");
9669                        }
9670                    }
9671                }
9672
9673                if (outUsedLibraries == null) {
9674                    // Use LinkedHashSet to preserve the order of files added to
9675                    // usesLibraryFiles while eliminating duplicates.
9676                    outUsedLibraries = new LinkedHashSet<>();
9677                }
9678                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9679            }
9680        }
9681        return outUsedLibraries;
9682    }
9683
9684    private static boolean hasString(List<String> list, List<String> which) {
9685        if (list == null) {
9686            return false;
9687        }
9688        for (int i=list.size()-1; i>=0; i--) {
9689            for (int j=which.size()-1; j>=0; j--) {
9690                if (which.get(j).equals(list.get(i))) {
9691                    return true;
9692                }
9693            }
9694        }
9695        return false;
9696    }
9697
9698    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9699            PackageParser.Package changingPkg) {
9700        ArrayList<PackageParser.Package> res = null;
9701        for (PackageParser.Package pkg : mPackages.values()) {
9702            if (changingPkg != null
9703                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9704                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9705                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9706                            changingPkg.staticSharedLibName)) {
9707                return null;
9708            }
9709            if (res == null) {
9710                res = new ArrayList<>();
9711            }
9712            res.add(pkg);
9713            try {
9714                updateSharedLibrariesLPr(pkg, changingPkg);
9715            } catch (PackageManagerException e) {
9716                // If a system app update or an app and a required lib missing we
9717                // delete the package and for updated system apps keep the data as
9718                // it is better for the user to reinstall than to be in an limbo
9719                // state. Also libs disappearing under an app should never happen
9720                // - just in case.
9721                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9722                    final int flags = pkg.isUpdatedSystemApp()
9723                            ? PackageManager.DELETE_KEEP_DATA : 0;
9724                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9725                            flags , null, true, null);
9726                }
9727                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9728            }
9729        }
9730        return res;
9731    }
9732
9733    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9734            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9735            @Nullable UserHandle user) throws PackageManagerException {
9736        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9737        // If the package has children and this is the first dive in the function
9738        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9739        // whether all packages (parent and children) would be successfully scanned
9740        // before the actual scan since scanning mutates internal state and we want
9741        // to atomically install the package and its children.
9742        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9743            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9744                scanFlags |= SCAN_CHECK_ONLY;
9745            }
9746        } else {
9747            scanFlags &= ~SCAN_CHECK_ONLY;
9748        }
9749
9750        final PackageParser.Package scannedPkg;
9751        try {
9752            // Scan the parent
9753            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9754            // Scan the children
9755            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9756            for (int i = 0; i < childCount; i++) {
9757                PackageParser.Package childPkg = pkg.childPackages.get(i);
9758                scanPackageNewLI(childPkg, parseFlags,
9759                        scanFlags, currentTime, user);
9760            }
9761        } finally {
9762            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9763        }
9764
9765        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9766            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9767        }
9768
9769        return scannedPkg;
9770    }
9771
9772    /** The result of a package scan. */
9773    private static class ScanResult {
9774        /** Whether or not the package scan was successful */
9775        public final boolean success;
9776        /**
9777         * The final package settings. This may be the same object passed in
9778         * the {@link ScanRequest}, but, with modified values.
9779         */
9780        @Nullable public final PackageSetting pkgSetting;
9781        /** ABI code paths that have changed in the package scan */
9782        @Nullable public final List<String> changedAbiCodePath;
9783        public ScanResult(
9784                boolean success,
9785                @Nullable PackageSetting pkgSetting,
9786                @Nullable List<String> changedAbiCodePath) {
9787            this.success = success;
9788            this.pkgSetting = pkgSetting;
9789            this.changedAbiCodePath = changedAbiCodePath;
9790        }
9791    }
9792
9793    /** A package to be scanned */
9794    private static class ScanRequest {
9795        /** The parsed package */
9796        @NonNull public final PackageParser.Package pkg;
9797        /** Shared user settings, if the package has a shared user */
9798        @Nullable public final SharedUserSetting sharedUserSetting;
9799        /**
9800         * Package settings of the currently installed version.
9801         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9802         * during scan.
9803         */
9804        @Nullable public final PackageSetting pkgSetting;
9805        /** A copy of the settings for the currently installed version */
9806        @Nullable public final PackageSetting oldPkgSetting;
9807        /** Package settings for the disabled version on the /system partition */
9808        @Nullable public final PackageSetting disabledPkgSetting;
9809        /** Package settings for the installed version under its original package name */
9810        @Nullable public final PackageSetting originalPkgSetting;
9811        /** The real package name of a renamed application */
9812        @Nullable public final String realPkgName;
9813        public final @ParseFlags int parseFlags;
9814        public final @ScanFlags int scanFlags;
9815        /** The user for which the package is being scanned */
9816        @Nullable public final UserHandle user;
9817        /** Whether or not the platform package is being scanned */
9818        public final boolean isPlatformPackage;
9819        public ScanRequest(
9820                @NonNull PackageParser.Package pkg,
9821                @Nullable SharedUserSetting sharedUserSetting,
9822                @Nullable PackageSetting pkgSetting,
9823                @Nullable PackageSetting disabledPkgSetting,
9824                @Nullable PackageSetting originalPkgSetting,
9825                @Nullable String realPkgName,
9826                @ParseFlags int parseFlags,
9827                @ScanFlags int scanFlags,
9828                boolean isPlatformPackage,
9829                @Nullable UserHandle user) {
9830            this.pkg = pkg;
9831            this.pkgSetting = pkgSetting;
9832            this.sharedUserSetting = sharedUserSetting;
9833            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9834            this.disabledPkgSetting = disabledPkgSetting;
9835            this.originalPkgSetting = originalPkgSetting;
9836            this.realPkgName = realPkgName;
9837            this.parseFlags = parseFlags;
9838            this.scanFlags = scanFlags;
9839            this.isPlatformPackage = isPlatformPackage;
9840            this.user = user;
9841        }
9842    }
9843
9844    /**
9845     * Returns the actual scan flags depending upon the state of the other settings.
9846     * <p>Updated system applications will not have the following flags set
9847     * by default and need to be adjusted after the fact:
9848     * <ul>
9849     * <li>{@link #SCAN_AS_SYSTEM}</li>
9850     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9851     * <li>{@link #SCAN_AS_OEM}</li>
9852     * <li>{@link #SCAN_AS_VENDOR}</li>
9853     * <li>{@link #SCAN_AS_PRODUCT}</li>
9854     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9855     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9856     * </ul>
9857     */
9858    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9859            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9860            PackageParser.Package pkg) {
9861        if (disabledPkgSetting != null) {
9862            // updated system application, must at least have SCAN_AS_SYSTEM
9863            scanFlags |= SCAN_AS_SYSTEM;
9864            if ((disabledPkgSetting.pkgPrivateFlags
9865                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9866                scanFlags |= SCAN_AS_PRIVILEGED;
9867            }
9868            if ((disabledPkgSetting.pkgPrivateFlags
9869                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9870                scanFlags |= SCAN_AS_OEM;
9871            }
9872            if ((disabledPkgSetting.pkgPrivateFlags
9873                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9874                scanFlags |= SCAN_AS_VENDOR;
9875            }
9876            if ((disabledPkgSetting.pkgPrivateFlags
9877                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9878                scanFlags |= SCAN_AS_PRODUCT;
9879            }
9880        }
9881        if (pkgSetting != null) {
9882            final int userId = ((user == null) ? 0 : user.getIdentifier());
9883            if (pkgSetting.getInstantApp(userId)) {
9884                scanFlags |= SCAN_AS_INSTANT_APP;
9885            }
9886            if (pkgSetting.getVirtulalPreload(userId)) {
9887                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9888            }
9889        }
9890
9891        // Scan as privileged apps that share a user with a priv-app.
9892        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9893                && (pkg.mSharedUserId != null)) {
9894            SharedUserSetting sharedUserSetting = null;
9895            try {
9896                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9897            } catch (PackageManagerException ignore) {}
9898            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9899                // Exempt SharedUsers signed with the platform key.
9900                // TODO(b/72378145) Fix this exemption. Force signature apps
9901                // to whitelist their privileged permissions just like other
9902                // priv-apps.
9903                synchronized (mPackages) {
9904                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9905                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
9906                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
9907                        scanFlags |= SCAN_AS_PRIVILEGED;
9908                    }
9909                }
9910            }
9911        }
9912
9913        return scanFlags;
9914    }
9915
9916    @GuardedBy("mInstallLock")
9917    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
9918            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9919            @Nullable UserHandle user) throws PackageManagerException {
9920
9921        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9922        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
9923        if (realPkgName != null) {
9924            ensurePackageRenamed(pkg, renamedPkgName);
9925        }
9926        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
9927        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9928        final PackageSetting disabledPkgSetting =
9929                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9930
9931        if (mTransferedPackages.contains(pkg.packageName)) {
9932            Slog.w(TAG, "Package " + pkg.packageName
9933                    + " was transferred to another, but its .apk remains");
9934        }
9935
9936        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
9937        synchronized (mPackages) {
9938            applyPolicy(pkg, parseFlags, scanFlags);
9939            assertPackageIsValid(pkg, parseFlags, scanFlags);
9940
9941            SharedUserSetting sharedUserSetting = null;
9942            if (pkg.mSharedUserId != null) {
9943                // SIDE EFFECTS; may potentially allocate a new shared user
9944                sharedUserSetting = mSettings.getSharedUserLPw(
9945                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9946                if (DEBUG_PACKAGE_SCANNING) {
9947                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
9948                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
9949                                + " (uid=" + sharedUserSetting.userId + "):"
9950                                + " packages=" + sharedUserSetting.packages);
9951                }
9952            }
9953
9954            boolean scanSucceeded = false;
9955            try {
9956                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
9957                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
9958                        (pkg == mPlatformPackage), user);
9959                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
9960                if (result.success) {
9961                    commitScanResultsLocked(request, result);
9962                }
9963                scanSucceeded = true;
9964            } finally {
9965                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9966                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
9967                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9968                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9969                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9970                  }
9971            }
9972        }
9973        return pkg;
9974    }
9975
9976    /**
9977     * Commits the package scan and modifies system state.
9978     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
9979     * of committing the package, leaving the system in an inconsistent state.
9980     * This needs to be fixed so, once we get to this point, no errors are
9981     * possible and the system is not left in an inconsistent state.
9982     */
9983    @GuardedBy("mPackages")
9984    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
9985            throws PackageManagerException {
9986        final PackageParser.Package pkg = request.pkg;
9987        final @ParseFlags int parseFlags = request.parseFlags;
9988        final @ScanFlags int scanFlags = request.scanFlags;
9989        final PackageSetting oldPkgSetting = request.oldPkgSetting;
9990        final PackageSetting originalPkgSetting = request.originalPkgSetting;
9991        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
9992        final UserHandle user = request.user;
9993        final String realPkgName = request.realPkgName;
9994        final PackageSetting pkgSetting = result.pkgSetting;
9995        final List<String> changedAbiCodePath = result.changedAbiCodePath;
9996        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
9997
9998        if (newPkgSettingCreated) {
9999            if (originalPkgSetting != null) {
10000                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10001            }
10002            // THROWS: when we can't allocate a user id. add call to check if there's
10003            // enough space to ensure we won't throw; otherwise, don't modify state
10004            mSettings.addUserToSettingLPw(pkgSetting);
10005
10006            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10007                mTransferedPackages.add(originalPkgSetting.name);
10008            }
10009        }
10010        // TODO(toddke): Consider a method specifically for modifying the Package object
10011        // post scan; or, moving this stuff out of the Package object since it has nothing
10012        // to do with the package on disk.
10013        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10014        // for creating the application ID. If we did this earlier, we would be saving the
10015        // correct ID.
10016        pkg.applicationInfo.uid = pkgSetting.appId;
10017
10018        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10019
10020        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10021            mTransferedPackages.add(pkg.packageName);
10022        }
10023
10024        // THROWS: when requested libraries that can't be found. it only changes
10025        // the state of the passed in pkg object, so, move to the top of the method
10026        // and allow it to abort
10027        if ((scanFlags & SCAN_BOOTING) == 0
10028                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10029            // Check all shared libraries and map to their actual file path.
10030            // We only do this here for apps not on a system dir, because those
10031            // are the only ones that can fail an install due to this.  We
10032            // will take care of the system apps by updating all of their
10033            // library paths after the scan is done. Also during the initial
10034            // scan don't update any libs as we do this wholesale after all
10035            // apps are scanned to avoid dependency based scanning.
10036            updateSharedLibrariesLPr(pkg, null);
10037        }
10038
10039        // All versions of a static shared library are referenced with the same
10040        // package name. Internally, we use a synthetic package name to allow
10041        // multiple versions of the same shared library to be installed. So,
10042        // we need to generate the synthetic package name of the latest shared
10043        // library in order to compare signatures.
10044        PackageSetting signatureCheckPs = pkgSetting;
10045        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10046            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10047            if (libraryEntry != null) {
10048                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10049            }
10050        }
10051
10052        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10053        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10054            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10055                // We just determined the app is signed correctly, so bring
10056                // over the latest parsed certs.
10057                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10058            } else {
10059                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10060                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10061                            "Package " + pkg.packageName + " upgrade keys do not match the "
10062                                    + "previously installed version");
10063                } else {
10064                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10065                    String msg = "System package " + pkg.packageName
10066                            + " signature changed; retaining data.";
10067                    reportSettingsProblem(Log.WARN, msg);
10068                }
10069            }
10070        } else {
10071            try {
10072                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10073                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10074                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10075                        pkg.mSigningDetails, compareCompat, compareRecover);
10076                // The new KeySets will be re-added later in the scanning process.
10077                if (compatMatch) {
10078                    synchronized (mPackages) {
10079                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10080                    }
10081                }
10082                // We just determined the app is signed correctly, so bring
10083                // over the latest parsed certs.
10084                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10085
10086
10087                // if this is is a sharedUser, check to see if the new package is signed by a newer
10088                // signing certificate than the existing one, and if so, copy over the new details
10089                if (signatureCheckPs.sharedUser != null
10090                        && pkg.mSigningDetails.hasAncestor(
10091                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10092                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10093                }
10094            } catch (PackageManagerException e) {
10095                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10096                    throw e;
10097                }
10098                // The signature has changed, but this package is in the system
10099                // image...  let's recover!
10100                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10101                // However...  if this package is part of a shared user, but it
10102                // doesn't match the signature of the shared user, let's fail.
10103                // What this means is that you can't change the signatures
10104                // associated with an overall shared user, which doesn't seem all
10105                // that unreasonable.
10106                if (signatureCheckPs.sharedUser != null) {
10107                    if (compareSignatures(
10108                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10109                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10110                        throw new PackageManagerException(
10111                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10112                                "Signature mismatch for shared user: "
10113                                        + pkgSetting.sharedUser);
10114                    }
10115                }
10116                // File a report about this.
10117                String msg = "System package " + pkg.packageName
10118                        + " signature changed; retaining data.";
10119                reportSettingsProblem(Log.WARN, msg);
10120            } catch (IllegalArgumentException e) {
10121
10122                // should never happen: certs matched when checking, but not when comparing
10123                // old to new for sharedUser
10124                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10125                        "Signing certificates comparison made on incomparable signing details"
10126                        + " but somehow passed verifySignatures!");
10127            }
10128        }
10129
10130        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10131            // This package wants to adopt ownership of permissions from
10132            // another package.
10133            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10134                final String origName = pkg.mAdoptPermissions.get(i);
10135                final PackageSetting orig = mSettings.getPackageLPr(origName);
10136                if (orig != null) {
10137                    if (verifyPackageUpdateLPr(orig, pkg)) {
10138                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10139                                + pkg.packageName);
10140                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10141                    }
10142                }
10143            }
10144        }
10145
10146        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10147            for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
10148                final String codePathString = changedAbiCodePath.get(i);
10149                try {
10150                    mInstaller.rmdex(codePathString,
10151                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10152                } catch (InstallerException ignored) {
10153                }
10154            }
10155        }
10156
10157        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10158            if (oldPkgSetting != null) {
10159                synchronized (mPackages) {
10160                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10161                }
10162            }
10163        } else {
10164            final int userId = user == null ? 0 : user.getIdentifier();
10165            // Modify state for the given package setting
10166            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10167                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10168            if (pkgSetting.getInstantApp(userId)) {
10169                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10170            }
10171        }
10172    }
10173
10174    /**
10175     * Returns the "real" name of the package.
10176     * <p>This may differ from the package's actual name if the application has already
10177     * been installed under one of this package's original names.
10178     */
10179    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10180            @Nullable String renamedPkgName) {
10181        if (isPackageRenamed(pkg, renamedPkgName)) {
10182            return pkg.mRealPackage;
10183        }
10184        return null;
10185    }
10186
10187    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10188    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10189            @Nullable String renamedPkgName) {
10190        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10191    }
10192
10193    /**
10194     * Returns the original package setting.
10195     * <p>A package can migrate its name during an update. In this scenario, a package
10196     * designates a set of names that it considers as one of its original names.
10197     * <p>An original package must be signed identically and it must have the same
10198     * shared user [if any].
10199     */
10200    @GuardedBy("mPackages")
10201    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10202            @Nullable String renamedPkgName) {
10203        if (!isPackageRenamed(pkg, renamedPkgName)) {
10204            return null;
10205        }
10206        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10207            final PackageSetting originalPs =
10208                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10209            if (originalPs != null) {
10210                // the package is already installed under its original name...
10211                // but, should we use it?
10212                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10213                    // the new package is incompatible with the original
10214                    continue;
10215                } else if (originalPs.sharedUser != null) {
10216                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10217                        // the shared user id is incompatible with the original
10218                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10219                                + " to " + pkg.packageName + ": old uid "
10220                                + originalPs.sharedUser.name
10221                                + " differs from " + pkg.mSharedUserId);
10222                        continue;
10223                    }
10224                    // TODO: Add case when shared user id is added [b/28144775]
10225                } else {
10226                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10227                            + pkg.packageName + " to old name " + originalPs.name);
10228                }
10229                return originalPs;
10230            }
10231        }
10232        return null;
10233    }
10234
10235    /**
10236     * Renames the package if it was installed under a different name.
10237     * <p>When we've already installed the package under an original name, update
10238     * the new package so we can continue to have the old name.
10239     */
10240    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10241            @NonNull String renamedPackageName) {
10242        if (pkg.mOriginalPackages == null
10243                || !pkg.mOriginalPackages.contains(renamedPackageName)
10244                || pkg.packageName.equals(renamedPackageName)) {
10245            return;
10246        }
10247        pkg.setPackageName(renamedPackageName);
10248    }
10249
10250    /**
10251     * Just scans the package without any side effects.
10252     * <p>Not entirely true at the moment. There is still one side effect -- this
10253     * method potentially modifies a live {@link PackageSetting} object representing
10254     * the package being scanned. This will be resolved in the future.
10255     *
10256     * @param request Information about the package to be scanned
10257     * @param isUnderFactoryTest Whether or not the device is under factory test
10258     * @param currentTime The current time, in millis
10259     * @return The results of the scan
10260     */
10261    @GuardedBy("mInstallLock")
10262    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10263            boolean isUnderFactoryTest, long currentTime)
10264                    throws PackageManagerException {
10265        final PackageParser.Package pkg = request.pkg;
10266        PackageSetting pkgSetting = request.pkgSetting;
10267        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10268        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10269        final @ParseFlags int parseFlags = request.parseFlags;
10270        final @ScanFlags int scanFlags = request.scanFlags;
10271        final String realPkgName = request.realPkgName;
10272        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10273        final UserHandle user = request.user;
10274        final boolean isPlatformPackage = request.isPlatformPackage;
10275
10276        List<String> changedAbiCodePath = null;
10277
10278        if (DEBUG_PACKAGE_SCANNING) {
10279            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10280                Log.d(TAG, "Scanning package " + pkg.packageName);
10281        }
10282
10283        if (Build.IS_DEBUGGABLE &&
10284                pkg.isPrivileged() &&
10285                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10286            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10287        }
10288
10289        // Initialize package source and resource directories
10290        final File scanFile = new File(pkg.codePath);
10291        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10292        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10293
10294        // We keep references to the derived CPU Abis from settings in oder to reuse
10295        // them in the case where we're not upgrading or booting for the first time.
10296        String primaryCpuAbiFromSettings = null;
10297        String secondaryCpuAbiFromSettings = null;
10298        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10299
10300        if (!needToDeriveAbi) {
10301            if (pkgSetting != null) {
10302                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10303                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10304            } else {
10305                // Re-scanning a system package after uninstalling updates; need to derive ABI
10306                needToDeriveAbi = true;
10307            }
10308        }
10309
10310        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10311            PackageManagerService.reportSettingsProblem(Log.WARN,
10312                    "Package " + pkg.packageName + " shared user changed from "
10313                            + (pkgSetting.sharedUser != null
10314                            ? pkgSetting.sharedUser.name : "<nothing>")
10315                            + " to "
10316                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10317                            + "; replacing with new");
10318            pkgSetting = null;
10319        }
10320
10321        String[] usesStaticLibraries = null;
10322        if (pkg.usesStaticLibraries != null) {
10323            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10324            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10325        }
10326        final boolean createNewPackage = (pkgSetting == null);
10327        if (createNewPackage) {
10328            final String parentPackageName = (pkg.parentPackage != null)
10329                    ? pkg.parentPackage.packageName : null;
10330            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10331            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10332            // REMOVE SharedUserSetting from method; update in a separate call
10333            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10334                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10335                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10336                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10337                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10338                    user, true /*allowInstall*/, instantApp, virtualPreload,
10339                    parentPackageName, pkg.getChildPackageNames(),
10340                    UserManagerService.getInstance(), usesStaticLibraries,
10341                    pkg.usesStaticLibrariesVersions);
10342        } else {
10343            // REMOVE SharedUserSetting from method; update in a separate call.
10344            //
10345            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10346            // secondaryCpuAbi are not known at this point so we always update them
10347            // to null here, only to reset them at a later point.
10348            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10349                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10350                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10351                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10352                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10353                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10354        }
10355        if (createNewPackage && originalPkgSetting != null) {
10356            // This is the initial transition from the original package, so,
10357            // fix up the new package's name now. We must do this after looking
10358            // up the package under its new name, so getPackageLP takes care of
10359            // fiddling things correctly.
10360            pkg.setPackageName(originalPkgSetting.name);
10361
10362            // File a report about this.
10363            String msg = "New package " + pkgSetting.realName
10364                    + " renamed to replace old package " + pkgSetting.name;
10365            reportSettingsProblem(Log.WARN, msg);
10366        }
10367
10368        if (disabledPkgSetting != null) {
10369            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10370        }
10371
10372        // SELinux sandboxes become more restrictive as targetSdkVersion increases.
10373        // To ensure that apps with sharedUserId are placed in the same selinux domain
10374        // without breaking any assumptions about access, put them into the least
10375        // restrictive targetSdkVersion=25 domain.
10376        // TODO(b/72290969): Base this on the actual targetSdkVersion(s) of the apps within the
10377        // sharedUserSetting, instead of defaulting to the least restrictive domain.
10378        final int targetSdk = (sharedUserSetting != null) ? 25
10379                : pkg.applicationInfo.targetSdkVersion;
10380        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10381        // They currently can be if the sharedUser apps are signed with the platform key.
10382        final boolean isPrivileged = (sharedUserSetting != null) ?
10383            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10384
10385        SELinuxMMAC.assignSeInfoValue(pkg, isPrivileged, targetSdk);
10386
10387        pkg.mExtras = pkgSetting;
10388        pkg.applicationInfo.processName = fixProcessName(
10389                pkg.applicationInfo.packageName,
10390                pkg.applicationInfo.processName);
10391
10392        if (!isPlatformPackage) {
10393            // Get all of our default paths setup
10394            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10395        }
10396
10397        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10398
10399        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10400            if (needToDeriveAbi) {
10401                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10402                final boolean extractNativeLibs = !pkg.isLibrary();
10403                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10404                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10405
10406                // Some system apps still use directory structure for native libraries
10407                // in which case we might end up not detecting abi solely based on apk
10408                // structure. Try to detect abi based on directory structure.
10409                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10410                        pkg.applicationInfo.primaryCpuAbi == null) {
10411                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10412                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10413                }
10414            } else {
10415                // This is not a first boot or an upgrade, don't bother deriving the
10416                // ABI during the scan. Instead, trust the value that was stored in the
10417                // package setting.
10418                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10419                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10420
10421                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10422
10423                if (DEBUG_ABI_SELECTION) {
10424                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10425                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10426                            pkg.applicationInfo.secondaryCpuAbi);
10427                }
10428            }
10429        } else {
10430            if ((scanFlags & SCAN_MOVE) != 0) {
10431                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10432                // but we already have this packages package info in the PackageSetting. We just
10433                // use that and derive the native library path based on the new codepath.
10434                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10435                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10436            }
10437
10438            // Set native library paths again. For moves, the path will be updated based on the
10439            // ABIs we've determined above. For non-moves, the path will be updated based on the
10440            // ABIs we determined during compilation, but the path will depend on the final
10441            // package path (after the rename away from the stage path).
10442            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10443        }
10444
10445        // This is a special case for the "system" package, where the ABI is
10446        // dictated by the zygote configuration (and init.rc). We should keep track
10447        // of this ABI so that we can deal with "normal" applications that run under
10448        // the same UID correctly.
10449        if (isPlatformPackage) {
10450            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10451                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10452        }
10453
10454        // If there's a mismatch between the abi-override in the package setting
10455        // and the abiOverride specified for the install. Warn about this because we
10456        // would've already compiled the app without taking the package setting into
10457        // account.
10458        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10459            if (cpuAbiOverride == null && pkg.packageName != null) {
10460                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10461                        " for package " + pkg.packageName);
10462            }
10463        }
10464
10465        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10466        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10467        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10468
10469        // Copy the derived override back to the parsed package, so that we can
10470        // update the package settings accordingly.
10471        pkg.cpuAbiOverride = cpuAbiOverride;
10472
10473        if (DEBUG_ABI_SELECTION) {
10474            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10475                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10476                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10477        }
10478
10479        // Push the derived path down into PackageSettings so we know what to
10480        // clean up at uninstall time.
10481        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10482
10483        if (DEBUG_ABI_SELECTION) {
10484            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10485                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10486                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10487        }
10488
10489        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10490            // We don't do this here during boot because we can do it all
10491            // at once after scanning all existing packages.
10492            //
10493            // We also do this *before* we perform dexopt on this package, so that
10494            // we can avoid redundant dexopts, and also to make sure we've got the
10495            // code and package path correct.
10496            changedAbiCodePath =
10497                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10498        }
10499
10500        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10501                android.Manifest.permission.FACTORY_TEST)) {
10502            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10503        }
10504
10505        if (isSystemApp(pkg)) {
10506            pkgSetting.isOrphaned = true;
10507        }
10508
10509        // Take care of first install / last update times.
10510        final long scanFileTime = getLastModifiedTime(pkg);
10511        if (currentTime != 0) {
10512            if (pkgSetting.firstInstallTime == 0) {
10513                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10514            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10515                pkgSetting.lastUpdateTime = currentTime;
10516            }
10517        } else if (pkgSetting.firstInstallTime == 0) {
10518            // We need *something*.  Take time time stamp of the file.
10519            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10520        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10521            if (scanFileTime != pkgSetting.timeStamp) {
10522                // A package on the system image has changed; consider this
10523                // to be an update.
10524                pkgSetting.lastUpdateTime = scanFileTime;
10525            }
10526        }
10527        pkgSetting.setTimeStamp(scanFileTime);
10528
10529        pkgSetting.pkg = pkg;
10530        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10531        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10532            pkgSetting.versionCode = pkg.getLongVersionCode();
10533        }
10534        // Update volume if needed
10535        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10536        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10537            Slog.i(PackageManagerService.TAG,
10538                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10539                    + " package " + pkg.packageName
10540                    + " volume from " + pkgSetting.volumeUuid
10541                    + " to " + volumeUuid);
10542            pkgSetting.volumeUuid = volumeUuid;
10543        }
10544
10545        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10546    }
10547
10548    /**
10549     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10550     */
10551    private static boolean apkHasCode(String fileName) {
10552        StrictJarFile jarFile = null;
10553        try {
10554            jarFile = new StrictJarFile(fileName,
10555                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10556            return jarFile.findEntry("classes.dex") != null;
10557        } catch (IOException ignore) {
10558        } finally {
10559            try {
10560                if (jarFile != null) {
10561                    jarFile.close();
10562                }
10563            } catch (IOException ignore) {}
10564        }
10565        return false;
10566    }
10567
10568    /**
10569     * Enforces code policy for the package. This ensures that if an APK has
10570     * declared hasCode="true" in its manifest that the APK actually contains
10571     * code.
10572     *
10573     * @throws PackageManagerException If bytecode could not be found when it should exist
10574     */
10575    private static void assertCodePolicy(PackageParser.Package pkg)
10576            throws PackageManagerException {
10577        final boolean shouldHaveCode =
10578                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10579        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10580            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10581                    "Package " + pkg.baseCodePath + " code is missing");
10582        }
10583
10584        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10585            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10586                final boolean splitShouldHaveCode =
10587                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10588                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10589                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10590                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10591                }
10592            }
10593        }
10594    }
10595
10596    /**
10597     * Applies policy to the parsed package based upon the given policy flags.
10598     * Ensures the package is in a good state.
10599     * <p>
10600     * Implementation detail: This method must NOT have any side effect. It would
10601     * ideally be static, but, it requires locks to read system state.
10602     */
10603    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10604            final @ScanFlags int scanFlags) {
10605        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10606            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10607            if (pkg.applicationInfo.isDirectBootAware()) {
10608                // we're direct boot aware; set for all components
10609                for (PackageParser.Service s : pkg.services) {
10610                    s.info.encryptionAware = s.info.directBootAware = true;
10611                }
10612                for (PackageParser.Provider p : pkg.providers) {
10613                    p.info.encryptionAware = p.info.directBootAware = true;
10614                }
10615                for (PackageParser.Activity a : pkg.activities) {
10616                    a.info.encryptionAware = a.info.directBootAware = true;
10617                }
10618                for (PackageParser.Activity r : pkg.receivers) {
10619                    r.info.encryptionAware = r.info.directBootAware = true;
10620                }
10621            }
10622            if (compressedFileExists(pkg.codePath)) {
10623                pkg.isStub = true;
10624            }
10625        } else {
10626            // non system apps can't be flagged as core
10627            pkg.coreApp = false;
10628            // clear flags not applicable to regular apps
10629            pkg.applicationInfo.flags &=
10630                    ~ApplicationInfo.FLAG_PERSISTENT;
10631            pkg.applicationInfo.privateFlags &=
10632                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10633            pkg.applicationInfo.privateFlags &=
10634                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10635            // cap permission priorities
10636            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10637                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10638                    pkg.permissionGroups.get(i).info.priority = 0;
10639                }
10640            }
10641        }
10642        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10643            // clear protected broadcasts
10644            pkg.protectedBroadcasts = null;
10645            // ignore export request for single user receivers
10646            if (pkg.receivers != null) {
10647                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10648                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10649                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10650                        receiver.info.exported = false;
10651                    }
10652                }
10653            }
10654            // ignore export request for single user services
10655            if (pkg.services != null) {
10656                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10657                    final PackageParser.Service service = pkg.services.get(i);
10658                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10659                        service.info.exported = false;
10660                    }
10661                }
10662            }
10663            // ignore export request for single user providers
10664            if (pkg.providers != null) {
10665                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10666                    final PackageParser.Provider provider = pkg.providers.get(i);
10667                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10668                        provider.info.exported = false;
10669                    }
10670                }
10671            }
10672        }
10673
10674        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10675            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10676        }
10677
10678        if ((scanFlags & SCAN_AS_OEM) != 0) {
10679            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10680        }
10681
10682        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10683            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10684        }
10685
10686        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10687            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10688        }
10689
10690        if (!isSystemApp(pkg)) {
10691            // Only system apps can use these features.
10692            pkg.mOriginalPackages = null;
10693            pkg.mRealPackage = null;
10694            pkg.mAdoptPermissions = null;
10695        }
10696    }
10697
10698    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10699            throws PackageManagerException {
10700        if (object == null) {
10701            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10702        }
10703        return object;
10704    }
10705
10706    /**
10707     * Asserts the parsed package is valid according to the given policy. If the
10708     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10709     * <p>
10710     * Implementation detail: This method must NOT have any side effects. It would
10711     * ideally be static, but, it requires locks to read system state.
10712     *
10713     * @throws PackageManagerException If the package fails any of the validation checks
10714     */
10715    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10716            final @ScanFlags int scanFlags)
10717                    throws PackageManagerException {
10718        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10719            assertCodePolicy(pkg);
10720        }
10721
10722        if (pkg.applicationInfo.getCodePath() == null ||
10723                pkg.applicationInfo.getResourcePath() == null) {
10724            // Bail out. The resource and code paths haven't been set.
10725            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10726                    "Code and resource paths haven't been set correctly");
10727        }
10728
10729        // Make sure we're not adding any bogus keyset info
10730        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10731        ksms.assertScannedPackageValid(pkg);
10732
10733        synchronized (mPackages) {
10734            // The special "android" package can only be defined once
10735            if (pkg.packageName.equals("android")) {
10736                if (mAndroidApplication != null) {
10737                    Slog.w(TAG, "*************************************************");
10738                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10739                    Slog.w(TAG, " codePath=" + pkg.codePath);
10740                    Slog.w(TAG, "*************************************************");
10741                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10742                            "Core android package being redefined.  Skipping.");
10743                }
10744            }
10745
10746            // A package name must be unique; don't allow duplicates
10747            if (mPackages.containsKey(pkg.packageName)) {
10748                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10749                        "Application package " + pkg.packageName
10750                        + " already installed.  Skipping duplicate.");
10751            }
10752
10753            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10754                // Static libs have a synthetic package name containing the version
10755                // but we still want the base name to be unique.
10756                if (mPackages.containsKey(pkg.manifestPackageName)) {
10757                    throw new PackageManagerException(
10758                            "Duplicate static shared lib provider package");
10759                }
10760
10761                // Static shared libraries should have at least O target SDK
10762                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10763                    throw new PackageManagerException(
10764                            "Packages declaring static-shared libs must target O SDK or higher");
10765                }
10766
10767                // Package declaring static a shared lib cannot be instant apps
10768                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10769                    throw new PackageManagerException(
10770                            "Packages declaring static-shared libs cannot be instant apps");
10771                }
10772
10773                // Package declaring static a shared lib cannot be renamed since the package
10774                // name is synthetic and apps can't code around package manager internals.
10775                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10776                    throw new PackageManagerException(
10777                            "Packages declaring static-shared libs cannot be renamed");
10778                }
10779
10780                // Package declaring static a shared lib cannot declare child packages
10781                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10782                    throw new PackageManagerException(
10783                            "Packages declaring static-shared libs cannot have child packages");
10784                }
10785
10786                // Package declaring static a shared lib cannot declare dynamic libs
10787                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10788                    throw new PackageManagerException(
10789                            "Packages declaring static-shared libs cannot declare dynamic libs");
10790                }
10791
10792                // Package declaring static a shared lib cannot declare shared users
10793                if (pkg.mSharedUserId != null) {
10794                    throw new PackageManagerException(
10795                            "Packages declaring static-shared libs cannot declare shared users");
10796                }
10797
10798                // Static shared libs cannot declare activities
10799                if (!pkg.activities.isEmpty()) {
10800                    throw new PackageManagerException(
10801                            "Static shared libs cannot declare activities");
10802                }
10803
10804                // Static shared libs cannot declare services
10805                if (!pkg.services.isEmpty()) {
10806                    throw new PackageManagerException(
10807                            "Static shared libs cannot declare services");
10808                }
10809
10810                // Static shared libs cannot declare providers
10811                if (!pkg.providers.isEmpty()) {
10812                    throw new PackageManagerException(
10813                            "Static shared libs cannot declare content providers");
10814                }
10815
10816                // Static shared libs cannot declare receivers
10817                if (!pkg.receivers.isEmpty()) {
10818                    throw new PackageManagerException(
10819                            "Static shared libs cannot declare broadcast receivers");
10820                }
10821
10822                // Static shared libs cannot declare permission groups
10823                if (!pkg.permissionGroups.isEmpty()) {
10824                    throw new PackageManagerException(
10825                            "Static shared libs cannot declare permission groups");
10826                }
10827
10828                // Static shared libs cannot declare permissions
10829                if (!pkg.permissions.isEmpty()) {
10830                    throw new PackageManagerException(
10831                            "Static shared libs cannot declare permissions");
10832                }
10833
10834                // Static shared libs cannot declare protected broadcasts
10835                if (pkg.protectedBroadcasts != null) {
10836                    throw new PackageManagerException(
10837                            "Static shared libs cannot declare protected broadcasts");
10838                }
10839
10840                // Static shared libs cannot be overlay targets
10841                if (pkg.mOverlayTarget != null) {
10842                    throw new PackageManagerException(
10843                            "Static shared libs cannot be overlay targets");
10844                }
10845
10846                // The version codes must be ordered as lib versions
10847                long minVersionCode = Long.MIN_VALUE;
10848                long maxVersionCode = Long.MAX_VALUE;
10849
10850                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10851                        pkg.staticSharedLibName);
10852                if (versionedLib != null) {
10853                    final int versionCount = versionedLib.size();
10854                    for (int i = 0; i < versionCount; i++) {
10855                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10856                        final long libVersionCode = libInfo.getDeclaringPackage()
10857                                .getLongVersionCode();
10858                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10859                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10860                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10861                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10862                        } else {
10863                            minVersionCode = maxVersionCode = libVersionCode;
10864                            break;
10865                        }
10866                    }
10867                }
10868                if (pkg.getLongVersionCode() < minVersionCode
10869                        || pkg.getLongVersionCode() > maxVersionCode) {
10870                    throw new PackageManagerException("Static shared"
10871                            + " lib version codes must be ordered as lib versions");
10872                }
10873            }
10874
10875            // Only privileged apps and updated privileged apps can add child packages.
10876            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10877                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10878                    throw new PackageManagerException("Only privileged apps can add child "
10879                            + "packages. Ignoring package " + pkg.packageName);
10880                }
10881                final int childCount = pkg.childPackages.size();
10882                for (int i = 0; i < childCount; i++) {
10883                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10884                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10885                            childPkg.packageName)) {
10886                        throw new PackageManagerException("Can't override child of "
10887                                + "another disabled app. Ignoring package " + pkg.packageName);
10888                    }
10889                }
10890            }
10891
10892            // If we're only installing presumed-existing packages, require that the
10893            // scanned APK is both already known and at the path previously established
10894            // for it.  Previously unknown packages we pick up normally, but if we have an
10895            // a priori expectation about this package's install presence, enforce it.
10896            // With a singular exception for new system packages. When an OTA contains
10897            // a new system package, we allow the codepath to change from a system location
10898            // to the user-installed location. If we don't allow this change, any newer,
10899            // user-installed version of the application will be ignored.
10900            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10901                if (mExpectingBetter.containsKey(pkg.packageName)) {
10902                    logCriticalInfo(Log.WARN,
10903                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10904                } else {
10905                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10906                    if (known != null) {
10907                        if (DEBUG_PACKAGE_SCANNING) {
10908                            Log.d(TAG, "Examining " + pkg.codePath
10909                                    + " and requiring known paths " + known.codePathString
10910                                    + " & " + known.resourcePathString);
10911                        }
10912                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10913                                || !pkg.applicationInfo.getResourcePath().equals(
10914                                        known.resourcePathString)) {
10915                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10916                                    "Application package " + pkg.packageName
10917                                    + " found at " + pkg.applicationInfo.getCodePath()
10918                                    + " but expected at " + known.codePathString
10919                                    + "; ignoring.");
10920                        }
10921                    } else {
10922                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10923                                "Application package " + pkg.packageName
10924                                + " not found; ignoring.");
10925                    }
10926                }
10927            }
10928
10929            // Verify that this new package doesn't have any content providers
10930            // that conflict with existing packages.  Only do this if the
10931            // package isn't already installed, since we don't want to break
10932            // things that are installed.
10933            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10934                final int N = pkg.providers.size();
10935                int i;
10936                for (i=0; i<N; i++) {
10937                    PackageParser.Provider p = pkg.providers.get(i);
10938                    if (p.info.authority != null) {
10939                        String names[] = p.info.authority.split(";");
10940                        for (int j = 0; j < names.length; j++) {
10941                            if (mProvidersByAuthority.containsKey(names[j])) {
10942                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10943                                final String otherPackageName =
10944                                        ((other != null && other.getComponentName() != null) ?
10945                                                other.getComponentName().getPackageName() : "?");
10946                                throw new PackageManagerException(
10947                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10948                                        "Can't install because provider name " + names[j]
10949                                                + " (in package " + pkg.applicationInfo.packageName
10950                                                + ") is already used by " + otherPackageName);
10951                            }
10952                        }
10953                    }
10954                }
10955            }
10956
10957            // Verify that packages sharing a user with a privileged app are marked as privileged.
10958            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
10959                SharedUserSetting sharedUserSetting = null;
10960                try {
10961                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
10962                } catch (PackageManagerException ignore) {}
10963                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
10964                    // Exempt SharedUsers signed with the platform key.
10965                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
10966                    if ((platformPkgSetting.signatures.mSigningDetails
10967                            != PackageParser.SigningDetails.UNKNOWN)
10968                            && (compareSignatures(
10969                                    platformPkgSetting.signatures.mSigningDetails.signatures,
10970                                    pkg.mSigningDetails.signatures)
10971                                            != PackageManager.SIGNATURE_MATCH)) {
10972                        throw new PackageManagerException("Apps that share a user with a " +
10973                                "privileged app must themselves be marked as privileged. " +
10974                                pkg.packageName + " shares privileged user " +
10975                                pkg.mSharedUserId + ".");
10976                    }
10977                }
10978            }
10979
10980            // Apply policies specific for runtime resource overlays (RROs).
10981            if (pkg.mOverlayTarget != null) {
10982                // System overlays have some restrictions on their use of the 'static' state.
10983                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10984                    // We are scanning a system overlay. This can be the first scan of the
10985                    // system/vendor/oem partition, or an update to the system overlay.
10986                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10987                        // This must be an update to a system overlay.
10988                        final PackageSetting previousPkg = assertNotNull(
10989                                mSettings.getPackageLPr(pkg.packageName),
10990                                "previous package state not present");
10991
10992                        // Static overlays cannot be updated.
10993                        if (previousPkg.pkg.mOverlayIsStatic) {
10994                            throw new PackageManagerException("Overlay " + pkg.packageName +
10995                                    " is static and cannot be upgraded.");
10996                        // Non-static overlays cannot be converted to static overlays.
10997                        } else if (pkg.mOverlayIsStatic) {
10998                            throw new PackageManagerException("Overlay " + pkg.packageName +
10999                                    " cannot be upgraded into a static overlay.");
11000                        }
11001                    }
11002                } else {
11003                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11004                    if (pkg.mOverlayIsStatic) {
11005                        throw new PackageManagerException("Overlay " + pkg.packageName +
11006                                " is static but not pre-installed.");
11007                    }
11008
11009                    // The only case where we allow installation of a non-system overlay is when
11010                    // its signature is signed with the platform certificate.
11011                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11012                    if ((platformPkgSetting.signatures.mSigningDetails
11013                            != PackageParser.SigningDetails.UNKNOWN)
11014                            && (compareSignatures(
11015                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11016                                    pkg.mSigningDetails.signatures)
11017                                            != PackageManager.SIGNATURE_MATCH)) {
11018                        throw new PackageManagerException("Overlay " + pkg.packageName +
11019                                " must be signed with the platform certificate.");
11020                    }
11021                }
11022            }
11023        }
11024    }
11025
11026    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11027            int type, String declaringPackageName, long declaringVersionCode) {
11028        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11029        if (versionedLib == null) {
11030            versionedLib = new LongSparseArray<>();
11031            mSharedLibraries.put(name, versionedLib);
11032            if (type == SharedLibraryInfo.TYPE_STATIC) {
11033                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11034            }
11035        } else if (versionedLib.indexOfKey(version) >= 0) {
11036            return false;
11037        }
11038        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11039                version, type, declaringPackageName, declaringVersionCode);
11040        versionedLib.put(version, libEntry);
11041        return true;
11042    }
11043
11044    private boolean removeSharedLibraryLPw(String name, long version) {
11045        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11046        if (versionedLib == null) {
11047            return false;
11048        }
11049        final int libIdx = versionedLib.indexOfKey(version);
11050        if (libIdx < 0) {
11051            return false;
11052        }
11053        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11054        versionedLib.remove(version);
11055        if (versionedLib.size() <= 0) {
11056            mSharedLibraries.remove(name);
11057            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11058                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11059                        .getPackageName());
11060            }
11061        }
11062        return true;
11063    }
11064
11065    /**
11066     * Adds a scanned package to the system. When this method is finished, the package will
11067     * be available for query, resolution, etc...
11068     */
11069    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11070            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
11071        final String pkgName = pkg.packageName;
11072        if (mCustomResolverComponentName != null &&
11073                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11074            setUpCustomResolverActivity(pkg);
11075        }
11076
11077        if (pkg.packageName.equals("android")) {
11078            synchronized (mPackages) {
11079                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11080                    // Set up information for our fall-back user intent resolution activity.
11081                    mPlatformPackage = pkg;
11082                    pkg.mVersionCode = mSdkVersion;
11083                    pkg.mVersionCodeMajor = 0;
11084                    mAndroidApplication = pkg.applicationInfo;
11085                    if (!mResolverReplaced) {
11086                        mResolveActivity.applicationInfo = mAndroidApplication;
11087                        mResolveActivity.name = ResolverActivity.class.getName();
11088                        mResolveActivity.packageName = mAndroidApplication.packageName;
11089                        mResolveActivity.processName = "system:ui";
11090                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11091                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11092                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11093                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11094                        mResolveActivity.exported = true;
11095                        mResolveActivity.enabled = true;
11096                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11097                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11098                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11099                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11100                                | ActivityInfo.CONFIG_ORIENTATION
11101                                | ActivityInfo.CONFIG_KEYBOARD
11102                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11103                        mResolveInfo.activityInfo = mResolveActivity;
11104                        mResolveInfo.priority = 0;
11105                        mResolveInfo.preferredOrder = 0;
11106                        mResolveInfo.match = 0;
11107                        mResolveComponentName = new ComponentName(
11108                                mAndroidApplication.packageName, mResolveActivity.name);
11109                    }
11110                }
11111            }
11112        }
11113
11114        ArrayList<PackageParser.Package> clientLibPkgs = null;
11115        // writer
11116        synchronized (mPackages) {
11117            boolean hasStaticSharedLibs = false;
11118
11119            // Any app can add new static shared libraries
11120            if (pkg.staticSharedLibName != null) {
11121                // Static shared libs don't allow renaming as they have synthetic package
11122                // names to allow install of multiple versions, so use name from manifest.
11123                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11124                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11125                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11126                    hasStaticSharedLibs = true;
11127                } else {
11128                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11129                                + pkg.staticSharedLibName + " already exists; skipping");
11130                }
11131                // Static shared libs cannot be updated once installed since they
11132                // use synthetic package name which includes the version code, so
11133                // not need to update other packages's shared lib dependencies.
11134            }
11135
11136            if (!hasStaticSharedLibs
11137                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11138                // Only system apps can add new dynamic shared libraries.
11139                if (pkg.libraryNames != null) {
11140                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11141                        String name = pkg.libraryNames.get(i);
11142                        boolean allowed = false;
11143                        if (pkg.isUpdatedSystemApp()) {
11144                            // New library entries can only be added through the
11145                            // system image.  This is important to get rid of a lot
11146                            // of nasty edge cases: for example if we allowed a non-
11147                            // system update of the app to add a library, then uninstalling
11148                            // the update would make the library go away, and assumptions
11149                            // we made such as through app install filtering would now
11150                            // have allowed apps on the device which aren't compatible
11151                            // with it.  Better to just have the restriction here, be
11152                            // conservative, and create many fewer cases that can negatively
11153                            // impact the user experience.
11154                            final PackageSetting sysPs = mSettings
11155                                    .getDisabledSystemPkgLPr(pkg.packageName);
11156                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11157                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11158                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11159                                        allowed = true;
11160                                        break;
11161                                    }
11162                                }
11163                            }
11164                        } else {
11165                            allowed = true;
11166                        }
11167                        if (allowed) {
11168                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11169                                    SharedLibraryInfo.VERSION_UNDEFINED,
11170                                    SharedLibraryInfo.TYPE_DYNAMIC,
11171                                    pkg.packageName, pkg.getLongVersionCode())) {
11172                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11173                                        + name + " already exists; skipping");
11174                            }
11175                        } else {
11176                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11177                                    + name + " that is not declared on system image; skipping");
11178                        }
11179                    }
11180
11181                    if ((scanFlags & SCAN_BOOTING) == 0) {
11182                        // If we are not booting, we need to update any applications
11183                        // that are clients of our shared library.  If we are booting,
11184                        // this will all be done once the scan is complete.
11185                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11186                    }
11187                }
11188            }
11189        }
11190
11191        if ((scanFlags & SCAN_BOOTING) != 0) {
11192            // No apps can run during boot scan, so they don't need to be frozen
11193        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11194            // Caller asked to not kill app, so it's probably not frozen
11195        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11196            // Caller asked us to ignore frozen check for some reason; they
11197            // probably didn't know the package name
11198        } else {
11199            // We're doing major surgery on this package, so it better be frozen
11200            // right now to keep it from launching
11201            checkPackageFrozen(pkgName);
11202        }
11203
11204        // Also need to kill any apps that are dependent on the library.
11205        if (clientLibPkgs != null) {
11206            for (int i=0; i<clientLibPkgs.size(); i++) {
11207                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11208                killApplication(clientPkg.applicationInfo.packageName,
11209                        clientPkg.applicationInfo.uid, "update lib");
11210            }
11211        }
11212
11213        // writer
11214        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11215
11216        synchronized (mPackages) {
11217            // We don't expect installation to fail beyond this point
11218
11219            // Add the new setting to mSettings
11220            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11221            // Add the new setting to mPackages
11222            mPackages.put(pkg.applicationInfo.packageName, pkg);
11223            // Make sure we don't accidentally delete its data.
11224            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11225            while (iter.hasNext()) {
11226                PackageCleanItem item = iter.next();
11227                if (pkgName.equals(item.packageName)) {
11228                    iter.remove();
11229                }
11230            }
11231
11232            // Add the package's KeySets to the global KeySetManagerService
11233            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11234            ksms.addScannedPackageLPw(pkg);
11235
11236            int N = pkg.providers.size();
11237            StringBuilder r = null;
11238            int i;
11239            for (i=0; i<N; i++) {
11240                PackageParser.Provider p = pkg.providers.get(i);
11241                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11242                        p.info.processName);
11243                mProviders.addProvider(p);
11244                p.syncable = p.info.isSyncable;
11245                if (p.info.authority != null) {
11246                    String names[] = p.info.authority.split(";");
11247                    p.info.authority = null;
11248                    for (int j = 0; j < names.length; j++) {
11249                        if (j == 1 && p.syncable) {
11250                            // We only want the first authority for a provider to possibly be
11251                            // syncable, so if we already added this provider using a different
11252                            // authority clear the syncable flag. We copy the provider before
11253                            // changing it because the mProviders object contains a reference
11254                            // to a provider that we don't want to change.
11255                            // Only do this for the second authority since the resulting provider
11256                            // object can be the same for all future authorities for this provider.
11257                            p = new PackageParser.Provider(p);
11258                            p.syncable = false;
11259                        }
11260                        if (!mProvidersByAuthority.containsKey(names[j])) {
11261                            mProvidersByAuthority.put(names[j], p);
11262                            if (p.info.authority == null) {
11263                                p.info.authority = names[j];
11264                            } else {
11265                                p.info.authority = p.info.authority + ";" + names[j];
11266                            }
11267                            if (DEBUG_PACKAGE_SCANNING) {
11268                                if (chatty)
11269                                    Log.d(TAG, "Registered content provider: " + names[j]
11270                                            + ", className = " + p.info.name + ", isSyncable = "
11271                                            + p.info.isSyncable);
11272                            }
11273                        } else {
11274                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11275                            Slog.w(TAG, "Skipping provider name " + names[j] +
11276                                    " (in package " + pkg.applicationInfo.packageName +
11277                                    "): name already used by "
11278                                    + ((other != null && other.getComponentName() != null)
11279                                            ? other.getComponentName().getPackageName() : "?"));
11280                        }
11281                    }
11282                }
11283                if (chatty) {
11284                    if (r == null) {
11285                        r = new StringBuilder(256);
11286                    } else {
11287                        r.append(' ');
11288                    }
11289                    r.append(p.info.name);
11290                }
11291            }
11292            if (r != null) {
11293                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11294            }
11295
11296            N = pkg.services.size();
11297            r = null;
11298            for (i=0; i<N; i++) {
11299                PackageParser.Service s = pkg.services.get(i);
11300                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11301                        s.info.processName);
11302                mServices.addService(s);
11303                if (chatty) {
11304                    if (r == null) {
11305                        r = new StringBuilder(256);
11306                    } else {
11307                        r.append(' ');
11308                    }
11309                    r.append(s.info.name);
11310                }
11311            }
11312            if (r != null) {
11313                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11314            }
11315
11316            N = pkg.receivers.size();
11317            r = null;
11318            for (i=0; i<N; i++) {
11319                PackageParser.Activity a = pkg.receivers.get(i);
11320                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11321                        a.info.processName);
11322                mReceivers.addActivity(a, "receiver");
11323                if (chatty) {
11324                    if (r == null) {
11325                        r = new StringBuilder(256);
11326                    } else {
11327                        r.append(' ');
11328                    }
11329                    r.append(a.info.name);
11330                }
11331            }
11332            if (r != null) {
11333                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11334            }
11335
11336            N = pkg.activities.size();
11337            r = null;
11338            for (i=0; i<N; i++) {
11339                PackageParser.Activity a = pkg.activities.get(i);
11340                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11341                        a.info.processName);
11342                mActivities.addActivity(a, "activity");
11343                if (chatty) {
11344                    if (r == null) {
11345                        r = new StringBuilder(256);
11346                    } else {
11347                        r.append(' ');
11348                    }
11349                    r.append(a.info.name);
11350                }
11351            }
11352            if (r != null) {
11353                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11354            }
11355
11356            // Don't allow ephemeral applications to define new permissions groups.
11357            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11358                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11359                        + " ignored: instant apps cannot define new permission groups.");
11360            } else {
11361                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11362            }
11363
11364            // Don't allow ephemeral applications to define new permissions.
11365            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11366                Slog.w(TAG, "Permissions from package " + pkg.packageName
11367                        + " ignored: instant apps cannot define new permissions.");
11368            } else {
11369                mPermissionManager.addAllPermissions(pkg, chatty);
11370            }
11371
11372            N = pkg.instrumentation.size();
11373            r = null;
11374            for (i=0; i<N; i++) {
11375                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11376                a.info.packageName = pkg.applicationInfo.packageName;
11377                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11378                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11379                a.info.splitNames = pkg.splitNames;
11380                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11381                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11382                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11383                a.info.dataDir = pkg.applicationInfo.dataDir;
11384                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11385                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11386                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11387                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11388                mInstrumentation.put(a.getComponentName(), a);
11389                if (chatty) {
11390                    if (r == null) {
11391                        r = new StringBuilder(256);
11392                    } else {
11393                        r.append(' ');
11394                    }
11395                    r.append(a.info.name);
11396                }
11397            }
11398            if (r != null) {
11399                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11400            }
11401
11402            if (pkg.protectedBroadcasts != null) {
11403                N = pkg.protectedBroadcasts.size();
11404                synchronized (mProtectedBroadcasts) {
11405                    for (i = 0; i < N; i++) {
11406                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11407                    }
11408                }
11409            }
11410        }
11411
11412        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11413    }
11414
11415    /**
11416     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11417     * is derived purely on the basis of the contents of {@code scanFile} and
11418     * {@code cpuAbiOverride}.
11419     *
11420     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11421     */
11422    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11423            boolean extractLibs)
11424                    throws PackageManagerException {
11425        // Give ourselves some initial paths; we'll come back for another
11426        // pass once we've determined ABI below.
11427        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11428
11429        // We would never need to extract libs for forward-locked and external packages,
11430        // since the container service will do it for us. We shouldn't attempt to
11431        // extract libs from system app when it was not updated.
11432        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11433                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11434            extractLibs = false;
11435        }
11436
11437        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11438        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11439
11440        NativeLibraryHelper.Handle handle = null;
11441        try {
11442            handle = NativeLibraryHelper.Handle.create(pkg);
11443            // TODO(multiArch): This can be null for apps that didn't go through the
11444            // usual installation process. We can calculate it again, like we
11445            // do during install time.
11446            //
11447            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11448            // unnecessary.
11449            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11450
11451            // Null out the abis so that they can be recalculated.
11452            pkg.applicationInfo.primaryCpuAbi = null;
11453            pkg.applicationInfo.secondaryCpuAbi = null;
11454            if (isMultiArch(pkg.applicationInfo)) {
11455                // Warn if we've set an abiOverride for multi-lib packages..
11456                // By definition, we need to copy both 32 and 64 bit libraries for
11457                // such packages.
11458                if (pkg.cpuAbiOverride != null
11459                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11460                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11461                }
11462
11463                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11464                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11465                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11466                    if (extractLibs) {
11467                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11468                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11469                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11470                                useIsaSpecificSubdirs);
11471                    } else {
11472                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11473                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11474                    }
11475                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11476                }
11477
11478                // Shared library native code should be in the APK zip aligned
11479                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11480                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11481                            "Shared library native lib extraction not supported");
11482                }
11483
11484                maybeThrowExceptionForMultiArchCopy(
11485                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11486
11487                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11488                    if (extractLibs) {
11489                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11490                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11491                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11492                                useIsaSpecificSubdirs);
11493                    } else {
11494                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11495                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11496                    }
11497                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11498                }
11499
11500                maybeThrowExceptionForMultiArchCopy(
11501                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11502
11503                if (abi64 >= 0) {
11504                    // Shared library native libs should be in the APK zip aligned
11505                    if (extractLibs && pkg.isLibrary()) {
11506                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11507                                "Shared library native lib extraction not supported");
11508                    }
11509                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11510                }
11511
11512                if (abi32 >= 0) {
11513                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11514                    if (abi64 >= 0) {
11515                        if (pkg.use32bitAbi) {
11516                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11517                            pkg.applicationInfo.primaryCpuAbi = abi;
11518                        } else {
11519                            pkg.applicationInfo.secondaryCpuAbi = abi;
11520                        }
11521                    } else {
11522                        pkg.applicationInfo.primaryCpuAbi = abi;
11523                    }
11524                }
11525            } else {
11526                String[] abiList = (cpuAbiOverride != null) ?
11527                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11528
11529                // Enable gross and lame hacks for apps that are built with old
11530                // SDK tools. We must scan their APKs for renderscript bitcode and
11531                // not launch them if it's present. Don't bother checking on devices
11532                // that don't have 64 bit support.
11533                boolean needsRenderScriptOverride = false;
11534                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11535                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11536                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11537                    needsRenderScriptOverride = true;
11538                }
11539
11540                final int copyRet;
11541                if (extractLibs) {
11542                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11543                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11544                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11545                } else {
11546                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11547                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11548                }
11549                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11550
11551                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11552                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11553                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11554                }
11555
11556                if (copyRet >= 0) {
11557                    // Shared libraries that have native libs must be multi-architecture
11558                    if (pkg.isLibrary()) {
11559                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11560                                "Shared library with native libs must be multiarch");
11561                    }
11562                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11563                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11564                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11565                } else if (needsRenderScriptOverride) {
11566                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11567                }
11568            }
11569        } catch (IOException ioe) {
11570            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11571        } finally {
11572            IoUtils.closeQuietly(handle);
11573        }
11574
11575        // Now that we've calculated the ABIs and determined if it's an internal app,
11576        // we will go ahead and populate the nativeLibraryPath.
11577        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11578    }
11579
11580    /**
11581     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11582     * i.e, so that all packages can be run inside a single process if required.
11583     *
11584     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11585     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11586     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11587     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11588     * updating a package that belongs to a shared user.
11589     *
11590     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11591     * adds unnecessary complexity.
11592     */
11593    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11594            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11595        List<String> changedAbiCodePath = null;
11596        String requiredInstructionSet = null;
11597        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11598            requiredInstructionSet = VMRuntime.getInstructionSet(
11599                     scannedPackage.applicationInfo.primaryCpuAbi);
11600        }
11601
11602        PackageSetting requirer = null;
11603        for (PackageSetting ps : packagesForUser) {
11604            // If packagesForUser contains scannedPackage, we skip it. This will happen
11605            // when scannedPackage is an update of an existing package. Without this check,
11606            // we will never be able to change the ABI of any package belonging to a shared
11607            // user, even if it's compatible with other packages.
11608            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11609                if (ps.primaryCpuAbiString == null) {
11610                    continue;
11611                }
11612
11613                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11614                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11615                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11616                    // this but there's not much we can do.
11617                    String errorMessage = "Instruction set mismatch, "
11618                            + ((requirer == null) ? "[caller]" : requirer)
11619                            + " requires " + requiredInstructionSet + " whereas " + ps
11620                            + " requires " + instructionSet;
11621                    Slog.w(TAG, errorMessage);
11622                }
11623
11624                if (requiredInstructionSet == null) {
11625                    requiredInstructionSet = instructionSet;
11626                    requirer = ps;
11627                }
11628            }
11629        }
11630
11631        if (requiredInstructionSet != null) {
11632            String adjustedAbi;
11633            if (requirer != null) {
11634                // requirer != null implies that either scannedPackage was null or that scannedPackage
11635                // did not require an ABI, in which case we have to adjust scannedPackage to match
11636                // the ABI of the set (which is the same as requirer's ABI)
11637                adjustedAbi = requirer.primaryCpuAbiString;
11638                if (scannedPackage != null) {
11639                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11640                }
11641            } else {
11642                // requirer == null implies that we're updating all ABIs in the set to
11643                // match scannedPackage.
11644                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11645            }
11646
11647            for (PackageSetting ps : packagesForUser) {
11648                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11649                    if (ps.primaryCpuAbiString != null) {
11650                        continue;
11651                    }
11652
11653                    ps.primaryCpuAbiString = adjustedAbi;
11654                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11655                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11656                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11657                        if (DEBUG_ABI_SELECTION) {
11658                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11659                                    + " (requirer="
11660                                    + (requirer != null ? requirer.pkg : "null")
11661                                    + ", scannedPackage="
11662                                    + (scannedPackage != null ? scannedPackage : "null")
11663                                    + ")");
11664                        }
11665                        if (changedAbiCodePath == null) {
11666                            changedAbiCodePath = new ArrayList<>();
11667                        }
11668                        changedAbiCodePath.add(ps.codePathString);
11669                    }
11670                }
11671            }
11672        }
11673        return changedAbiCodePath;
11674    }
11675
11676    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11677        synchronized (mPackages) {
11678            mResolverReplaced = true;
11679            // Set up information for custom user intent resolution activity.
11680            mResolveActivity.applicationInfo = pkg.applicationInfo;
11681            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11682            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11683            mResolveActivity.processName = pkg.applicationInfo.packageName;
11684            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11685            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11686                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11687            mResolveActivity.theme = 0;
11688            mResolveActivity.exported = true;
11689            mResolveActivity.enabled = true;
11690            mResolveInfo.activityInfo = mResolveActivity;
11691            mResolveInfo.priority = 0;
11692            mResolveInfo.preferredOrder = 0;
11693            mResolveInfo.match = 0;
11694            mResolveComponentName = mCustomResolverComponentName;
11695            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11696                    mResolveComponentName);
11697        }
11698    }
11699
11700    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11701        if (installerActivity == null) {
11702            if (DEBUG_INSTANT) {
11703                Slog.d(TAG, "Clear ephemeral installer activity");
11704            }
11705            mInstantAppInstallerActivity = null;
11706            return;
11707        }
11708
11709        if (DEBUG_INSTANT) {
11710            Slog.d(TAG, "Set ephemeral installer activity: "
11711                    + installerActivity.getComponentName());
11712        }
11713        // Set up information for ephemeral installer activity
11714        mInstantAppInstallerActivity = installerActivity;
11715        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11716                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11717        mInstantAppInstallerActivity.exported = true;
11718        mInstantAppInstallerActivity.enabled = true;
11719        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11720        mInstantAppInstallerInfo.priority = 1;
11721        mInstantAppInstallerInfo.preferredOrder = 1;
11722        mInstantAppInstallerInfo.isDefault = true;
11723        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11724                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11725    }
11726
11727    private static String calculateBundledApkRoot(final String codePathString) {
11728        final File codePath = new File(codePathString);
11729        final File codeRoot;
11730        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11731            codeRoot = Environment.getRootDirectory();
11732        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11733            codeRoot = Environment.getOemDirectory();
11734        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11735            codeRoot = Environment.getVendorDirectory();
11736        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11737            codeRoot = Environment.getProductDirectory();
11738        } else {
11739            // Unrecognized code path; take its top real segment as the apk root:
11740            // e.g. /something/app/blah.apk => /something
11741            try {
11742                File f = codePath.getCanonicalFile();
11743                File parent = f.getParentFile();    // non-null because codePath is a file
11744                File tmp;
11745                while ((tmp = parent.getParentFile()) != null) {
11746                    f = parent;
11747                    parent = tmp;
11748                }
11749                codeRoot = f;
11750                Slog.w(TAG, "Unrecognized code path "
11751                        + codePath + " - using " + codeRoot);
11752            } catch (IOException e) {
11753                // Can't canonicalize the code path -- shenanigans?
11754                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11755                return Environment.getRootDirectory().getPath();
11756            }
11757        }
11758        return codeRoot.getPath();
11759    }
11760
11761    /**
11762     * Derive and set the location of native libraries for the given package,
11763     * which varies depending on where and how the package was installed.
11764     */
11765    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11766        final ApplicationInfo info = pkg.applicationInfo;
11767        final String codePath = pkg.codePath;
11768        final File codeFile = new File(codePath);
11769        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11770        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11771
11772        info.nativeLibraryRootDir = null;
11773        info.nativeLibraryRootRequiresIsa = false;
11774        info.nativeLibraryDir = null;
11775        info.secondaryNativeLibraryDir = null;
11776
11777        if (isApkFile(codeFile)) {
11778            // Monolithic install
11779            if (bundledApp) {
11780                // If "/system/lib64/apkname" exists, assume that is the per-package
11781                // native library directory to use; otherwise use "/system/lib/apkname".
11782                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11783                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11784                        getPrimaryInstructionSet(info));
11785
11786                // This is a bundled system app so choose the path based on the ABI.
11787                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11788                // is just the default path.
11789                final String apkName = deriveCodePathName(codePath);
11790                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11791                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11792                        apkName).getAbsolutePath();
11793
11794                if (info.secondaryCpuAbi != null) {
11795                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11796                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11797                            secondaryLibDir, apkName).getAbsolutePath();
11798                }
11799            } else if (asecApp) {
11800                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11801                        .getAbsolutePath();
11802            } else {
11803                final String apkName = deriveCodePathName(codePath);
11804                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11805                        .getAbsolutePath();
11806            }
11807
11808            info.nativeLibraryRootRequiresIsa = false;
11809            info.nativeLibraryDir = info.nativeLibraryRootDir;
11810        } else {
11811            // Cluster install
11812            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11813            info.nativeLibraryRootRequiresIsa = true;
11814
11815            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11816                    getPrimaryInstructionSet(info)).getAbsolutePath();
11817
11818            if (info.secondaryCpuAbi != null) {
11819                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11820                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11821            }
11822        }
11823    }
11824
11825    /**
11826     * Calculate the abis and roots for a bundled app. These can uniquely
11827     * be determined from the contents of the system partition, i.e whether
11828     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11829     * of this information, and instead assume that the system was built
11830     * sensibly.
11831     */
11832    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11833                                           PackageSetting pkgSetting) {
11834        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11835
11836        // If "/system/lib64/apkname" exists, assume that is the per-package
11837        // native library directory to use; otherwise use "/system/lib/apkname".
11838        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11839        setBundledAppAbi(pkg, apkRoot, apkName);
11840        // pkgSetting might be null during rescan following uninstall of updates
11841        // to a bundled app, so accommodate that possibility.  The settings in
11842        // that case will be established later from the parsed package.
11843        //
11844        // If the settings aren't null, sync them up with what we've just derived.
11845        // note that apkRoot isn't stored in the package settings.
11846        if (pkgSetting != null) {
11847            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11848            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11849        }
11850    }
11851
11852    /**
11853     * Deduces the ABI of a bundled app and sets the relevant fields on the
11854     * parsed pkg object.
11855     *
11856     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11857     *        under which system libraries are installed.
11858     * @param apkName the name of the installed package.
11859     */
11860    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11861        final File codeFile = new File(pkg.codePath);
11862
11863        final boolean has64BitLibs;
11864        final boolean has32BitLibs;
11865        if (isApkFile(codeFile)) {
11866            // Monolithic install
11867            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11868            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11869        } else {
11870            // Cluster install
11871            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11872            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11873                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11874                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11875                has64BitLibs = (new File(rootDir, isa)).exists();
11876            } else {
11877                has64BitLibs = false;
11878            }
11879            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11880                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11881                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11882                has32BitLibs = (new File(rootDir, isa)).exists();
11883            } else {
11884                has32BitLibs = false;
11885            }
11886        }
11887
11888        if (has64BitLibs && !has32BitLibs) {
11889            // The package has 64 bit libs, but not 32 bit libs. Its primary
11890            // ABI should be 64 bit. We can safely assume here that the bundled
11891            // native libraries correspond to the most preferred ABI in the list.
11892
11893            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11894            pkg.applicationInfo.secondaryCpuAbi = null;
11895        } else if (has32BitLibs && !has64BitLibs) {
11896            // The package has 32 bit libs but not 64 bit libs. Its primary
11897            // ABI should be 32 bit.
11898
11899            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11900            pkg.applicationInfo.secondaryCpuAbi = null;
11901        } else if (has32BitLibs && has64BitLibs) {
11902            // The application has both 64 and 32 bit bundled libraries. We check
11903            // here that the app declares multiArch support, and warn if it doesn't.
11904            //
11905            // We will be lenient here and record both ABIs. The primary will be the
11906            // ABI that's higher on the list, i.e, a device that's configured to prefer
11907            // 64 bit apps will see a 64 bit primary ABI,
11908
11909            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11910                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11911            }
11912
11913            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11914                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11915                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11916            } else {
11917                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11918                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11919            }
11920        } else {
11921            pkg.applicationInfo.primaryCpuAbi = null;
11922            pkg.applicationInfo.secondaryCpuAbi = null;
11923        }
11924    }
11925
11926    private void killApplication(String pkgName, int appId, String reason) {
11927        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11928    }
11929
11930    private void killApplication(String pkgName, int appId, int userId, String reason) {
11931        // Request the ActivityManager to kill the process(only for existing packages)
11932        // so that we do not end up in a confused state while the user is still using the older
11933        // version of the application while the new one gets installed.
11934        final long token = Binder.clearCallingIdentity();
11935        try {
11936            IActivityManager am = ActivityManager.getService();
11937            if (am != null) {
11938                try {
11939                    am.killApplication(pkgName, appId, userId, reason);
11940                } catch (RemoteException e) {
11941                }
11942            }
11943        } finally {
11944            Binder.restoreCallingIdentity(token);
11945        }
11946    }
11947
11948    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11949        // Remove the parent package setting
11950        PackageSetting ps = (PackageSetting) pkg.mExtras;
11951        if (ps != null) {
11952            removePackageLI(ps, chatty);
11953        }
11954        // Remove the child package setting
11955        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11956        for (int i = 0; i < childCount; i++) {
11957            PackageParser.Package childPkg = pkg.childPackages.get(i);
11958            ps = (PackageSetting) childPkg.mExtras;
11959            if (ps != null) {
11960                removePackageLI(ps, chatty);
11961            }
11962        }
11963    }
11964
11965    void removePackageLI(PackageSetting ps, boolean chatty) {
11966        if (DEBUG_INSTALL) {
11967            if (chatty)
11968                Log.d(TAG, "Removing package " + ps.name);
11969        }
11970
11971        // writer
11972        synchronized (mPackages) {
11973            mPackages.remove(ps.name);
11974            final PackageParser.Package pkg = ps.pkg;
11975            if (pkg != null) {
11976                cleanPackageDataStructuresLILPw(pkg, chatty);
11977            }
11978        }
11979    }
11980
11981    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11982        if (DEBUG_INSTALL) {
11983            if (chatty)
11984                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11985        }
11986
11987        // writer
11988        synchronized (mPackages) {
11989            // Remove the parent package
11990            mPackages.remove(pkg.applicationInfo.packageName);
11991            cleanPackageDataStructuresLILPw(pkg, chatty);
11992
11993            // Remove the child packages
11994            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11995            for (int i = 0; i < childCount; i++) {
11996                PackageParser.Package childPkg = pkg.childPackages.get(i);
11997                mPackages.remove(childPkg.applicationInfo.packageName);
11998                cleanPackageDataStructuresLILPw(childPkg, chatty);
11999            }
12000        }
12001    }
12002
12003    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12004        int N = pkg.providers.size();
12005        StringBuilder r = null;
12006        int i;
12007        for (i=0; i<N; i++) {
12008            PackageParser.Provider p = pkg.providers.get(i);
12009            mProviders.removeProvider(p);
12010            if (p.info.authority == null) {
12011
12012                /* There was another ContentProvider with this authority when
12013                 * this app was installed so this authority is null,
12014                 * Ignore it as we don't have to unregister the provider.
12015                 */
12016                continue;
12017            }
12018            String names[] = p.info.authority.split(";");
12019            for (int j = 0; j < names.length; j++) {
12020                if (mProvidersByAuthority.get(names[j]) == p) {
12021                    mProvidersByAuthority.remove(names[j]);
12022                    if (DEBUG_REMOVE) {
12023                        if (chatty)
12024                            Log.d(TAG, "Unregistered content provider: " + names[j]
12025                                    + ", className = " + p.info.name + ", isSyncable = "
12026                                    + p.info.isSyncable);
12027                    }
12028                }
12029            }
12030            if (DEBUG_REMOVE && chatty) {
12031                if (r == null) {
12032                    r = new StringBuilder(256);
12033                } else {
12034                    r.append(' ');
12035                }
12036                r.append(p.info.name);
12037            }
12038        }
12039        if (r != null) {
12040            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12041        }
12042
12043        N = pkg.services.size();
12044        r = null;
12045        for (i=0; i<N; i++) {
12046            PackageParser.Service s = pkg.services.get(i);
12047            mServices.removeService(s);
12048            if (chatty) {
12049                if (r == null) {
12050                    r = new StringBuilder(256);
12051                } else {
12052                    r.append(' ');
12053                }
12054                r.append(s.info.name);
12055            }
12056        }
12057        if (r != null) {
12058            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12059        }
12060
12061        N = pkg.receivers.size();
12062        r = null;
12063        for (i=0; i<N; i++) {
12064            PackageParser.Activity a = pkg.receivers.get(i);
12065            mReceivers.removeActivity(a, "receiver");
12066            if (DEBUG_REMOVE && chatty) {
12067                if (r == null) {
12068                    r = new StringBuilder(256);
12069                } else {
12070                    r.append(' ');
12071                }
12072                r.append(a.info.name);
12073            }
12074        }
12075        if (r != null) {
12076            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12077        }
12078
12079        N = pkg.activities.size();
12080        r = null;
12081        for (i=0; i<N; i++) {
12082            PackageParser.Activity a = pkg.activities.get(i);
12083            mActivities.removeActivity(a, "activity");
12084            if (DEBUG_REMOVE && chatty) {
12085                if (r == null) {
12086                    r = new StringBuilder(256);
12087                } else {
12088                    r.append(' ');
12089                }
12090                r.append(a.info.name);
12091            }
12092        }
12093        if (r != null) {
12094            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12095        }
12096
12097        mPermissionManager.removeAllPermissions(pkg, chatty);
12098
12099        N = pkg.instrumentation.size();
12100        r = null;
12101        for (i=0; i<N; i++) {
12102            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12103            mInstrumentation.remove(a.getComponentName());
12104            if (DEBUG_REMOVE && chatty) {
12105                if (r == null) {
12106                    r = new StringBuilder(256);
12107                } else {
12108                    r.append(' ');
12109                }
12110                r.append(a.info.name);
12111            }
12112        }
12113        if (r != null) {
12114            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12115        }
12116
12117        r = null;
12118        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12119            // Only system apps can hold shared libraries.
12120            if (pkg.libraryNames != null) {
12121                for (i = 0; i < pkg.libraryNames.size(); i++) {
12122                    String name = pkg.libraryNames.get(i);
12123                    if (removeSharedLibraryLPw(name, 0)) {
12124                        if (DEBUG_REMOVE && chatty) {
12125                            if (r == null) {
12126                                r = new StringBuilder(256);
12127                            } else {
12128                                r.append(' ');
12129                            }
12130                            r.append(name);
12131                        }
12132                    }
12133                }
12134            }
12135        }
12136
12137        r = null;
12138
12139        // Any package can hold static shared libraries.
12140        if (pkg.staticSharedLibName != null) {
12141            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12142                if (DEBUG_REMOVE && chatty) {
12143                    if (r == null) {
12144                        r = new StringBuilder(256);
12145                    } else {
12146                        r.append(' ');
12147                    }
12148                    r.append(pkg.staticSharedLibName);
12149                }
12150            }
12151        }
12152
12153        if (r != null) {
12154            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12155        }
12156    }
12157
12158
12159    final class ActivityIntentResolver
12160            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12161        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12162                boolean defaultOnly, int userId) {
12163            if (!sUserManager.exists(userId)) return null;
12164            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12165            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12166        }
12167
12168        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12169                int userId) {
12170            if (!sUserManager.exists(userId)) return null;
12171            mFlags = flags;
12172            return super.queryIntent(intent, resolvedType,
12173                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12174                    userId);
12175        }
12176
12177        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12178                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12179            if (!sUserManager.exists(userId)) return null;
12180            if (packageActivities == null) {
12181                return null;
12182            }
12183            mFlags = flags;
12184            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12185            final int N = packageActivities.size();
12186            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12187                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12188
12189            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12190            for (int i = 0; i < N; ++i) {
12191                intentFilters = packageActivities.get(i).intents;
12192                if (intentFilters != null && intentFilters.size() > 0) {
12193                    PackageParser.ActivityIntentInfo[] array =
12194                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12195                    intentFilters.toArray(array);
12196                    listCut.add(array);
12197                }
12198            }
12199            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12200        }
12201
12202        /**
12203         * Finds a privileged activity that matches the specified activity names.
12204         */
12205        private PackageParser.Activity findMatchingActivity(
12206                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12207            for (PackageParser.Activity sysActivity : activityList) {
12208                if (sysActivity.info.name.equals(activityInfo.name)) {
12209                    return sysActivity;
12210                }
12211                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12212                    return sysActivity;
12213                }
12214                if (sysActivity.info.targetActivity != null) {
12215                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12216                        return sysActivity;
12217                    }
12218                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12219                        return sysActivity;
12220                    }
12221                }
12222            }
12223            return null;
12224        }
12225
12226        public class IterGenerator<E> {
12227            public Iterator<E> generate(ActivityIntentInfo info) {
12228                return null;
12229            }
12230        }
12231
12232        public class ActionIterGenerator extends IterGenerator<String> {
12233            @Override
12234            public Iterator<String> generate(ActivityIntentInfo info) {
12235                return info.actionsIterator();
12236            }
12237        }
12238
12239        public class CategoriesIterGenerator extends IterGenerator<String> {
12240            @Override
12241            public Iterator<String> generate(ActivityIntentInfo info) {
12242                return info.categoriesIterator();
12243            }
12244        }
12245
12246        public class SchemesIterGenerator extends IterGenerator<String> {
12247            @Override
12248            public Iterator<String> generate(ActivityIntentInfo info) {
12249                return info.schemesIterator();
12250            }
12251        }
12252
12253        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12254            @Override
12255            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12256                return info.authoritiesIterator();
12257            }
12258        }
12259
12260        /**
12261         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12262         * MODIFIED. Do not pass in a list that should not be changed.
12263         */
12264        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12265                IterGenerator<T> generator, Iterator<T> searchIterator) {
12266            // loop through the set of actions; every one must be found in the intent filter
12267            while (searchIterator.hasNext()) {
12268                // we must have at least one filter in the list to consider a match
12269                if (intentList.size() == 0) {
12270                    break;
12271                }
12272
12273                final T searchAction = searchIterator.next();
12274
12275                // loop through the set of intent filters
12276                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12277                while (intentIter.hasNext()) {
12278                    final ActivityIntentInfo intentInfo = intentIter.next();
12279                    boolean selectionFound = false;
12280
12281                    // loop through the intent filter's selection criteria; at least one
12282                    // of them must match the searched criteria
12283                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12284                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12285                        final T intentSelection = intentSelectionIter.next();
12286                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12287                            selectionFound = true;
12288                            break;
12289                        }
12290                    }
12291
12292                    // the selection criteria wasn't found in this filter's set; this filter
12293                    // is not a potential match
12294                    if (!selectionFound) {
12295                        intentIter.remove();
12296                    }
12297                }
12298            }
12299        }
12300
12301        private boolean isProtectedAction(ActivityIntentInfo filter) {
12302            final Iterator<String> actionsIter = filter.actionsIterator();
12303            while (actionsIter != null && actionsIter.hasNext()) {
12304                final String filterAction = actionsIter.next();
12305                if (PROTECTED_ACTIONS.contains(filterAction)) {
12306                    return true;
12307                }
12308            }
12309            return false;
12310        }
12311
12312        /**
12313         * Adjusts the priority of the given intent filter according to policy.
12314         * <p>
12315         * <ul>
12316         * <li>The priority for non privileged applications is capped to '0'</li>
12317         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12318         * <li>The priority for unbundled updates to privileged applications is capped to the
12319         *      priority defined on the system partition</li>
12320         * </ul>
12321         * <p>
12322         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12323         * allowed to obtain any priority on any action.
12324         */
12325        private void adjustPriority(
12326                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12327            // nothing to do; priority is fine as-is
12328            if (intent.getPriority() <= 0) {
12329                return;
12330            }
12331
12332            final ActivityInfo activityInfo = intent.activity.info;
12333            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12334
12335            final boolean privilegedApp =
12336                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12337            if (!privilegedApp) {
12338                // non-privileged applications can never define a priority >0
12339                if (DEBUG_FILTERS) {
12340                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12341                            + " package: " + applicationInfo.packageName
12342                            + " activity: " + intent.activity.className
12343                            + " origPrio: " + intent.getPriority());
12344                }
12345                intent.setPriority(0);
12346                return;
12347            }
12348
12349            if (systemActivities == null) {
12350                // the system package is not disabled; we're parsing the system partition
12351                if (isProtectedAction(intent)) {
12352                    if (mDeferProtectedFilters) {
12353                        // We can't deal with these just yet. No component should ever obtain a
12354                        // >0 priority for a protected actions, with ONE exception -- the setup
12355                        // wizard. The setup wizard, however, cannot be known until we're able to
12356                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12357                        // until all intent filters have been processed. Chicken, meet egg.
12358                        // Let the filter temporarily have a high priority and rectify the
12359                        // priorities after all system packages have been scanned.
12360                        mProtectedFilters.add(intent);
12361                        if (DEBUG_FILTERS) {
12362                            Slog.i(TAG, "Protected action; save for later;"
12363                                    + " package: " + applicationInfo.packageName
12364                                    + " activity: " + intent.activity.className
12365                                    + " origPrio: " + intent.getPriority());
12366                        }
12367                        return;
12368                    } else {
12369                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12370                            Slog.i(TAG, "No setup wizard;"
12371                                + " All protected intents capped to priority 0");
12372                        }
12373                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12374                            if (DEBUG_FILTERS) {
12375                                Slog.i(TAG, "Found setup wizard;"
12376                                    + " allow priority " + intent.getPriority() + ";"
12377                                    + " package: " + intent.activity.info.packageName
12378                                    + " activity: " + intent.activity.className
12379                                    + " priority: " + intent.getPriority());
12380                            }
12381                            // setup wizard gets whatever it wants
12382                            return;
12383                        }
12384                        if (DEBUG_FILTERS) {
12385                            Slog.i(TAG, "Protected action; cap priority to 0;"
12386                                    + " package: " + intent.activity.info.packageName
12387                                    + " activity: " + intent.activity.className
12388                                    + " origPrio: " + intent.getPriority());
12389                        }
12390                        intent.setPriority(0);
12391                        return;
12392                    }
12393                }
12394                // privileged apps on the system image get whatever priority they request
12395                return;
12396            }
12397
12398            // privileged app unbundled update ... try to find the same activity
12399            final PackageParser.Activity foundActivity =
12400                    findMatchingActivity(systemActivities, activityInfo);
12401            if (foundActivity == null) {
12402                // this is a new activity; it cannot obtain >0 priority
12403                if (DEBUG_FILTERS) {
12404                    Slog.i(TAG, "New activity; cap priority to 0;"
12405                            + " package: " + applicationInfo.packageName
12406                            + " activity: " + intent.activity.className
12407                            + " origPrio: " + intent.getPriority());
12408                }
12409                intent.setPriority(0);
12410                return;
12411            }
12412
12413            // found activity, now check for filter equivalence
12414
12415            // a shallow copy is enough; we modify the list, not its contents
12416            final List<ActivityIntentInfo> intentListCopy =
12417                    new ArrayList<>(foundActivity.intents);
12418            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12419
12420            // find matching action subsets
12421            final Iterator<String> actionsIterator = intent.actionsIterator();
12422            if (actionsIterator != null) {
12423                getIntentListSubset(
12424                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12425                if (intentListCopy.size() == 0) {
12426                    // no more intents to match; we're not equivalent
12427                    if (DEBUG_FILTERS) {
12428                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12429                                + " package: " + applicationInfo.packageName
12430                                + " activity: " + intent.activity.className
12431                                + " origPrio: " + intent.getPriority());
12432                    }
12433                    intent.setPriority(0);
12434                    return;
12435                }
12436            }
12437
12438            // find matching category subsets
12439            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12440            if (categoriesIterator != null) {
12441                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12442                        categoriesIterator);
12443                if (intentListCopy.size() == 0) {
12444                    // no more intents to match; we're not equivalent
12445                    if (DEBUG_FILTERS) {
12446                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12447                                + " package: " + applicationInfo.packageName
12448                                + " activity: " + intent.activity.className
12449                                + " origPrio: " + intent.getPriority());
12450                    }
12451                    intent.setPriority(0);
12452                    return;
12453                }
12454            }
12455
12456            // find matching schemes subsets
12457            final Iterator<String> schemesIterator = intent.schemesIterator();
12458            if (schemesIterator != null) {
12459                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12460                        schemesIterator);
12461                if (intentListCopy.size() == 0) {
12462                    // no more intents to match; we're not equivalent
12463                    if (DEBUG_FILTERS) {
12464                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12465                                + " package: " + applicationInfo.packageName
12466                                + " activity: " + intent.activity.className
12467                                + " origPrio: " + intent.getPriority());
12468                    }
12469                    intent.setPriority(0);
12470                    return;
12471                }
12472            }
12473
12474            // find matching authorities subsets
12475            final Iterator<IntentFilter.AuthorityEntry>
12476                    authoritiesIterator = intent.authoritiesIterator();
12477            if (authoritiesIterator != null) {
12478                getIntentListSubset(intentListCopy,
12479                        new AuthoritiesIterGenerator(),
12480                        authoritiesIterator);
12481                if (intentListCopy.size() == 0) {
12482                    // no more intents to match; we're not equivalent
12483                    if (DEBUG_FILTERS) {
12484                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12485                                + " package: " + applicationInfo.packageName
12486                                + " activity: " + intent.activity.className
12487                                + " origPrio: " + intent.getPriority());
12488                    }
12489                    intent.setPriority(0);
12490                    return;
12491                }
12492            }
12493
12494            // we found matching filter(s); app gets the max priority of all intents
12495            int cappedPriority = 0;
12496            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12497                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12498            }
12499            if (intent.getPriority() > cappedPriority) {
12500                if (DEBUG_FILTERS) {
12501                    Slog.i(TAG, "Found matching filter(s);"
12502                            + " cap priority to " + cappedPriority + ";"
12503                            + " package: " + applicationInfo.packageName
12504                            + " activity: " + intent.activity.className
12505                            + " origPrio: " + intent.getPriority());
12506                }
12507                intent.setPriority(cappedPriority);
12508                return;
12509            }
12510            // all this for nothing; the requested priority was <= what was on the system
12511        }
12512
12513        public final void addActivity(PackageParser.Activity a, String type) {
12514            mActivities.put(a.getComponentName(), a);
12515            if (DEBUG_SHOW_INFO)
12516                Log.v(
12517                TAG, "  " + type + " " +
12518                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12519            if (DEBUG_SHOW_INFO)
12520                Log.v(TAG, "    Class=" + a.info.name);
12521            final int NI = a.intents.size();
12522            for (int j=0; j<NI; j++) {
12523                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12524                if ("activity".equals(type)) {
12525                    final PackageSetting ps =
12526                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12527                    final List<PackageParser.Activity> systemActivities =
12528                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12529                    adjustPriority(systemActivities, intent);
12530                }
12531                if (DEBUG_SHOW_INFO) {
12532                    Log.v(TAG, "    IntentFilter:");
12533                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12534                }
12535                if (!intent.debugCheck()) {
12536                    Log.w(TAG, "==> For Activity " + a.info.name);
12537                }
12538                addFilter(intent);
12539            }
12540        }
12541
12542        public final void removeActivity(PackageParser.Activity a, String type) {
12543            mActivities.remove(a.getComponentName());
12544            if (DEBUG_SHOW_INFO) {
12545                Log.v(TAG, "  " + type + " "
12546                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12547                                : a.info.name) + ":");
12548                Log.v(TAG, "    Class=" + a.info.name);
12549            }
12550            final int NI = a.intents.size();
12551            for (int j=0; j<NI; j++) {
12552                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12553                if (DEBUG_SHOW_INFO) {
12554                    Log.v(TAG, "    IntentFilter:");
12555                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12556                }
12557                removeFilter(intent);
12558            }
12559        }
12560
12561        @Override
12562        protected boolean allowFilterResult(
12563                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12564            ActivityInfo filterAi = filter.activity.info;
12565            for (int i=dest.size()-1; i>=0; i--) {
12566                ActivityInfo destAi = dest.get(i).activityInfo;
12567                if (destAi.name == filterAi.name
12568                        && destAi.packageName == filterAi.packageName) {
12569                    return false;
12570                }
12571            }
12572            return true;
12573        }
12574
12575        @Override
12576        protected ActivityIntentInfo[] newArray(int size) {
12577            return new ActivityIntentInfo[size];
12578        }
12579
12580        @Override
12581        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12582            if (!sUserManager.exists(userId)) return true;
12583            PackageParser.Package p = filter.activity.owner;
12584            if (p != null) {
12585                PackageSetting ps = (PackageSetting)p.mExtras;
12586                if (ps != null) {
12587                    // System apps are never considered stopped for purposes of
12588                    // filtering, because there may be no way for the user to
12589                    // actually re-launch them.
12590                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12591                            && ps.getStopped(userId);
12592                }
12593            }
12594            return false;
12595        }
12596
12597        @Override
12598        protected boolean isPackageForFilter(String packageName,
12599                PackageParser.ActivityIntentInfo info) {
12600            return packageName.equals(info.activity.owner.packageName);
12601        }
12602
12603        @Override
12604        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12605                int match, int userId) {
12606            if (!sUserManager.exists(userId)) return null;
12607            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12608                return null;
12609            }
12610            final PackageParser.Activity activity = info.activity;
12611            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12612            if (ps == null) {
12613                return null;
12614            }
12615            final PackageUserState userState = ps.readUserState(userId);
12616            ActivityInfo ai =
12617                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12618            if (ai == null) {
12619                return null;
12620            }
12621            final boolean matchExplicitlyVisibleOnly =
12622                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12623            final boolean matchVisibleToInstantApp =
12624                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12625            final boolean componentVisible =
12626                    matchVisibleToInstantApp
12627                    && info.isVisibleToInstantApp()
12628                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12629            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12630            // throw out filters that aren't visible to ephemeral apps
12631            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12632                return null;
12633            }
12634            // throw out instant app filters if we're not explicitly requesting them
12635            if (!matchInstantApp && userState.instantApp) {
12636                return null;
12637            }
12638            // throw out instant app filters if updates are available; will trigger
12639            // instant app resolution
12640            if (userState.instantApp && ps.isUpdateAvailable()) {
12641                return null;
12642            }
12643            final ResolveInfo res = new ResolveInfo();
12644            res.activityInfo = ai;
12645            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12646                res.filter = info;
12647            }
12648            if (info != null) {
12649                res.handleAllWebDataURI = info.handleAllWebDataURI();
12650            }
12651            res.priority = info.getPriority();
12652            res.preferredOrder = activity.owner.mPreferredOrder;
12653            //System.out.println("Result: " + res.activityInfo.className +
12654            //                   " = " + res.priority);
12655            res.match = match;
12656            res.isDefault = info.hasDefault;
12657            res.labelRes = info.labelRes;
12658            res.nonLocalizedLabel = info.nonLocalizedLabel;
12659            if (userNeedsBadging(userId)) {
12660                res.noResourceId = true;
12661            } else {
12662                res.icon = info.icon;
12663            }
12664            res.iconResourceId = info.icon;
12665            res.system = res.activityInfo.applicationInfo.isSystemApp();
12666            res.isInstantAppAvailable = userState.instantApp;
12667            return res;
12668        }
12669
12670        @Override
12671        protected void sortResults(List<ResolveInfo> results) {
12672            Collections.sort(results, mResolvePrioritySorter);
12673        }
12674
12675        @Override
12676        protected void dumpFilter(PrintWriter out, String prefix,
12677                PackageParser.ActivityIntentInfo filter) {
12678            out.print(prefix); out.print(
12679                    Integer.toHexString(System.identityHashCode(filter.activity)));
12680                    out.print(' ');
12681                    filter.activity.printComponentShortName(out);
12682                    out.print(" filter ");
12683                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12684        }
12685
12686        @Override
12687        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12688            return filter.activity;
12689        }
12690
12691        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12692            PackageParser.Activity activity = (PackageParser.Activity)label;
12693            out.print(prefix); out.print(
12694                    Integer.toHexString(System.identityHashCode(activity)));
12695                    out.print(' ');
12696                    activity.printComponentShortName(out);
12697            if (count > 1) {
12698                out.print(" ("); out.print(count); out.print(" filters)");
12699            }
12700            out.println();
12701        }
12702
12703        // Keys are String (activity class name), values are Activity.
12704        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12705                = new ArrayMap<ComponentName, PackageParser.Activity>();
12706        private int mFlags;
12707    }
12708
12709    private final class ServiceIntentResolver
12710            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12711        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12712                boolean defaultOnly, int userId) {
12713            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12714            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12715        }
12716
12717        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12718                int userId) {
12719            if (!sUserManager.exists(userId)) return null;
12720            mFlags = flags;
12721            return super.queryIntent(intent, resolvedType,
12722                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12723                    userId);
12724        }
12725
12726        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12727                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12728            if (!sUserManager.exists(userId)) return null;
12729            if (packageServices == null) {
12730                return null;
12731            }
12732            mFlags = flags;
12733            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12734            final int N = packageServices.size();
12735            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12736                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12737
12738            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12739            for (int i = 0; i < N; ++i) {
12740                intentFilters = packageServices.get(i).intents;
12741                if (intentFilters != null && intentFilters.size() > 0) {
12742                    PackageParser.ServiceIntentInfo[] array =
12743                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12744                    intentFilters.toArray(array);
12745                    listCut.add(array);
12746                }
12747            }
12748            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12749        }
12750
12751        public final void addService(PackageParser.Service s) {
12752            mServices.put(s.getComponentName(), s);
12753            if (DEBUG_SHOW_INFO) {
12754                Log.v(TAG, "  "
12755                        + (s.info.nonLocalizedLabel != null
12756                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12757                Log.v(TAG, "    Class=" + s.info.name);
12758            }
12759            final int NI = s.intents.size();
12760            int j;
12761            for (j=0; j<NI; j++) {
12762                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12763                if (DEBUG_SHOW_INFO) {
12764                    Log.v(TAG, "    IntentFilter:");
12765                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12766                }
12767                if (!intent.debugCheck()) {
12768                    Log.w(TAG, "==> For Service " + s.info.name);
12769                }
12770                addFilter(intent);
12771            }
12772        }
12773
12774        public final void removeService(PackageParser.Service s) {
12775            mServices.remove(s.getComponentName());
12776            if (DEBUG_SHOW_INFO) {
12777                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12778                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12779                Log.v(TAG, "    Class=" + s.info.name);
12780            }
12781            final int NI = s.intents.size();
12782            int j;
12783            for (j=0; j<NI; j++) {
12784                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12785                if (DEBUG_SHOW_INFO) {
12786                    Log.v(TAG, "    IntentFilter:");
12787                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12788                }
12789                removeFilter(intent);
12790            }
12791        }
12792
12793        @Override
12794        protected boolean allowFilterResult(
12795                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12796            ServiceInfo filterSi = filter.service.info;
12797            for (int i=dest.size()-1; i>=0; i--) {
12798                ServiceInfo destAi = dest.get(i).serviceInfo;
12799                if (destAi.name == filterSi.name
12800                        && destAi.packageName == filterSi.packageName) {
12801                    return false;
12802                }
12803            }
12804            return true;
12805        }
12806
12807        @Override
12808        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12809            return new PackageParser.ServiceIntentInfo[size];
12810        }
12811
12812        @Override
12813        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12814            if (!sUserManager.exists(userId)) return true;
12815            PackageParser.Package p = filter.service.owner;
12816            if (p != null) {
12817                PackageSetting ps = (PackageSetting)p.mExtras;
12818                if (ps != null) {
12819                    // System apps are never considered stopped for purposes of
12820                    // filtering, because there may be no way for the user to
12821                    // actually re-launch them.
12822                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12823                            && ps.getStopped(userId);
12824                }
12825            }
12826            return false;
12827        }
12828
12829        @Override
12830        protected boolean isPackageForFilter(String packageName,
12831                PackageParser.ServiceIntentInfo info) {
12832            return packageName.equals(info.service.owner.packageName);
12833        }
12834
12835        @Override
12836        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12837                int match, int userId) {
12838            if (!sUserManager.exists(userId)) return null;
12839            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12840            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12841                return null;
12842            }
12843            final PackageParser.Service service = info.service;
12844            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12845            if (ps == null) {
12846                return null;
12847            }
12848            final PackageUserState userState = ps.readUserState(userId);
12849            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12850                    userState, userId);
12851            if (si == null) {
12852                return null;
12853            }
12854            final boolean matchVisibleToInstantApp =
12855                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12856            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12857            // throw out filters that aren't visible to ephemeral apps
12858            if (matchVisibleToInstantApp
12859                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12860                return null;
12861            }
12862            // throw out ephemeral filters if we're not explicitly requesting them
12863            if (!isInstantApp && userState.instantApp) {
12864                return null;
12865            }
12866            // throw out instant app filters if updates are available; will trigger
12867            // instant app resolution
12868            if (userState.instantApp && ps.isUpdateAvailable()) {
12869                return null;
12870            }
12871            final ResolveInfo res = new ResolveInfo();
12872            res.serviceInfo = si;
12873            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12874                res.filter = filter;
12875            }
12876            res.priority = info.getPriority();
12877            res.preferredOrder = service.owner.mPreferredOrder;
12878            res.match = match;
12879            res.isDefault = info.hasDefault;
12880            res.labelRes = info.labelRes;
12881            res.nonLocalizedLabel = info.nonLocalizedLabel;
12882            res.icon = info.icon;
12883            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12884            return res;
12885        }
12886
12887        @Override
12888        protected void sortResults(List<ResolveInfo> results) {
12889            Collections.sort(results, mResolvePrioritySorter);
12890        }
12891
12892        @Override
12893        protected void dumpFilter(PrintWriter out, String prefix,
12894                PackageParser.ServiceIntentInfo filter) {
12895            out.print(prefix); out.print(
12896                    Integer.toHexString(System.identityHashCode(filter.service)));
12897                    out.print(' ');
12898                    filter.service.printComponentShortName(out);
12899                    out.print(" filter ");
12900                    out.print(Integer.toHexString(System.identityHashCode(filter)));
12901                    if (filter.service.info.permission != null) {
12902                        out.print(" permission "); out.println(filter.service.info.permission);
12903                    } else {
12904                        out.println();
12905                    }
12906        }
12907
12908        @Override
12909        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12910            return filter.service;
12911        }
12912
12913        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12914            PackageParser.Service service = (PackageParser.Service)label;
12915            out.print(prefix); out.print(
12916                    Integer.toHexString(System.identityHashCode(service)));
12917                    out.print(' ');
12918                    service.printComponentShortName(out);
12919            if (count > 1) {
12920                out.print(" ("); out.print(count); out.print(" filters)");
12921            }
12922            out.println();
12923        }
12924
12925//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12926//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12927//            final List<ResolveInfo> retList = Lists.newArrayList();
12928//            while (i.hasNext()) {
12929//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12930//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12931//                    retList.add(resolveInfo);
12932//                }
12933//            }
12934//            return retList;
12935//        }
12936
12937        // Keys are String (activity class name), values are Activity.
12938        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12939                = new ArrayMap<ComponentName, PackageParser.Service>();
12940        private int mFlags;
12941    }
12942
12943    private final class ProviderIntentResolver
12944            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12945        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12946                boolean defaultOnly, int userId) {
12947            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12948            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12949        }
12950
12951        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12952                int userId) {
12953            if (!sUserManager.exists(userId))
12954                return null;
12955            mFlags = flags;
12956            return super.queryIntent(intent, resolvedType,
12957                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12958                    userId);
12959        }
12960
12961        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12962                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12963            if (!sUserManager.exists(userId))
12964                return null;
12965            if (packageProviders == null) {
12966                return null;
12967            }
12968            mFlags = flags;
12969            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12970            final int N = packageProviders.size();
12971            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12972                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12973
12974            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12975            for (int i = 0; i < N; ++i) {
12976                intentFilters = packageProviders.get(i).intents;
12977                if (intentFilters != null && intentFilters.size() > 0) {
12978                    PackageParser.ProviderIntentInfo[] array =
12979                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12980                    intentFilters.toArray(array);
12981                    listCut.add(array);
12982                }
12983            }
12984            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12985        }
12986
12987        public final void addProvider(PackageParser.Provider p) {
12988            if (mProviders.containsKey(p.getComponentName())) {
12989                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12990                return;
12991            }
12992
12993            mProviders.put(p.getComponentName(), p);
12994            if (DEBUG_SHOW_INFO) {
12995                Log.v(TAG, "  "
12996                        + (p.info.nonLocalizedLabel != null
12997                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12998                Log.v(TAG, "    Class=" + p.info.name);
12999            }
13000            final int NI = p.intents.size();
13001            int j;
13002            for (j = 0; j < NI; j++) {
13003                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13004                if (DEBUG_SHOW_INFO) {
13005                    Log.v(TAG, "    IntentFilter:");
13006                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13007                }
13008                if (!intent.debugCheck()) {
13009                    Log.w(TAG, "==> For Provider " + p.info.name);
13010                }
13011                addFilter(intent);
13012            }
13013        }
13014
13015        public final void removeProvider(PackageParser.Provider p) {
13016            mProviders.remove(p.getComponentName());
13017            if (DEBUG_SHOW_INFO) {
13018                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13019                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13020                Log.v(TAG, "    Class=" + p.info.name);
13021            }
13022            final int NI = p.intents.size();
13023            int j;
13024            for (j = 0; j < NI; j++) {
13025                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13026                if (DEBUG_SHOW_INFO) {
13027                    Log.v(TAG, "    IntentFilter:");
13028                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13029                }
13030                removeFilter(intent);
13031            }
13032        }
13033
13034        @Override
13035        protected boolean allowFilterResult(
13036                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13037            ProviderInfo filterPi = filter.provider.info;
13038            for (int i = dest.size() - 1; i >= 0; i--) {
13039                ProviderInfo destPi = dest.get(i).providerInfo;
13040                if (destPi.name == filterPi.name
13041                        && destPi.packageName == filterPi.packageName) {
13042                    return false;
13043                }
13044            }
13045            return true;
13046        }
13047
13048        @Override
13049        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13050            return new PackageParser.ProviderIntentInfo[size];
13051        }
13052
13053        @Override
13054        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13055            if (!sUserManager.exists(userId))
13056                return true;
13057            PackageParser.Package p = filter.provider.owner;
13058            if (p != null) {
13059                PackageSetting ps = (PackageSetting) p.mExtras;
13060                if (ps != null) {
13061                    // System apps are never considered stopped for purposes of
13062                    // filtering, because there may be no way for the user to
13063                    // actually re-launch them.
13064                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13065                            && ps.getStopped(userId);
13066                }
13067            }
13068            return false;
13069        }
13070
13071        @Override
13072        protected boolean isPackageForFilter(String packageName,
13073                PackageParser.ProviderIntentInfo info) {
13074            return packageName.equals(info.provider.owner.packageName);
13075        }
13076
13077        @Override
13078        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13079                int match, int userId) {
13080            if (!sUserManager.exists(userId))
13081                return null;
13082            final PackageParser.ProviderIntentInfo info = filter;
13083            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13084                return null;
13085            }
13086            final PackageParser.Provider provider = info.provider;
13087            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13088            if (ps == null) {
13089                return null;
13090            }
13091            final PackageUserState userState = ps.readUserState(userId);
13092            final boolean matchVisibleToInstantApp =
13093                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13094            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13095            // throw out filters that aren't visible to instant applications
13096            if (matchVisibleToInstantApp
13097                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13098                return null;
13099            }
13100            // throw out instant application filters if we're not explicitly requesting them
13101            if (!isInstantApp && userState.instantApp) {
13102                return null;
13103            }
13104            // throw out instant application filters if updates are available; will trigger
13105            // instant application resolution
13106            if (userState.instantApp && ps.isUpdateAvailable()) {
13107                return null;
13108            }
13109            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13110                    userState, userId);
13111            if (pi == null) {
13112                return null;
13113            }
13114            final ResolveInfo res = new ResolveInfo();
13115            res.providerInfo = pi;
13116            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13117                res.filter = filter;
13118            }
13119            res.priority = info.getPriority();
13120            res.preferredOrder = provider.owner.mPreferredOrder;
13121            res.match = match;
13122            res.isDefault = info.hasDefault;
13123            res.labelRes = info.labelRes;
13124            res.nonLocalizedLabel = info.nonLocalizedLabel;
13125            res.icon = info.icon;
13126            res.system = res.providerInfo.applicationInfo.isSystemApp();
13127            return res;
13128        }
13129
13130        @Override
13131        protected void sortResults(List<ResolveInfo> results) {
13132            Collections.sort(results, mResolvePrioritySorter);
13133        }
13134
13135        @Override
13136        protected void dumpFilter(PrintWriter out, String prefix,
13137                PackageParser.ProviderIntentInfo filter) {
13138            out.print(prefix);
13139            out.print(
13140                    Integer.toHexString(System.identityHashCode(filter.provider)));
13141            out.print(' ');
13142            filter.provider.printComponentShortName(out);
13143            out.print(" filter ");
13144            out.println(Integer.toHexString(System.identityHashCode(filter)));
13145        }
13146
13147        @Override
13148        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13149            return filter.provider;
13150        }
13151
13152        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13153            PackageParser.Provider provider = (PackageParser.Provider)label;
13154            out.print(prefix); out.print(
13155                    Integer.toHexString(System.identityHashCode(provider)));
13156                    out.print(' ');
13157                    provider.printComponentShortName(out);
13158            if (count > 1) {
13159                out.print(" ("); out.print(count); out.print(" filters)");
13160            }
13161            out.println();
13162        }
13163
13164        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13165                = new ArrayMap<ComponentName, PackageParser.Provider>();
13166        private int mFlags;
13167    }
13168
13169    static final class InstantAppIntentResolver
13170            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13171            AuxiliaryResolveInfo.AuxiliaryFilter> {
13172        /**
13173         * The result that has the highest defined order. Ordering applies on a
13174         * per-package basis. Mapping is from package name to Pair of order and
13175         * EphemeralResolveInfo.
13176         * <p>
13177         * NOTE: This is implemented as a field variable for convenience and efficiency.
13178         * By having a field variable, we're able to track filter ordering as soon as
13179         * a non-zero order is defined. Otherwise, multiple loops across the result set
13180         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13181         * this needs to be contained entirely within {@link #filterResults}.
13182         */
13183        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13184
13185        @Override
13186        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13187            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13188        }
13189
13190        @Override
13191        protected boolean isPackageForFilter(String packageName,
13192                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13193            return true;
13194        }
13195
13196        @Override
13197        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13198                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13199            if (!sUserManager.exists(userId)) {
13200                return null;
13201            }
13202            final String packageName = responseObj.resolveInfo.getPackageName();
13203            final Integer order = responseObj.getOrder();
13204            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13205                    mOrderResult.get(packageName);
13206            // ordering is enabled and this item's order isn't high enough
13207            if (lastOrderResult != null && lastOrderResult.first >= order) {
13208                return null;
13209            }
13210            final InstantAppResolveInfo res = responseObj.resolveInfo;
13211            if (order > 0) {
13212                // non-zero order, enable ordering
13213                mOrderResult.put(packageName, new Pair<>(order, res));
13214            }
13215            return responseObj;
13216        }
13217
13218        @Override
13219        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13220            // only do work if ordering is enabled [most of the time it won't be]
13221            if (mOrderResult.size() == 0) {
13222                return;
13223            }
13224            int resultSize = results.size();
13225            for (int i = 0; i < resultSize; i++) {
13226                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13227                final String packageName = info.getPackageName();
13228                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13229                if (savedInfo == null) {
13230                    // package doesn't having ordering
13231                    continue;
13232                }
13233                if (savedInfo.second == info) {
13234                    // circled back to the highest ordered item; remove from order list
13235                    mOrderResult.remove(packageName);
13236                    if (mOrderResult.size() == 0) {
13237                        // no more ordered items
13238                        break;
13239                    }
13240                    continue;
13241                }
13242                // item has a worse order, remove it from the result list
13243                results.remove(i);
13244                resultSize--;
13245                i--;
13246            }
13247        }
13248    }
13249
13250    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13251            new Comparator<ResolveInfo>() {
13252        public int compare(ResolveInfo r1, ResolveInfo r2) {
13253            int v1 = r1.priority;
13254            int v2 = r2.priority;
13255            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13256            if (v1 != v2) {
13257                return (v1 > v2) ? -1 : 1;
13258            }
13259            v1 = r1.preferredOrder;
13260            v2 = r2.preferredOrder;
13261            if (v1 != v2) {
13262                return (v1 > v2) ? -1 : 1;
13263            }
13264            if (r1.isDefault != r2.isDefault) {
13265                return r1.isDefault ? -1 : 1;
13266            }
13267            v1 = r1.match;
13268            v2 = r2.match;
13269            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13270            if (v1 != v2) {
13271                return (v1 > v2) ? -1 : 1;
13272            }
13273            if (r1.system != r2.system) {
13274                return r1.system ? -1 : 1;
13275            }
13276            if (r1.activityInfo != null) {
13277                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13278            }
13279            if (r1.serviceInfo != null) {
13280                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13281            }
13282            if (r1.providerInfo != null) {
13283                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13284            }
13285            return 0;
13286        }
13287    };
13288
13289    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13290            new Comparator<ProviderInfo>() {
13291        public int compare(ProviderInfo p1, ProviderInfo p2) {
13292            final int v1 = p1.initOrder;
13293            final int v2 = p2.initOrder;
13294            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13295        }
13296    };
13297
13298    @Override
13299    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13300            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13301            final int[] userIds, int[] instantUserIds) {
13302        mHandler.post(new Runnable() {
13303            @Override
13304            public void run() {
13305                try {
13306                    final IActivityManager am = ActivityManager.getService();
13307                    if (am == null) return;
13308                    final int[] resolvedUserIds;
13309                    if (userIds == null) {
13310                        resolvedUserIds = am.getRunningUserIds();
13311                    } else {
13312                        resolvedUserIds = userIds;
13313                    }
13314                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13315                            resolvedUserIds, false);
13316                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13317                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13318                                instantUserIds, true);
13319                    }
13320                } catch (RemoteException ex) {
13321                }
13322            }
13323        });
13324    }
13325
13326    @Override
13327    public void notifyPackageAdded(String packageName) {
13328        final PackageListObserver[] observers;
13329        synchronized (mPackages) {
13330            if (mPackageListObservers.size() == 0) {
13331                return;
13332            }
13333            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13334        }
13335        for (int i = observers.length - 1; i >= 0; --i) {
13336            observers[i].onPackageAdded(packageName);
13337        }
13338    }
13339
13340    @Override
13341    public void notifyPackageRemoved(String packageName) {
13342        final PackageListObserver[] observers;
13343        synchronized (mPackages) {
13344            if (mPackageListObservers.size() == 0) {
13345                return;
13346            }
13347            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13348        }
13349        for (int i = observers.length - 1; i >= 0; --i) {
13350            observers[i].onPackageRemoved(packageName);
13351        }
13352    }
13353
13354    /**
13355     * Sends a broadcast for the given action.
13356     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13357     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13358     * the system and applications allowed to see instant applications to receive package
13359     * lifecycle events for instant applications.
13360     */
13361    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13362            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13363            int[] userIds, boolean isInstantApp)
13364                    throws RemoteException {
13365        for (int id : userIds) {
13366            final Intent intent = new Intent(action,
13367                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13368            final String[] requiredPermissions =
13369                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13370            if (extras != null) {
13371                intent.putExtras(extras);
13372            }
13373            if (targetPkg != null) {
13374                intent.setPackage(targetPkg);
13375            }
13376            // Modify the UID when posting to other users
13377            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13378            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13379                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13380                intent.putExtra(Intent.EXTRA_UID, uid);
13381            }
13382            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13383            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13384            if (DEBUG_BROADCASTS) {
13385                RuntimeException here = new RuntimeException("here");
13386                here.fillInStackTrace();
13387                Slog.d(TAG, "Sending to user " + id + ": "
13388                        + intent.toShortString(false, true, false, false)
13389                        + " " + intent.getExtras(), here);
13390            }
13391            am.broadcastIntent(null, intent, null, finishedReceiver,
13392                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13393                    null, finishedReceiver != null, false, id);
13394        }
13395    }
13396
13397    /**
13398     * Check if the external storage media is available. This is true if there
13399     * is a mounted external storage medium or if the external storage is
13400     * emulated.
13401     */
13402    private boolean isExternalMediaAvailable() {
13403        return mMediaMounted || Environment.isExternalStorageEmulated();
13404    }
13405
13406    @Override
13407    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13408        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13409            return null;
13410        }
13411        if (!isExternalMediaAvailable()) {
13412                // If the external storage is no longer mounted at this point,
13413                // the caller may not have been able to delete all of this
13414                // packages files and can not delete any more.  Bail.
13415            return null;
13416        }
13417        synchronized (mPackages) {
13418            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13419            if (lastPackage != null) {
13420                pkgs.remove(lastPackage);
13421            }
13422            if (pkgs.size() > 0) {
13423                return pkgs.get(0);
13424            }
13425        }
13426        return null;
13427    }
13428
13429    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13430        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13431                userId, andCode ? 1 : 0, packageName);
13432        if (mSystemReady) {
13433            msg.sendToTarget();
13434        } else {
13435            if (mPostSystemReadyMessages == null) {
13436                mPostSystemReadyMessages = new ArrayList<>();
13437            }
13438            mPostSystemReadyMessages.add(msg);
13439        }
13440    }
13441
13442    void startCleaningPackages() {
13443        // reader
13444        if (!isExternalMediaAvailable()) {
13445            return;
13446        }
13447        synchronized (mPackages) {
13448            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13449                return;
13450            }
13451        }
13452        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13453        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13454        IActivityManager am = ActivityManager.getService();
13455        if (am != null) {
13456            int dcsUid = -1;
13457            synchronized (mPackages) {
13458                if (!mDefaultContainerWhitelisted) {
13459                    mDefaultContainerWhitelisted = true;
13460                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13461                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13462                }
13463            }
13464            try {
13465                if (dcsUid > 0) {
13466                    am.backgroundWhitelistUid(dcsUid);
13467                }
13468                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13469                        UserHandle.USER_SYSTEM);
13470            } catch (RemoteException e) {
13471            }
13472        }
13473    }
13474
13475    /**
13476     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13477     * it is acting on behalf on an enterprise or the user).
13478     *
13479     * Note that the ordering of the conditionals in this method is important. The checks we perform
13480     * are as follows, in this order:
13481     *
13482     * 1) If the install is being performed by a system app, we can trust the app to have set the
13483     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13484     *    what it is.
13485     * 2) If the install is being performed by a device or profile owner app, the install reason
13486     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13487     *    set the install reason correctly. If the app targets an older SDK version where install
13488     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13489     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13490     * 3) In all other cases, the install is being performed by a regular app that is neither part
13491     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13492     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13493     *    set to enterprise policy and if so, change it to unknown instead.
13494     */
13495    private int fixUpInstallReason(String installerPackageName, int installerUid,
13496            int installReason) {
13497        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13498                == PERMISSION_GRANTED) {
13499            // If the install is being performed by a system app, we trust that app to have set the
13500            // install reason correctly.
13501            return installReason;
13502        }
13503
13504        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13505            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13506        if (dpm != null) {
13507            ComponentName owner = null;
13508            try {
13509                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13510                if (owner == null) {
13511                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13512                }
13513            } catch (RemoteException e) {
13514            }
13515            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13516                // If the install is being performed by a device or profile owner, the install
13517                // reason should be enterprise policy.
13518                return PackageManager.INSTALL_REASON_POLICY;
13519            }
13520        }
13521
13522        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13523            // If the install is being performed by a regular app (i.e. neither system app nor
13524            // device or profile owner), we have no reason to believe that the app is acting on
13525            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13526            // change it to unknown instead.
13527            return PackageManager.INSTALL_REASON_UNKNOWN;
13528        }
13529
13530        // If the install is being performed by a regular app and the install reason was set to any
13531        // value but enterprise policy, leave the install reason unchanged.
13532        return installReason;
13533    }
13534
13535    void installStage(String packageName, File stagedDir,
13536            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13537            String installerPackageName, int installerUid, UserHandle user,
13538            PackageParser.SigningDetails signingDetails) {
13539        if (DEBUG_INSTANT) {
13540            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13541                Slog.d(TAG, "Ephemeral install of " + packageName);
13542            }
13543        }
13544        final VerificationInfo verificationInfo = new VerificationInfo(
13545                sessionParams.originatingUri, sessionParams.referrerUri,
13546                sessionParams.originatingUid, installerUid);
13547
13548        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13549
13550        final Message msg = mHandler.obtainMessage(INIT_COPY);
13551        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13552                sessionParams.installReason);
13553        final InstallParams params = new InstallParams(origin, null, observer,
13554                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13555                verificationInfo, user, sessionParams.abiOverride,
13556                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13557        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13558        msg.obj = params;
13559
13560        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13561                System.identityHashCode(msg.obj));
13562        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13563                System.identityHashCode(msg.obj));
13564
13565        mHandler.sendMessage(msg);
13566    }
13567
13568    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13569            int userId) {
13570        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13571        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13572        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13573        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13574        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13575                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13576
13577        // Send a session commit broadcast
13578        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13579        info.installReason = pkgSetting.getInstallReason(userId);
13580        info.appPackageName = packageName;
13581        sendSessionCommitBroadcast(info, userId);
13582    }
13583
13584    @Override
13585    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13586            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13587        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13588            return;
13589        }
13590        Bundle extras = new Bundle(1);
13591        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13592        final int uid = UserHandle.getUid(
13593                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13594        extras.putInt(Intent.EXTRA_UID, uid);
13595
13596        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13597                packageName, extras, 0, null, null, userIds, instantUserIds);
13598        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13599            mHandler.post(() -> {
13600                        for (int userId : userIds) {
13601                            sendBootCompletedBroadcastToSystemApp(
13602                                    packageName, includeStopped, userId);
13603                        }
13604                    }
13605            );
13606        }
13607    }
13608
13609    /**
13610     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13611     * automatically without needing an explicit launch.
13612     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13613     */
13614    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13615            int userId) {
13616        // If user is not running, the app didn't miss any broadcast
13617        if (!mUserManagerInternal.isUserRunning(userId)) {
13618            return;
13619        }
13620        final IActivityManager am = ActivityManager.getService();
13621        try {
13622            // Deliver LOCKED_BOOT_COMPLETED first
13623            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13624                    .setPackage(packageName);
13625            if (includeStopped) {
13626                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13627            }
13628            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13629            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13630                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13631
13632            // Deliver BOOT_COMPLETED only if user is unlocked
13633            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13634                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13635                if (includeStopped) {
13636                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13637                }
13638                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13639                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13640            }
13641        } catch (RemoteException e) {
13642            throw e.rethrowFromSystemServer();
13643        }
13644    }
13645
13646    @Override
13647    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13648            int userId) {
13649        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13650        PackageSetting pkgSetting;
13651        final int callingUid = Binder.getCallingUid();
13652        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13653                true /* requireFullPermission */, true /* checkShell */,
13654                "setApplicationHiddenSetting for user " + userId);
13655
13656        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13657            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13658            return false;
13659        }
13660
13661        long callingId = Binder.clearCallingIdentity();
13662        try {
13663            boolean sendAdded = false;
13664            boolean sendRemoved = false;
13665            // writer
13666            synchronized (mPackages) {
13667                pkgSetting = mSettings.mPackages.get(packageName);
13668                if (pkgSetting == null) {
13669                    return false;
13670                }
13671                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13672                    return false;
13673                }
13674                // Do not allow "android" is being disabled
13675                if ("android".equals(packageName)) {
13676                    Slog.w(TAG, "Cannot hide package: android");
13677                    return false;
13678                }
13679                // Cannot hide static shared libs as they are considered
13680                // a part of the using app (emulating static linking). Also
13681                // static libs are installed always on internal storage.
13682                PackageParser.Package pkg = mPackages.get(packageName);
13683                if (pkg != null && pkg.staticSharedLibName != null) {
13684                    Slog.w(TAG, "Cannot hide package: " + packageName
13685                            + " providing static shared library: "
13686                            + pkg.staticSharedLibName);
13687                    return false;
13688                }
13689                // Only allow protected packages to hide themselves.
13690                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13691                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13692                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13693                    return false;
13694                }
13695
13696                if (pkgSetting.getHidden(userId) != hidden) {
13697                    pkgSetting.setHidden(hidden, userId);
13698                    mSettings.writePackageRestrictionsLPr(userId);
13699                    if (hidden) {
13700                        sendRemoved = true;
13701                    } else {
13702                        sendAdded = true;
13703                    }
13704                }
13705            }
13706            if (sendAdded) {
13707                sendPackageAddedForUser(packageName, pkgSetting, userId);
13708                return true;
13709            }
13710            if (sendRemoved) {
13711                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13712                        "hiding pkg");
13713                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13714                return true;
13715            }
13716        } finally {
13717            Binder.restoreCallingIdentity(callingId);
13718        }
13719        return false;
13720    }
13721
13722    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13723            int userId) {
13724        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13725        info.removedPackage = packageName;
13726        info.installerPackageName = pkgSetting.installerPackageName;
13727        info.removedUsers = new int[] {userId};
13728        info.broadcastUsers = new int[] {userId};
13729        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13730        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13731    }
13732
13733    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13734        if (pkgList.length > 0) {
13735            Bundle extras = new Bundle(1);
13736            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13737
13738            sendPackageBroadcast(
13739                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13740                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13741                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13742                    new int[] {userId}, null);
13743        }
13744    }
13745
13746    /**
13747     * Returns true if application is not found or there was an error. Otherwise it returns
13748     * the hidden state of the package for the given user.
13749     */
13750    @Override
13751    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13752        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13753        final int callingUid = Binder.getCallingUid();
13754        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13755                true /* requireFullPermission */, false /* checkShell */,
13756                "getApplicationHidden for user " + userId);
13757        PackageSetting ps;
13758        long callingId = Binder.clearCallingIdentity();
13759        try {
13760            // writer
13761            synchronized (mPackages) {
13762                ps = mSettings.mPackages.get(packageName);
13763                if (ps == null) {
13764                    return true;
13765                }
13766                if (filterAppAccessLPr(ps, callingUid, userId)) {
13767                    return true;
13768                }
13769                return ps.getHidden(userId);
13770            }
13771        } finally {
13772            Binder.restoreCallingIdentity(callingId);
13773        }
13774    }
13775
13776    /**
13777     * @hide
13778     */
13779    @Override
13780    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13781            int installReason) {
13782        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13783                null);
13784        PackageSetting pkgSetting;
13785        final int callingUid = Binder.getCallingUid();
13786        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13787                true /* requireFullPermission */, true /* checkShell */,
13788                "installExistingPackage for user " + userId);
13789        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13790            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13791        }
13792
13793        long callingId = Binder.clearCallingIdentity();
13794        try {
13795            boolean installed = false;
13796            final boolean instantApp =
13797                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13798            final boolean fullApp =
13799                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13800
13801            // writer
13802            synchronized (mPackages) {
13803                pkgSetting = mSettings.mPackages.get(packageName);
13804                if (pkgSetting == null) {
13805                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13806                }
13807                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13808                    // only allow the existing package to be used if it's installed as a full
13809                    // application for at least one user
13810                    boolean installAllowed = false;
13811                    for (int checkUserId : sUserManager.getUserIds()) {
13812                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13813                        if (installAllowed) {
13814                            break;
13815                        }
13816                    }
13817                    if (!installAllowed) {
13818                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13819                    }
13820                }
13821                if (!pkgSetting.getInstalled(userId)) {
13822                    pkgSetting.setInstalled(true, userId);
13823                    pkgSetting.setHidden(false, userId);
13824                    pkgSetting.setInstallReason(installReason, userId);
13825                    mSettings.writePackageRestrictionsLPr(userId);
13826                    mSettings.writeKernelMappingLPr(pkgSetting);
13827                    installed = true;
13828                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13829                    // upgrade app from instant to full; we don't allow app downgrade
13830                    installed = true;
13831                }
13832                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13833            }
13834
13835            if (installed) {
13836                if (pkgSetting.pkg != null) {
13837                    synchronized (mInstallLock) {
13838                        // We don't need to freeze for a brand new install
13839                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13840                    }
13841                }
13842                sendPackageAddedForUser(packageName, pkgSetting, userId);
13843                synchronized (mPackages) {
13844                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13845                }
13846            }
13847        } finally {
13848            Binder.restoreCallingIdentity(callingId);
13849        }
13850
13851        return PackageManager.INSTALL_SUCCEEDED;
13852    }
13853
13854    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13855            boolean instantApp, boolean fullApp) {
13856        // no state specified; do nothing
13857        if (!instantApp && !fullApp) {
13858            return;
13859        }
13860        if (userId != UserHandle.USER_ALL) {
13861            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13862                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13863            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13864                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13865            }
13866        } else {
13867            for (int currentUserId : sUserManager.getUserIds()) {
13868                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13869                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13870                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13871                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13872                }
13873            }
13874        }
13875    }
13876
13877    boolean isUserRestricted(int userId, String restrictionKey) {
13878        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13879        if (restrictions.getBoolean(restrictionKey, false)) {
13880            Log.w(TAG, "User is restricted: " + restrictionKey);
13881            return true;
13882        }
13883        return false;
13884    }
13885
13886    @Override
13887    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13888            int userId) {
13889        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13890        final int callingUid = Binder.getCallingUid();
13891        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13892                true /* requireFullPermission */, true /* checkShell */,
13893                "setPackagesSuspended for user " + userId);
13894
13895        if (ArrayUtils.isEmpty(packageNames)) {
13896            return packageNames;
13897        }
13898
13899        // List of package names for whom the suspended state has changed.
13900        List<String> changedPackages = new ArrayList<>(packageNames.length);
13901        // List of package names for whom the suspended state is not set as requested in this
13902        // method.
13903        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13904        long callingId = Binder.clearCallingIdentity();
13905        try {
13906            for (int i = 0; i < packageNames.length; i++) {
13907                String packageName = packageNames[i];
13908                boolean changed = false;
13909                final int appId;
13910                synchronized (mPackages) {
13911                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13912                    if (pkgSetting == null
13913                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13914                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13915                                + "\". Skipping suspending/un-suspending.");
13916                        unactionedPackages.add(packageName);
13917                        continue;
13918                    }
13919                    appId = pkgSetting.appId;
13920                    if (pkgSetting.getSuspended(userId) != suspended) {
13921                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13922                            unactionedPackages.add(packageName);
13923                            continue;
13924                        }
13925                        pkgSetting.setSuspended(suspended, userId);
13926                        mSettings.writePackageRestrictionsLPr(userId);
13927                        changed = true;
13928                        changedPackages.add(packageName);
13929                    }
13930                }
13931
13932                if (changed && suspended) {
13933                    killApplication(packageName, UserHandle.getUid(userId, appId),
13934                            "suspending package");
13935                }
13936            }
13937        } finally {
13938            Binder.restoreCallingIdentity(callingId);
13939        }
13940
13941        if (!changedPackages.isEmpty()) {
13942            sendPackagesSuspendedForUser(changedPackages.toArray(
13943                    new String[changedPackages.size()]), userId, suspended);
13944        }
13945
13946        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13947    }
13948
13949    @Override
13950    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13951        final int callingUid = Binder.getCallingUid();
13952        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13953                true /* requireFullPermission */, false /* checkShell */,
13954                "isPackageSuspendedForUser for user " + userId);
13955        synchronized (mPackages) {
13956            final PackageSetting ps = mSettings.mPackages.get(packageName);
13957            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
13958                throw new IllegalArgumentException("Unknown target package: " + packageName);
13959            }
13960            return ps.getSuspended(userId);
13961        }
13962    }
13963
13964    @GuardedBy("mPackages")
13965    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13966        if (isPackageDeviceAdmin(packageName, userId)) {
13967            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13968                    + "\": has an active device admin");
13969            return false;
13970        }
13971
13972        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13973        if (packageName.equals(activeLauncherPackageName)) {
13974            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13975                    + "\": contains the active launcher");
13976            return false;
13977        }
13978
13979        if (packageName.equals(mRequiredInstallerPackage)) {
13980            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13981                    + "\": required for package installation");
13982            return false;
13983        }
13984
13985        if (packageName.equals(mRequiredUninstallerPackage)) {
13986            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13987                    + "\": required for package uninstallation");
13988            return false;
13989        }
13990
13991        if (packageName.equals(mRequiredVerifierPackage)) {
13992            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13993                    + "\": required for package verification");
13994            return false;
13995        }
13996
13997        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13998            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13999                    + "\": is the default dialer");
14000            return false;
14001        }
14002
14003        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14004            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14005                    + "\": protected package");
14006            return false;
14007        }
14008
14009        // Cannot suspend static shared libs as they are considered
14010        // a part of the using app (emulating static linking). Also
14011        // static libs are installed always on internal storage.
14012        PackageParser.Package pkg = mPackages.get(packageName);
14013        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14014            Slog.w(TAG, "Cannot suspend package: " + packageName
14015                    + " providing static shared library: "
14016                    + pkg.staticSharedLibName);
14017            return false;
14018        }
14019
14020        return true;
14021    }
14022
14023    private String getActiveLauncherPackageName(int userId) {
14024        Intent intent = new Intent(Intent.ACTION_MAIN);
14025        intent.addCategory(Intent.CATEGORY_HOME);
14026        ResolveInfo resolveInfo = resolveIntent(
14027                intent,
14028                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14029                PackageManager.MATCH_DEFAULT_ONLY,
14030                userId);
14031
14032        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14033    }
14034
14035    private String getDefaultDialerPackageName(int userId) {
14036        synchronized (mPackages) {
14037            return mSettings.getDefaultDialerPackageNameLPw(userId);
14038        }
14039    }
14040
14041    @Override
14042    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14043        mContext.enforceCallingOrSelfPermission(
14044                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14045                "Only package verification agents can verify applications");
14046
14047        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14048        final PackageVerificationResponse response = new PackageVerificationResponse(
14049                verificationCode, Binder.getCallingUid());
14050        msg.arg1 = id;
14051        msg.obj = response;
14052        mHandler.sendMessage(msg);
14053    }
14054
14055    @Override
14056    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14057            long millisecondsToDelay) {
14058        mContext.enforceCallingOrSelfPermission(
14059                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14060                "Only package verification agents can extend verification timeouts");
14061
14062        final PackageVerificationState state = mPendingVerification.get(id);
14063        final PackageVerificationResponse response = new PackageVerificationResponse(
14064                verificationCodeAtTimeout, Binder.getCallingUid());
14065
14066        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14067            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14068        }
14069        if (millisecondsToDelay < 0) {
14070            millisecondsToDelay = 0;
14071        }
14072        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14073                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14074            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14075        }
14076
14077        if ((state != null) && !state.timeoutExtended()) {
14078            state.extendTimeout();
14079
14080            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14081            msg.arg1 = id;
14082            msg.obj = response;
14083            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14084        }
14085    }
14086
14087    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14088            int verificationCode, UserHandle user) {
14089        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14090        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14091        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14092        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14093        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14094
14095        mContext.sendBroadcastAsUser(intent, user,
14096                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14097    }
14098
14099    private ComponentName matchComponentForVerifier(String packageName,
14100            List<ResolveInfo> receivers) {
14101        ActivityInfo targetReceiver = null;
14102
14103        final int NR = receivers.size();
14104        for (int i = 0; i < NR; i++) {
14105            final ResolveInfo info = receivers.get(i);
14106            if (info.activityInfo == null) {
14107                continue;
14108            }
14109
14110            if (packageName.equals(info.activityInfo.packageName)) {
14111                targetReceiver = info.activityInfo;
14112                break;
14113            }
14114        }
14115
14116        if (targetReceiver == null) {
14117            return null;
14118        }
14119
14120        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14121    }
14122
14123    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14124            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14125        if (pkgInfo.verifiers.length == 0) {
14126            return null;
14127        }
14128
14129        final int N = pkgInfo.verifiers.length;
14130        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14131        for (int i = 0; i < N; i++) {
14132            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14133
14134            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14135                    receivers);
14136            if (comp == null) {
14137                continue;
14138            }
14139
14140            final int verifierUid = getUidForVerifier(verifierInfo);
14141            if (verifierUid == -1) {
14142                continue;
14143            }
14144
14145            if (DEBUG_VERIFY) {
14146                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14147                        + " with the correct signature");
14148            }
14149            sufficientVerifiers.add(comp);
14150            verificationState.addSufficientVerifier(verifierUid);
14151        }
14152
14153        return sufficientVerifiers;
14154    }
14155
14156    private int getUidForVerifier(VerifierInfo verifierInfo) {
14157        synchronized (mPackages) {
14158            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14159            if (pkg == null) {
14160                return -1;
14161            } else if (pkg.mSigningDetails.signatures.length != 1) {
14162                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14163                        + " has more than one signature; ignoring");
14164                return -1;
14165            }
14166
14167            /*
14168             * If the public key of the package's signature does not match
14169             * our expected public key, then this is a different package and
14170             * we should skip.
14171             */
14172
14173            final byte[] expectedPublicKey;
14174            try {
14175                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14176                final PublicKey publicKey = verifierSig.getPublicKey();
14177                expectedPublicKey = publicKey.getEncoded();
14178            } catch (CertificateException e) {
14179                return -1;
14180            }
14181
14182            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14183
14184            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14185                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14186                        + " does not have the expected public key; ignoring");
14187                return -1;
14188            }
14189
14190            return pkg.applicationInfo.uid;
14191        }
14192    }
14193
14194    @Override
14195    public void finishPackageInstall(int token, boolean didLaunch) {
14196        enforceSystemOrRoot("Only the system is allowed to finish installs");
14197
14198        if (DEBUG_INSTALL) {
14199            Slog.v(TAG, "BM finishing package install for " + token);
14200        }
14201        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14202
14203        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14204        mHandler.sendMessage(msg);
14205    }
14206
14207    /**
14208     * Get the verification agent timeout.  Used for both the APK verifier and the
14209     * intent filter verifier.
14210     *
14211     * @return verification timeout in milliseconds
14212     */
14213    private long getVerificationTimeout() {
14214        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14215                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14216                DEFAULT_VERIFICATION_TIMEOUT);
14217    }
14218
14219    /**
14220     * Get the default verification agent response code.
14221     *
14222     * @return default verification response code
14223     */
14224    private int getDefaultVerificationResponse(UserHandle user) {
14225        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14226            return PackageManager.VERIFICATION_REJECT;
14227        }
14228        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14229                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14230                DEFAULT_VERIFICATION_RESPONSE);
14231    }
14232
14233    /**
14234     * Check whether or not package verification has been enabled.
14235     *
14236     * @return true if verification should be performed
14237     */
14238    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14239        if (!DEFAULT_VERIFY_ENABLE) {
14240            return false;
14241        }
14242
14243        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14244
14245        // Check if installing from ADB
14246        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14247            // Do not run verification in a test harness environment
14248            if (ActivityManager.isRunningInTestHarness()) {
14249                return false;
14250            }
14251            if (ensureVerifyAppsEnabled) {
14252                return true;
14253            }
14254            // Check if the developer does not want package verification for ADB installs
14255            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14256                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14257                return false;
14258            }
14259        } else {
14260            // only when not installed from ADB, skip verification for instant apps when
14261            // the installer and verifier are the same.
14262            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14263                if (mInstantAppInstallerActivity != null
14264                        && mInstantAppInstallerActivity.packageName.equals(
14265                                mRequiredVerifierPackage)) {
14266                    try {
14267                        mContext.getSystemService(AppOpsManager.class)
14268                                .checkPackage(installerUid, mRequiredVerifierPackage);
14269                        if (DEBUG_VERIFY) {
14270                            Slog.i(TAG, "disable verification for instant app");
14271                        }
14272                        return false;
14273                    } catch (SecurityException ignore) { }
14274                }
14275            }
14276        }
14277
14278        if (ensureVerifyAppsEnabled) {
14279            return true;
14280        }
14281
14282        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14283                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14284    }
14285
14286    @Override
14287    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14288            throws RemoteException {
14289        mContext.enforceCallingOrSelfPermission(
14290                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14291                "Only intentfilter verification agents can verify applications");
14292
14293        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14294        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14295                Binder.getCallingUid(), verificationCode, failedDomains);
14296        msg.arg1 = id;
14297        msg.obj = response;
14298        mHandler.sendMessage(msg);
14299    }
14300
14301    @Override
14302    public int getIntentVerificationStatus(String packageName, int userId) {
14303        final int callingUid = Binder.getCallingUid();
14304        if (UserHandle.getUserId(callingUid) != userId) {
14305            mContext.enforceCallingOrSelfPermission(
14306                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14307                    "getIntentVerificationStatus" + userId);
14308        }
14309        if (getInstantAppPackageName(callingUid) != null) {
14310            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14311        }
14312        synchronized (mPackages) {
14313            final PackageSetting ps = mSettings.mPackages.get(packageName);
14314            if (ps == null
14315                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14316                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14317            }
14318            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14319        }
14320    }
14321
14322    @Override
14323    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14324        mContext.enforceCallingOrSelfPermission(
14325                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14326
14327        boolean result = false;
14328        synchronized (mPackages) {
14329            final PackageSetting ps = mSettings.mPackages.get(packageName);
14330            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14331                return false;
14332            }
14333            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14334        }
14335        if (result) {
14336            scheduleWritePackageRestrictionsLocked(userId);
14337        }
14338        return result;
14339    }
14340
14341    @Override
14342    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14343            String packageName) {
14344        final int callingUid = Binder.getCallingUid();
14345        if (getInstantAppPackageName(callingUid) != null) {
14346            return ParceledListSlice.emptyList();
14347        }
14348        synchronized (mPackages) {
14349            final PackageSetting ps = mSettings.mPackages.get(packageName);
14350            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14351                return ParceledListSlice.emptyList();
14352            }
14353            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14354        }
14355    }
14356
14357    @Override
14358    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14359        if (TextUtils.isEmpty(packageName)) {
14360            return ParceledListSlice.emptyList();
14361        }
14362        final int callingUid = Binder.getCallingUid();
14363        final int callingUserId = UserHandle.getUserId(callingUid);
14364        synchronized (mPackages) {
14365            PackageParser.Package pkg = mPackages.get(packageName);
14366            if (pkg == null || pkg.activities == null) {
14367                return ParceledListSlice.emptyList();
14368            }
14369            if (pkg.mExtras == null) {
14370                return ParceledListSlice.emptyList();
14371            }
14372            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14373            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14374                return ParceledListSlice.emptyList();
14375            }
14376            final int count = pkg.activities.size();
14377            ArrayList<IntentFilter> result = new ArrayList<>();
14378            for (int n=0; n<count; n++) {
14379                PackageParser.Activity activity = pkg.activities.get(n);
14380                if (activity.intents != null && activity.intents.size() > 0) {
14381                    result.addAll(activity.intents);
14382                }
14383            }
14384            return new ParceledListSlice<>(result);
14385        }
14386    }
14387
14388    @Override
14389    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14390        mContext.enforceCallingOrSelfPermission(
14391                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14392        if (UserHandle.getCallingUserId() != userId) {
14393            mContext.enforceCallingOrSelfPermission(
14394                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14395        }
14396
14397        synchronized (mPackages) {
14398            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14399            if (packageName != null) {
14400                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14401                        packageName, userId);
14402            }
14403            return result;
14404        }
14405    }
14406
14407    @Override
14408    public String getDefaultBrowserPackageName(int userId) {
14409        if (UserHandle.getCallingUserId() != userId) {
14410            mContext.enforceCallingOrSelfPermission(
14411                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14412        }
14413        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14414            return null;
14415        }
14416        synchronized (mPackages) {
14417            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14418        }
14419    }
14420
14421    /**
14422     * Get the "allow unknown sources" setting.
14423     *
14424     * @return the current "allow unknown sources" setting
14425     */
14426    private int getUnknownSourcesSettings() {
14427        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14428                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14429                -1);
14430    }
14431
14432    @Override
14433    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14434        final int callingUid = Binder.getCallingUid();
14435        if (getInstantAppPackageName(callingUid) != null) {
14436            return;
14437        }
14438        // writer
14439        synchronized (mPackages) {
14440            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14441            if (targetPackageSetting == null
14442                    || filterAppAccessLPr(
14443                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14444                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14445            }
14446
14447            PackageSetting installerPackageSetting;
14448            if (installerPackageName != null) {
14449                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14450                if (installerPackageSetting == null) {
14451                    throw new IllegalArgumentException("Unknown installer package: "
14452                            + installerPackageName);
14453                }
14454            } else {
14455                installerPackageSetting = null;
14456            }
14457
14458            Signature[] callerSignature;
14459            Object obj = mSettings.getUserIdLPr(callingUid);
14460            if (obj != null) {
14461                if (obj instanceof SharedUserSetting) {
14462                    callerSignature =
14463                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14464                } else if (obj instanceof PackageSetting) {
14465                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14466                } else {
14467                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14468                }
14469            } else {
14470                throw new SecurityException("Unknown calling UID: " + callingUid);
14471            }
14472
14473            // Verify: can't set installerPackageName to a package that is
14474            // not signed with the same cert as the caller.
14475            if (installerPackageSetting != null) {
14476                if (compareSignatures(callerSignature,
14477                        installerPackageSetting.signatures.mSigningDetails.signatures)
14478                        != PackageManager.SIGNATURE_MATCH) {
14479                    throw new SecurityException(
14480                            "Caller does not have same cert as new installer package "
14481                            + installerPackageName);
14482                }
14483            }
14484
14485            // Verify: if target already has an installer package, it must
14486            // be signed with the same cert as the caller.
14487            if (targetPackageSetting.installerPackageName != null) {
14488                PackageSetting setting = mSettings.mPackages.get(
14489                        targetPackageSetting.installerPackageName);
14490                // If the currently set package isn't valid, then it's always
14491                // okay to change it.
14492                if (setting != null) {
14493                    if (compareSignatures(callerSignature,
14494                            setting.signatures.mSigningDetails.signatures)
14495                            != PackageManager.SIGNATURE_MATCH) {
14496                        throw new SecurityException(
14497                                "Caller does not have same cert as old installer package "
14498                                + targetPackageSetting.installerPackageName);
14499                    }
14500                }
14501            }
14502
14503            // Okay!
14504            targetPackageSetting.installerPackageName = installerPackageName;
14505            if (installerPackageName != null) {
14506                mSettings.mInstallerPackages.add(installerPackageName);
14507            }
14508            scheduleWriteSettingsLocked();
14509        }
14510    }
14511
14512    @Override
14513    public void setApplicationCategoryHint(String packageName, int categoryHint,
14514            String callerPackageName) {
14515        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14516            throw new SecurityException("Instant applications don't have access to this method");
14517        }
14518        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14519                callerPackageName);
14520        synchronized (mPackages) {
14521            PackageSetting ps = mSettings.mPackages.get(packageName);
14522            if (ps == null) {
14523                throw new IllegalArgumentException("Unknown target package " + packageName);
14524            }
14525            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14526                throw new IllegalArgumentException("Unknown target package " + packageName);
14527            }
14528            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14529                throw new IllegalArgumentException("Calling package " + callerPackageName
14530                        + " is not installer for " + packageName);
14531            }
14532
14533            if (ps.categoryHint != categoryHint) {
14534                ps.categoryHint = categoryHint;
14535                scheduleWriteSettingsLocked();
14536            }
14537        }
14538    }
14539
14540    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14541        // Queue up an async operation since the package installation may take a little while.
14542        mHandler.post(new Runnable() {
14543            public void run() {
14544                mHandler.removeCallbacks(this);
14545                 // Result object to be returned
14546                PackageInstalledInfo res = new PackageInstalledInfo();
14547                res.setReturnCode(currentStatus);
14548                res.uid = -1;
14549                res.pkg = null;
14550                res.removedInfo = null;
14551                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14552                    args.doPreInstall(res.returnCode);
14553                    synchronized (mInstallLock) {
14554                        installPackageTracedLI(args, res);
14555                    }
14556                    args.doPostInstall(res.returnCode, res.uid);
14557                }
14558
14559                // A restore should be performed at this point if (a) the install
14560                // succeeded, (b) the operation is not an update, and (c) the new
14561                // package has not opted out of backup participation.
14562                final boolean update = res.removedInfo != null
14563                        && res.removedInfo.removedPackage != null;
14564                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14565                boolean doRestore = !update
14566                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14567
14568                // Set up the post-install work request bookkeeping.  This will be used
14569                // and cleaned up by the post-install event handling regardless of whether
14570                // there's a restore pass performed.  Token values are >= 1.
14571                int token;
14572                if (mNextInstallToken < 0) mNextInstallToken = 1;
14573                token = mNextInstallToken++;
14574
14575                PostInstallData data = new PostInstallData(args, res);
14576                mRunningInstalls.put(token, data);
14577                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14578
14579                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14580                    // Pass responsibility to the Backup Manager.  It will perform a
14581                    // restore if appropriate, then pass responsibility back to the
14582                    // Package Manager to run the post-install observer callbacks
14583                    // and broadcasts.
14584                    IBackupManager bm = IBackupManager.Stub.asInterface(
14585                            ServiceManager.getService(Context.BACKUP_SERVICE));
14586                    if (bm != null) {
14587                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14588                                + " to BM for possible restore");
14589                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14590                        try {
14591                            // TODO: http://b/22388012
14592                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14593                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14594                            } else {
14595                                doRestore = false;
14596                            }
14597                        } catch (RemoteException e) {
14598                            // can't happen; the backup manager is local
14599                        } catch (Exception e) {
14600                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14601                            doRestore = false;
14602                        }
14603                    } else {
14604                        Slog.e(TAG, "Backup Manager not found!");
14605                        doRestore = false;
14606                    }
14607                }
14608
14609                if (!doRestore) {
14610                    // No restore possible, or the Backup Manager was mysteriously not
14611                    // available -- just fire the post-install work request directly.
14612                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14613
14614                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14615
14616                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14617                    mHandler.sendMessage(msg);
14618                }
14619            }
14620        });
14621    }
14622
14623    /**
14624     * Callback from PackageSettings whenever an app is first transitioned out of the
14625     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14626     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14627     * here whether the app is the target of an ongoing install, and only send the
14628     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14629     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14630     * handling.
14631     */
14632    void notifyFirstLaunch(final String packageName, final String installerPackage,
14633            final int userId) {
14634        // Serialize this with the rest of the install-process message chain.  In the
14635        // restore-at-install case, this Runnable will necessarily run before the
14636        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14637        // are coherent.  In the non-restore case, the app has already completed install
14638        // and been launched through some other means, so it is not in a problematic
14639        // state for observers to see the FIRST_LAUNCH signal.
14640        mHandler.post(new Runnable() {
14641            @Override
14642            public void run() {
14643                for (int i = 0; i < mRunningInstalls.size(); i++) {
14644                    final PostInstallData data = mRunningInstalls.valueAt(i);
14645                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14646                        continue;
14647                    }
14648                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14649                        // right package; but is it for the right user?
14650                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14651                            if (userId == data.res.newUsers[uIndex]) {
14652                                if (DEBUG_BACKUP) {
14653                                    Slog.i(TAG, "Package " + packageName
14654                                            + " being restored so deferring FIRST_LAUNCH");
14655                                }
14656                                return;
14657                            }
14658                        }
14659                    }
14660                }
14661                // didn't find it, so not being restored
14662                if (DEBUG_BACKUP) {
14663                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14664                }
14665                final boolean isInstantApp = isInstantApp(packageName, userId);
14666                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14667                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14668                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14669            }
14670        });
14671    }
14672
14673    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14674            int[] userIds, int[] instantUserIds) {
14675        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14676                installerPkg, null, userIds, instantUserIds);
14677    }
14678
14679    private abstract class HandlerParams {
14680        private static final int MAX_RETRIES = 4;
14681
14682        /**
14683         * Number of times startCopy() has been attempted and had a non-fatal
14684         * error.
14685         */
14686        private int mRetries = 0;
14687
14688        /** User handle for the user requesting the information or installation. */
14689        private final UserHandle mUser;
14690        String traceMethod;
14691        int traceCookie;
14692
14693        HandlerParams(UserHandle user) {
14694            mUser = user;
14695        }
14696
14697        UserHandle getUser() {
14698            return mUser;
14699        }
14700
14701        HandlerParams setTraceMethod(String traceMethod) {
14702            this.traceMethod = traceMethod;
14703            return this;
14704        }
14705
14706        HandlerParams setTraceCookie(int traceCookie) {
14707            this.traceCookie = traceCookie;
14708            return this;
14709        }
14710
14711        final boolean startCopy() {
14712            boolean res;
14713            try {
14714                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14715
14716                if (++mRetries > MAX_RETRIES) {
14717                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14718                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14719                    handleServiceError();
14720                    return false;
14721                } else {
14722                    handleStartCopy();
14723                    res = true;
14724                }
14725            } catch (RemoteException e) {
14726                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14727                mHandler.sendEmptyMessage(MCS_RECONNECT);
14728                res = false;
14729            }
14730            handleReturnCode();
14731            return res;
14732        }
14733
14734        final void serviceError() {
14735            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14736            handleServiceError();
14737            handleReturnCode();
14738        }
14739
14740        abstract void handleStartCopy() throws RemoteException;
14741        abstract void handleServiceError();
14742        abstract void handleReturnCode();
14743    }
14744
14745    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14746        for (File path : paths) {
14747            try {
14748                mcs.clearDirectory(path.getAbsolutePath());
14749            } catch (RemoteException e) {
14750            }
14751        }
14752    }
14753
14754    static class OriginInfo {
14755        /**
14756         * Location where install is coming from, before it has been
14757         * copied/renamed into place. This could be a single monolithic APK
14758         * file, or a cluster directory. This location may be untrusted.
14759         */
14760        final File file;
14761
14762        /**
14763         * Flag indicating that {@link #file} or {@link #cid} has already been
14764         * staged, meaning downstream users don't need to defensively copy the
14765         * contents.
14766         */
14767        final boolean staged;
14768
14769        /**
14770         * Flag indicating that {@link #file} or {@link #cid} is an already
14771         * installed app that is being moved.
14772         */
14773        final boolean existing;
14774
14775        final String resolvedPath;
14776        final File resolvedFile;
14777
14778        static OriginInfo fromNothing() {
14779            return new OriginInfo(null, false, false);
14780        }
14781
14782        static OriginInfo fromUntrustedFile(File file) {
14783            return new OriginInfo(file, false, false);
14784        }
14785
14786        static OriginInfo fromExistingFile(File file) {
14787            return new OriginInfo(file, false, true);
14788        }
14789
14790        static OriginInfo fromStagedFile(File file) {
14791            return new OriginInfo(file, true, false);
14792        }
14793
14794        private OriginInfo(File file, boolean staged, boolean existing) {
14795            this.file = file;
14796            this.staged = staged;
14797            this.existing = existing;
14798
14799            if (file != null) {
14800                resolvedPath = file.getAbsolutePath();
14801                resolvedFile = file;
14802            } else {
14803                resolvedPath = null;
14804                resolvedFile = null;
14805            }
14806        }
14807    }
14808
14809    static class MoveInfo {
14810        final int moveId;
14811        final String fromUuid;
14812        final String toUuid;
14813        final String packageName;
14814        final String dataAppName;
14815        final int appId;
14816        final String seinfo;
14817        final int targetSdkVersion;
14818
14819        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14820                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14821            this.moveId = moveId;
14822            this.fromUuid = fromUuid;
14823            this.toUuid = toUuid;
14824            this.packageName = packageName;
14825            this.dataAppName = dataAppName;
14826            this.appId = appId;
14827            this.seinfo = seinfo;
14828            this.targetSdkVersion = targetSdkVersion;
14829        }
14830    }
14831
14832    static class VerificationInfo {
14833        /** A constant used to indicate that a uid value is not present. */
14834        public static final int NO_UID = -1;
14835
14836        /** URI referencing where the package was downloaded from. */
14837        final Uri originatingUri;
14838
14839        /** HTTP referrer URI associated with the originatingURI. */
14840        final Uri referrer;
14841
14842        /** UID of the application that the install request originated from. */
14843        final int originatingUid;
14844
14845        /** UID of application requesting the install */
14846        final int installerUid;
14847
14848        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14849            this.originatingUri = originatingUri;
14850            this.referrer = referrer;
14851            this.originatingUid = originatingUid;
14852            this.installerUid = installerUid;
14853        }
14854    }
14855
14856    class InstallParams extends HandlerParams {
14857        final OriginInfo origin;
14858        final MoveInfo move;
14859        final IPackageInstallObserver2 observer;
14860        int installFlags;
14861        final String installerPackageName;
14862        final String volumeUuid;
14863        private InstallArgs mArgs;
14864        private int mRet;
14865        final String packageAbiOverride;
14866        final String[] grantedRuntimePermissions;
14867        final VerificationInfo verificationInfo;
14868        final PackageParser.SigningDetails signingDetails;
14869        final int installReason;
14870
14871        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14872                int installFlags, String installerPackageName, String volumeUuid,
14873                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14874                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
14875            super(user);
14876            this.origin = origin;
14877            this.move = move;
14878            this.observer = observer;
14879            this.installFlags = installFlags;
14880            this.installerPackageName = installerPackageName;
14881            this.volumeUuid = volumeUuid;
14882            this.verificationInfo = verificationInfo;
14883            this.packageAbiOverride = packageAbiOverride;
14884            this.grantedRuntimePermissions = grantedPermissions;
14885            this.signingDetails = signingDetails;
14886            this.installReason = installReason;
14887        }
14888
14889        @Override
14890        public String toString() {
14891            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14892                    + " file=" + origin.file + "}";
14893        }
14894
14895        private int installLocationPolicy(PackageInfoLite pkgLite) {
14896            String packageName = pkgLite.packageName;
14897            int installLocation = pkgLite.installLocation;
14898            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14899            // reader
14900            synchronized (mPackages) {
14901                // Currently installed package which the new package is attempting to replace or
14902                // null if no such package is installed.
14903                PackageParser.Package installedPkg = mPackages.get(packageName);
14904                // Package which currently owns the data which the new package will own if installed.
14905                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14906                // will be null whereas dataOwnerPkg will contain information about the package
14907                // which was uninstalled while keeping its data.
14908                PackageParser.Package dataOwnerPkg = installedPkg;
14909                if (dataOwnerPkg  == null) {
14910                    PackageSetting ps = mSettings.mPackages.get(packageName);
14911                    if (ps != null) {
14912                        dataOwnerPkg = ps.pkg;
14913                    }
14914                }
14915
14916                if (dataOwnerPkg != null) {
14917                    // If installed, the package will get access to data left on the device by its
14918                    // predecessor. As a security measure, this is permited only if this is not a
14919                    // version downgrade or if the predecessor package is marked as debuggable and
14920                    // a downgrade is explicitly requested.
14921                    //
14922                    // On debuggable platform builds, downgrades are permitted even for
14923                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14924                    // not offer security guarantees and thus it's OK to disable some security
14925                    // mechanisms to make debugging/testing easier on those builds. However, even on
14926                    // debuggable builds downgrades of packages are permitted only if requested via
14927                    // installFlags. This is because we aim to keep the behavior of debuggable
14928                    // platform builds as close as possible to the behavior of non-debuggable
14929                    // platform builds.
14930                    final boolean downgradeRequested =
14931                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14932                    final boolean packageDebuggable =
14933                                (dataOwnerPkg.applicationInfo.flags
14934                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14935                    final boolean downgradePermitted =
14936                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14937                    if (!downgradePermitted) {
14938                        try {
14939                            checkDowngrade(dataOwnerPkg, pkgLite);
14940                        } catch (PackageManagerException e) {
14941                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14942                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14943                        }
14944                    }
14945                }
14946
14947                if (installedPkg != null) {
14948                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14949                        // Check for updated system application.
14950                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14951                            if (onSd) {
14952                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14953                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14954                            }
14955                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14956                        } else {
14957                            if (onSd) {
14958                                // Install flag overrides everything.
14959                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14960                            }
14961                            // If current upgrade specifies particular preference
14962                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14963                                // Application explicitly specified internal.
14964                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14965                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14966                                // App explictly prefers external. Let policy decide
14967                            } else {
14968                                // Prefer previous location
14969                                if (isExternal(installedPkg)) {
14970                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14971                                }
14972                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14973                            }
14974                        }
14975                    } else {
14976                        // Invalid install. Return error code
14977                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14978                    }
14979                }
14980            }
14981            // All the special cases have been taken care of.
14982            // Return result based on recommended install location.
14983            if (onSd) {
14984                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14985            }
14986            return pkgLite.recommendedInstallLocation;
14987        }
14988
14989        /*
14990         * Invoke remote method to get package information and install
14991         * location values. Override install location based on default
14992         * policy if needed and then create install arguments based
14993         * on the install location.
14994         */
14995        public void handleStartCopy() throws RemoteException {
14996            int ret = PackageManager.INSTALL_SUCCEEDED;
14997
14998            // If we're already staged, we've firmly committed to an install location
14999            if (origin.staged) {
15000                if (origin.file != null) {
15001                    installFlags |= PackageManager.INSTALL_INTERNAL;
15002                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15003                } else {
15004                    throw new IllegalStateException("Invalid stage location");
15005                }
15006            }
15007
15008            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15009            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15010            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15011            PackageInfoLite pkgLite = null;
15012
15013            if (onInt && onSd) {
15014                // Check if both bits are set.
15015                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15016                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15017            } else if (onSd && ephemeral) {
15018                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15019                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15020            } else {
15021                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15022                        packageAbiOverride);
15023
15024                if (DEBUG_INSTANT && ephemeral) {
15025                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15026                }
15027
15028                /*
15029                 * If we have too little free space, try to free cache
15030                 * before giving up.
15031                 */
15032                if (!origin.staged && pkgLite.recommendedInstallLocation
15033                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15034                    // TODO: focus freeing disk space on the target device
15035                    final StorageManager storage = StorageManager.from(mContext);
15036                    final long lowThreshold = storage.getStorageLowBytes(
15037                            Environment.getDataDirectory());
15038
15039                    final long sizeBytes = mContainerService.calculateInstalledSize(
15040                            origin.resolvedPath, packageAbiOverride);
15041
15042                    try {
15043                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15044                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15045                                installFlags, packageAbiOverride);
15046                    } catch (InstallerException e) {
15047                        Slog.w(TAG, "Failed to free cache", e);
15048                    }
15049
15050                    /*
15051                     * The cache free must have deleted the file we
15052                     * downloaded to install.
15053                     *
15054                     * TODO: fix the "freeCache" call to not delete
15055                     *       the file we care about.
15056                     */
15057                    if (pkgLite.recommendedInstallLocation
15058                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15059                        pkgLite.recommendedInstallLocation
15060                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15061                    }
15062                }
15063            }
15064
15065            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15066                int loc = pkgLite.recommendedInstallLocation;
15067                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15068                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15069                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15070                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15071                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15072                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15073                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15074                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15075                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15076                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15077                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15078                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15079                } else {
15080                    // Override with defaults if needed.
15081                    loc = installLocationPolicy(pkgLite);
15082                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15083                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15084                    } else if (!onSd && !onInt) {
15085                        // Override install location with flags
15086                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15087                            // Set the flag to install on external media.
15088                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15089                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15090                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15091                            if (DEBUG_INSTANT) {
15092                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15093                            }
15094                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15095                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15096                                    |PackageManager.INSTALL_INTERNAL);
15097                        } else {
15098                            // Make sure the flag for installing on external
15099                            // media is unset
15100                            installFlags |= PackageManager.INSTALL_INTERNAL;
15101                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15102                        }
15103                    }
15104                }
15105            }
15106
15107            final InstallArgs args = createInstallArgs(this);
15108            mArgs = args;
15109
15110            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15111                // TODO: http://b/22976637
15112                // Apps installed for "all" users use the device owner to verify the app
15113                UserHandle verifierUser = getUser();
15114                if (verifierUser == UserHandle.ALL) {
15115                    verifierUser = UserHandle.SYSTEM;
15116                }
15117
15118                /*
15119                 * Determine if we have any installed package verifiers. If we
15120                 * do, then we'll defer to them to verify the packages.
15121                 */
15122                final int requiredUid = mRequiredVerifierPackage == null ? -1
15123                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15124                                verifierUser.getIdentifier());
15125                final int installerUid =
15126                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15127                if (!origin.existing && requiredUid != -1
15128                        && isVerificationEnabled(
15129                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15130                    final Intent verification = new Intent(
15131                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15132                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15133                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15134                            PACKAGE_MIME_TYPE);
15135                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15136
15137                    // Query all live verifiers based on current user state
15138                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15139                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15140                            false /*allowDynamicSplits*/);
15141
15142                    if (DEBUG_VERIFY) {
15143                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15144                                + verification.toString() + " with " + pkgLite.verifiers.length
15145                                + " optional verifiers");
15146                    }
15147
15148                    final int verificationId = mPendingVerificationToken++;
15149
15150                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15151
15152                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15153                            installerPackageName);
15154
15155                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15156                            installFlags);
15157
15158                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15159                            pkgLite.packageName);
15160
15161                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15162                            pkgLite.versionCode);
15163
15164                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15165                            pkgLite.getLongVersionCode());
15166
15167                    if (verificationInfo != null) {
15168                        if (verificationInfo.originatingUri != null) {
15169                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15170                                    verificationInfo.originatingUri);
15171                        }
15172                        if (verificationInfo.referrer != null) {
15173                            verification.putExtra(Intent.EXTRA_REFERRER,
15174                                    verificationInfo.referrer);
15175                        }
15176                        if (verificationInfo.originatingUid >= 0) {
15177                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15178                                    verificationInfo.originatingUid);
15179                        }
15180                        if (verificationInfo.installerUid >= 0) {
15181                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15182                                    verificationInfo.installerUid);
15183                        }
15184                    }
15185
15186                    final PackageVerificationState verificationState = new PackageVerificationState(
15187                            requiredUid, args);
15188
15189                    mPendingVerification.append(verificationId, verificationState);
15190
15191                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15192                            receivers, verificationState);
15193
15194                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15195                    final long idleDuration = getVerificationTimeout();
15196
15197                    /*
15198                     * If any sufficient verifiers were listed in the package
15199                     * manifest, attempt to ask them.
15200                     */
15201                    if (sufficientVerifiers != null) {
15202                        final int N = sufficientVerifiers.size();
15203                        if (N == 0) {
15204                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15205                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15206                        } else {
15207                            for (int i = 0; i < N; i++) {
15208                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15209                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15210                                        verifierComponent.getPackageName(), idleDuration,
15211                                        verifierUser.getIdentifier(), false, "package verifier");
15212
15213                                final Intent sufficientIntent = new Intent(verification);
15214                                sufficientIntent.setComponent(verifierComponent);
15215                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15216                            }
15217                        }
15218                    }
15219
15220                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15221                            mRequiredVerifierPackage, receivers);
15222                    if (ret == PackageManager.INSTALL_SUCCEEDED
15223                            && mRequiredVerifierPackage != null) {
15224                        Trace.asyncTraceBegin(
15225                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15226                        /*
15227                         * Send the intent to the required verification agent,
15228                         * but only start the verification timeout after the
15229                         * target BroadcastReceivers have run.
15230                         */
15231                        verification.setComponent(requiredVerifierComponent);
15232                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15233                                mRequiredVerifierPackage, idleDuration,
15234                                verifierUser.getIdentifier(), false, "package verifier");
15235                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15236                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15237                                new BroadcastReceiver() {
15238                                    @Override
15239                                    public void onReceive(Context context, Intent intent) {
15240                                        final Message msg = mHandler
15241                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15242                                        msg.arg1 = verificationId;
15243                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15244                                    }
15245                                }, null, 0, null, null);
15246
15247                        /*
15248                         * We don't want the copy to proceed until verification
15249                         * succeeds, so null out this field.
15250                         */
15251                        mArgs = null;
15252                    }
15253                } else {
15254                    /*
15255                     * No package verification is enabled, so immediately start
15256                     * the remote call to initiate copy using temporary file.
15257                     */
15258                    ret = args.copyApk(mContainerService, true);
15259                }
15260            }
15261
15262            mRet = ret;
15263        }
15264
15265        @Override
15266        void handleReturnCode() {
15267            // If mArgs is null, then MCS couldn't be reached. When it
15268            // reconnects, it will try again to install. At that point, this
15269            // will succeed.
15270            if (mArgs != null) {
15271                processPendingInstall(mArgs, mRet);
15272            }
15273        }
15274
15275        @Override
15276        void handleServiceError() {
15277            mArgs = createInstallArgs(this);
15278            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15279        }
15280    }
15281
15282    private InstallArgs createInstallArgs(InstallParams params) {
15283        if (params.move != null) {
15284            return new MoveInstallArgs(params);
15285        } else {
15286            return new FileInstallArgs(params);
15287        }
15288    }
15289
15290    /**
15291     * Create args that describe an existing installed package. Typically used
15292     * when cleaning up old installs, or used as a move source.
15293     */
15294    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15295            String resourcePath, String[] instructionSets) {
15296        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15297    }
15298
15299    static abstract class InstallArgs {
15300        /** @see InstallParams#origin */
15301        final OriginInfo origin;
15302        /** @see InstallParams#move */
15303        final MoveInfo move;
15304
15305        final IPackageInstallObserver2 observer;
15306        // Always refers to PackageManager flags only
15307        final int installFlags;
15308        final String installerPackageName;
15309        final String volumeUuid;
15310        final UserHandle user;
15311        final String abiOverride;
15312        final String[] installGrantPermissions;
15313        /** If non-null, drop an async trace when the install completes */
15314        final String traceMethod;
15315        final int traceCookie;
15316        final PackageParser.SigningDetails signingDetails;
15317        final int installReason;
15318
15319        // The list of instruction sets supported by this app. This is currently
15320        // only used during the rmdex() phase to clean up resources. We can get rid of this
15321        // if we move dex files under the common app path.
15322        /* nullable */ String[] instructionSets;
15323
15324        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15325                int installFlags, String installerPackageName, String volumeUuid,
15326                UserHandle user, String[] instructionSets,
15327                String abiOverride, String[] installGrantPermissions,
15328                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15329                int installReason) {
15330            this.origin = origin;
15331            this.move = move;
15332            this.installFlags = installFlags;
15333            this.observer = observer;
15334            this.installerPackageName = installerPackageName;
15335            this.volumeUuid = volumeUuid;
15336            this.user = user;
15337            this.instructionSets = instructionSets;
15338            this.abiOverride = abiOverride;
15339            this.installGrantPermissions = installGrantPermissions;
15340            this.traceMethod = traceMethod;
15341            this.traceCookie = traceCookie;
15342            this.signingDetails = signingDetails;
15343            this.installReason = installReason;
15344        }
15345
15346        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15347        abstract int doPreInstall(int status);
15348
15349        /**
15350         * Rename package into final resting place. All paths on the given
15351         * scanned package should be updated to reflect the rename.
15352         */
15353        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15354        abstract int doPostInstall(int status, int uid);
15355
15356        /** @see PackageSettingBase#codePathString */
15357        abstract String getCodePath();
15358        /** @see PackageSettingBase#resourcePathString */
15359        abstract String getResourcePath();
15360
15361        // Need installer lock especially for dex file removal.
15362        abstract void cleanUpResourcesLI();
15363        abstract boolean doPostDeleteLI(boolean delete);
15364
15365        /**
15366         * Called before the source arguments are copied. This is used mostly
15367         * for MoveParams when it needs to read the source file to put it in the
15368         * destination.
15369         */
15370        int doPreCopy() {
15371            return PackageManager.INSTALL_SUCCEEDED;
15372        }
15373
15374        /**
15375         * Called after the source arguments are copied. This is used mostly for
15376         * MoveParams when it needs to read the source file to put it in the
15377         * destination.
15378         */
15379        int doPostCopy(int uid) {
15380            return PackageManager.INSTALL_SUCCEEDED;
15381        }
15382
15383        protected boolean isFwdLocked() {
15384            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15385        }
15386
15387        protected boolean isExternalAsec() {
15388            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15389        }
15390
15391        protected boolean isEphemeral() {
15392            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15393        }
15394
15395        UserHandle getUser() {
15396            return user;
15397        }
15398    }
15399
15400    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15401        if (!allCodePaths.isEmpty()) {
15402            if (instructionSets == null) {
15403                throw new IllegalStateException("instructionSet == null");
15404            }
15405            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15406            for (String codePath : allCodePaths) {
15407                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15408                    try {
15409                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15410                    } catch (InstallerException ignored) {
15411                    }
15412                }
15413            }
15414        }
15415    }
15416
15417    /**
15418     * Logic to handle installation of non-ASEC applications, including copying
15419     * and renaming logic.
15420     */
15421    class FileInstallArgs extends InstallArgs {
15422        private File codeFile;
15423        private File resourceFile;
15424
15425        // Example topology:
15426        // /data/app/com.example/base.apk
15427        // /data/app/com.example/split_foo.apk
15428        // /data/app/com.example/lib/arm/libfoo.so
15429        // /data/app/com.example/lib/arm64/libfoo.so
15430        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15431
15432        /** New install */
15433        FileInstallArgs(InstallParams params) {
15434            super(params.origin, params.move, params.observer, params.installFlags,
15435                    params.installerPackageName, params.volumeUuid,
15436                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15437                    params.grantedRuntimePermissions,
15438                    params.traceMethod, params.traceCookie, params.signingDetails,
15439                    params.installReason);
15440            if (isFwdLocked()) {
15441                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15442            }
15443        }
15444
15445        /** Existing install */
15446        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15447            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15448                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15449                    PackageManager.INSTALL_REASON_UNKNOWN);
15450            this.codeFile = (codePath != null) ? new File(codePath) : null;
15451            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15452        }
15453
15454        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15455            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15456            try {
15457                return doCopyApk(imcs, temp);
15458            } finally {
15459                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15460            }
15461        }
15462
15463        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15464            if (origin.staged) {
15465                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15466                codeFile = origin.file;
15467                resourceFile = origin.file;
15468                return PackageManager.INSTALL_SUCCEEDED;
15469            }
15470
15471            try {
15472                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15473                final File tempDir =
15474                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15475                codeFile = tempDir;
15476                resourceFile = tempDir;
15477            } catch (IOException e) {
15478                Slog.w(TAG, "Failed to create copy file: " + e);
15479                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15480            }
15481
15482            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15483                @Override
15484                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15485                    if (!FileUtils.isValidExtFilename(name)) {
15486                        throw new IllegalArgumentException("Invalid filename: " + name);
15487                    }
15488                    try {
15489                        final File file = new File(codeFile, name);
15490                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15491                                O_RDWR | O_CREAT, 0644);
15492                        Os.chmod(file.getAbsolutePath(), 0644);
15493                        return new ParcelFileDescriptor(fd);
15494                    } catch (ErrnoException e) {
15495                        throw new RemoteException("Failed to open: " + e.getMessage());
15496                    }
15497                }
15498            };
15499
15500            int ret = PackageManager.INSTALL_SUCCEEDED;
15501            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15502            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15503                Slog.e(TAG, "Failed to copy package");
15504                return ret;
15505            }
15506
15507            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15508            NativeLibraryHelper.Handle handle = null;
15509            try {
15510                handle = NativeLibraryHelper.Handle.create(codeFile);
15511                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15512                        abiOverride);
15513            } catch (IOException e) {
15514                Slog.e(TAG, "Copying native libraries failed", e);
15515                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15516            } finally {
15517                IoUtils.closeQuietly(handle);
15518            }
15519
15520            return ret;
15521        }
15522
15523        int doPreInstall(int status) {
15524            if (status != PackageManager.INSTALL_SUCCEEDED) {
15525                cleanUp();
15526            }
15527            return status;
15528        }
15529
15530        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15531            if (status != PackageManager.INSTALL_SUCCEEDED) {
15532                cleanUp();
15533                return false;
15534            }
15535
15536            final File targetDir = codeFile.getParentFile();
15537            final File beforeCodeFile = codeFile;
15538            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15539
15540            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15541            try {
15542                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15543            } catch (ErrnoException e) {
15544                Slog.w(TAG, "Failed to rename", e);
15545                return false;
15546            }
15547
15548            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15549                Slog.w(TAG, "Failed to restorecon");
15550                return false;
15551            }
15552
15553            // Reflect the rename internally
15554            codeFile = afterCodeFile;
15555            resourceFile = afterCodeFile;
15556
15557            // Reflect the rename in scanned details
15558            try {
15559                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15560            } catch (IOException e) {
15561                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15562                return false;
15563            }
15564            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15565                    afterCodeFile, pkg.baseCodePath));
15566            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15567                    afterCodeFile, pkg.splitCodePaths));
15568
15569            // Reflect the rename in app info
15570            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15571            pkg.setApplicationInfoCodePath(pkg.codePath);
15572            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15573            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15574            pkg.setApplicationInfoResourcePath(pkg.codePath);
15575            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15576            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15577
15578            return true;
15579        }
15580
15581        int doPostInstall(int status, int uid) {
15582            if (status != PackageManager.INSTALL_SUCCEEDED) {
15583                cleanUp();
15584            }
15585            return status;
15586        }
15587
15588        @Override
15589        String getCodePath() {
15590            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15591        }
15592
15593        @Override
15594        String getResourcePath() {
15595            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15596        }
15597
15598        private boolean cleanUp() {
15599            if (codeFile == null || !codeFile.exists()) {
15600                return false;
15601            }
15602
15603            removeCodePathLI(codeFile);
15604
15605            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15606                resourceFile.delete();
15607            }
15608
15609            return true;
15610        }
15611
15612        void cleanUpResourcesLI() {
15613            // Try enumerating all code paths before deleting
15614            List<String> allCodePaths = Collections.EMPTY_LIST;
15615            if (codeFile != null && codeFile.exists()) {
15616                try {
15617                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15618                    allCodePaths = pkg.getAllCodePaths();
15619                } catch (PackageParserException e) {
15620                    // Ignored; we tried our best
15621                }
15622            }
15623
15624            cleanUp();
15625            removeDexFiles(allCodePaths, instructionSets);
15626        }
15627
15628        boolean doPostDeleteLI(boolean delete) {
15629            // XXX err, shouldn't we respect the delete flag?
15630            cleanUpResourcesLI();
15631            return true;
15632        }
15633    }
15634
15635    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15636            PackageManagerException {
15637        if (copyRet < 0) {
15638            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15639                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15640                throw new PackageManagerException(copyRet, message);
15641            }
15642        }
15643    }
15644
15645    /**
15646     * Extract the StorageManagerService "container ID" from the full code path of an
15647     * .apk.
15648     */
15649    static String cidFromCodePath(String fullCodePath) {
15650        int eidx = fullCodePath.lastIndexOf("/");
15651        String subStr1 = fullCodePath.substring(0, eidx);
15652        int sidx = subStr1.lastIndexOf("/");
15653        return subStr1.substring(sidx+1, eidx);
15654    }
15655
15656    /**
15657     * Logic to handle movement of existing installed applications.
15658     */
15659    class MoveInstallArgs extends InstallArgs {
15660        private File codeFile;
15661        private File resourceFile;
15662
15663        /** New install */
15664        MoveInstallArgs(InstallParams params) {
15665            super(params.origin, params.move, params.observer, params.installFlags,
15666                    params.installerPackageName, params.volumeUuid,
15667                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15668                    params.grantedRuntimePermissions,
15669                    params.traceMethod, params.traceCookie, params.signingDetails,
15670                    params.installReason);
15671        }
15672
15673        int copyApk(IMediaContainerService imcs, boolean temp) {
15674            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15675                    + move.fromUuid + " to " + move.toUuid);
15676            synchronized (mInstaller) {
15677                try {
15678                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15679                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15680                } catch (InstallerException e) {
15681                    Slog.w(TAG, "Failed to move app", e);
15682                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15683                }
15684            }
15685
15686            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15687            resourceFile = codeFile;
15688            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15689
15690            return PackageManager.INSTALL_SUCCEEDED;
15691        }
15692
15693        int doPreInstall(int status) {
15694            if (status != PackageManager.INSTALL_SUCCEEDED) {
15695                cleanUp(move.toUuid);
15696            }
15697            return status;
15698        }
15699
15700        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15701            if (status != PackageManager.INSTALL_SUCCEEDED) {
15702                cleanUp(move.toUuid);
15703                return false;
15704            }
15705
15706            // Reflect the move in app info
15707            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15708            pkg.setApplicationInfoCodePath(pkg.codePath);
15709            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15710            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15711            pkg.setApplicationInfoResourcePath(pkg.codePath);
15712            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15713            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15714
15715            return true;
15716        }
15717
15718        int doPostInstall(int status, int uid) {
15719            if (status == PackageManager.INSTALL_SUCCEEDED) {
15720                cleanUp(move.fromUuid);
15721            } else {
15722                cleanUp(move.toUuid);
15723            }
15724            return status;
15725        }
15726
15727        @Override
15728        String getCodePath() {
15729            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15730        }
15731
15732        @Override
15733        String getResourcePath() {
15734            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15735        }
15736
15737        private boolean cleanUp(String volumeUuid) {
15738            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15739                    move.dataAppName);
15740            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15741            final int[] userIds = sUserManager.getUserIds();
15742            synchronized (mInstallLock) {
15743                // Clean up both app data and code
15744                // All package moves are frozen until finished
15745                for (int userId : userIds) {
15746                    try {
15747                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15748                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15749                    } catch (InstallerException e) {
15750                        Slog.w(TAG, String.valueOf(e));
15751                    }
15752                }
15753                removeCodePathLI(codeFile);
15754            }
15755            return true;
15756        }
15757
15758        void cleanUpResourcesLI() {
15759            throw new UnsupportedOperationException();
15760        }
15761
15762        boolean doPostDeleteLI(boolean delete) {
15763            throw new UnsupportedOperationException();
15764        }
15765    }
15766
15767    static String getAsecPackageName(String packageCid) {
15768        int idx = packageCid.lastIndexOf("-");
15769        if (idx == -1) {
15770            return packageCid;
15771        }
15772        return packageCid.substring(0, idx);
15773    }
15774
15775    // Utility method used to create code paths based on package name and available index.
15776    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15777        String idxStr = "";
15778        int idx = 1;
15779        // Fall back to default value of idx=1 if prefix is not
15780        // part of oldCodePath
15781        if (oldCodePath != null) {
15782            String subStr = oldCodePath;
15783            // Drop the suffix right away
15784            if (suffix != null && subStr.endsWith(suffix)) {
15785                subStr = subStr.substring(0, subStr.length() - suffix.length());
15786            }
15787            // If oldCodePath already contains prefix find out the
15788            // ending index to either increment or decrement.
15789            int sidx = subStr.lastIndexOf(prefix);
15790            if (sidx != -1) {
15791                subStr = subStr.substring(sidx + prefix.length());
15792                if (subStr != null) {
15793                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15794                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15795                    }
15796                    try {
15797                        idx = Integer.parseInt(subStr);
15798                        if (idx <= 1) {
15799                            idx++;
15800                        } else {
15801                            idx--;
15802                        }
15803                    } catch(NumberFormatException e) {
15804                    }
15805                }
15806            }
15807        }
15808        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15809        return prefix + idxStr;
15810    }
15811
15812    private File getNextCodePath(File targetDir, String packageName) {
15813        File result;
15814        SecureRandom random = new SecureRandom();
15815        byte[] bytes = new byte[16];
15816        do {
15817            random.nextBytes(bytes);
15818            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15819            result = new File(targetDir, packageName + "-" + suffix);
15820        } while (result.exists());
15821        return result;
15822    }
15823
15824    // Utility method that returns the relative package path with respect
15825    // to the installation directory. Like say for /data/data/com.test-1.apk
15826    // string com.test-1 is returned.
15827    static String deriveCodePathName(String codePath) {
15828        if (codePath == null) {
15829            return null;
15830        }
15831        final File codeFile = new File(codePath);
15832        final String name = codeFile.getName();
15833        if (codeFile.isDirectory()) {
15834            return name;
15835        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15836            final int lastDot = name.lastIndexOf('.');
15837            return name.substring(0, lastDot);
15838        } else {
15839            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15840            return null;
15841        }
15842    }
15843
15844    static class PackageInstalledInfo {
15845        String name;
15846        int uid;
15847        // The set of users that originally had this package installed.
15848        int[] origUsers;
15849        // The set of users that now have this package installed.
15850        int[] newUsers;
15851        PackageParser.Package pkg;
15852        int returnCode;
15853        String returnMsg;
15854        String installerPackageName;
15855        PackageRemovedInfo removedInfo;
15856        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15857
15858        public void setError(int code, String msg) {
15859            setReturnCode(code);
15860            setReturnMessage(msg);
15861            Slog.w(TAG, msg);
15862        }
15863
15864        public void setError(String msg, PackageParserException e) {
15865            setReturnCode(e.error);
15866            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15867            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15868            for (int i = 0; i < childCount; i++) {
15869                addedChildPackages.valueAt(i).setError(msg, e);
15870            }
15871            Slog.w(TAG, msg, e);
15872        }
15873
15874        public void setError(String msg, PackageManagerException e) {
15875            returnCode = e.error;
15876            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15877            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15878            for (int i = 0; i < childCount; i++) {
15879                addedChildPackages.valueAt(i).setError(msg, e);
15880            }
15881            Slog.w(TAG, msg, e);
15882        }
15883
15884        public void setReturnCode(int returnCode) {
15885            this.returnCode = returnCode;
15886            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15887            for (int i = 0; i < childCount; i++) {
15888                addedChildPackages.valueAt(i).returnCode = returnCode;
15889            }
15890        }
15891
15892        private void setReturnMessage(String returnMsg) {
15893            this.returnMsg = returnMsg;
15894            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15895            for (int i = 0; i < childCount; i++) {
15896                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15897            }
15898        }
15899
15900        // In some error cases we want to convey more info back to the observer
15901        String origPackage;
15902        String origPermission;
15903    }
15904
15905    /*
15906     * Install a non-existing package.
15907     */
15908    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15909            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15910            String volumeUuid, PackageInstalledInfo res, int installReason) {
15911        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15912
15913        // Remember this for later, in case we need to rollback this install
15914        String pkgName = pkg.packageName;
15915
15916        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15917
15918        synchronized(mPackages) {
15919            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15920            if (renamedPackage != null) {
15921                // A package with the same name is already installed, though
15922                // it has been renamed to an older name.  The package we
15923                // are trying to install should be installed as an update to
15924                // the existing one, but that has not been requested, so bail.
15925                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15926                        + " without first uninstalling package running as "
15927                        + renamedPackage);
15928                return;
15929            }
15930            if (mPackages.containsKey(pkgName)) {
15931                // Don't allow installation over an existing package with the same name.
15932                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15933                        + " without first uninstalling.");
15934                return;
15935            }
15936        }
15937
15938        try {
15939            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
15940                    System.currentTimeMillis(), user);
15941
15942            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15943
15944            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15945                prepareAppDataAfterInstallLIF(newPackage);
15946
15947            } else {
15948                // Remove package from internal structures, but keep around any
15949                // data that might have already existed
15950                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15951                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15952            }
15953        } catch (PackageManagerException e) {
15954            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15955        }
15956
15957        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15958    }
15959
15960    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15961        try (DigestInputStream digestStream =
15962                new DigestInputStream(new FileInputStream(file), digest)) {
15963            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15964        }
15965    }
15966
15967    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15968            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15969            PackageInstalledInfo res, int installReason) {
15970        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15971
15972        final PackageParser.Package oldPackage;
15973        final PackageSetting ps;
15974        final String pkgName = pkg.packageName;
15975        final int[] allUsers;
15976        final int[] installedUsers;
15977
15978        synchronized(mPackages) {
15979            oldPackage = mPackages.get(pkgName);
15980            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15981
15982            // don't allow upgrade to target a release SDK from a pre-release SDK
15983            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15984                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15985            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15986                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15987            if (oldTargetsPreRelease
15988                    && !newTargetsPreRelease
15989                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15990                Slog.w(TAG, "Can't install package targeting released sdk");
15991                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15992                return;
15993            }
15994
15995            ps = mSettings.mPackages.get(pkgName);
15996
15997            // verify signatures are valid
15998            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
15999            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16000                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16001                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16002                            "New package not signed by keys specified by upgrade-keysets: "
16003                                    + pkgName);
16004                    return;
16005                }
16006            } else {
16007
16008                // default to original signature matching
16009                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16010                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
16011                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16012                            "New package has a different signature: " + pkgName);
16013                    return;
16014                }
16015            }
16016
16017            // don't allow a system upgrade unless the upgrade hash matches
16018            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16019                byte[] digestBytes = null;
16020                try {
16021                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16022                    updateDigest(digest, new File(pkg.baseCodePath));
16023                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16024                        for (String path : pkg.splitCodePaths) {
16025                            updateDigest(digest, new File(path));
16026                        }
16027                    }
16028                    digestBytes = digest.digest();
16029                } catch (NoSuchAlgorithmException | IOException e) {
16030                    res.setError(INSTALL_FAILED_INVALID_APK,
16031                            "Could not compute hash: " + pkgName);
16032                    return;
16033                }
16034                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16035                    res.setError(INSTALL_FAILED_INVALID_APK,
16036                            "New package fails restrict-update check: " + pkgName);
16037                    return;
16038                }
16039                // retain upgrade restriction
16040                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16041            }
16042
16043            // Check for shared user id changes
16044            String invalidPackageName =
16045                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16046            if (invalidPackageName != null) {
16047                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16048                        "Package " + invalidPackageName + " tried to change user "
16049                                + oldPackage.mSharedUserId);
16050                return;
16051            }
16052
16053            // check if the new package supports all of the abis which the old package supports
16054            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16055            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16056            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16057                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16058                        "Update to package " + pkgName + " doesn't support multi arch");
16059                return;
16060            }
16061
16062            // In case of rollback, remember per-user/profile install state
16063            allUsers = sUserManager.getUserIds();
16064            installedUsers = ps.queryInstalledUsers(allUsers, true);
16065
16066            // don't allow an upgrade from full to ephemeral
16067            if (isInstantApp) {
16068                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16069                    for (int currentUser : allUsers) {
16070                        if (!ps.getInstantApp(currentUser)) {
16071                            // can't downgrade from full to instant
16072                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16073                                    + " for user: " + currentUser);
16074                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16075                            return;
16076                        }
16077                    }
16078                } else if (!ps.getInstantApp(user.getIdentifier())) {
16079                    // can't downgrade from full to instant
16080                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16081                            + " for user: " + user.getIdentifier());
16082                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16083                    return;
16084                }
16085            }
16086        }
16087
16088        // Update what is removed
16089        res.removedInfo = new PackageRemovedInfo(this);
16090        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16091        res.removedInfo.removedPackage = oldPackage.packageName;
16092        res.removedInfo.installerPackageName = ps.installerPackageName;
16093        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16094        res.removedInfo.isUpdate = true;
16095        res.removedInfo.origUsers = installedUsers;
16096        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16097        for (int i = 0; i < installedUsers.length; i++) {
16098            final int userId = installedUsers[i];
16099            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16100        }
16101
16102        final int childCount = (oldPackage.childPackages != null)
16103                ? oldPackage.childPackages.size() : 0;
16104        for (int i = 0; i < childCount; i++) {
16105            boolean childPackageUpdated = false;
16106            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16107            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16108            if (res.addedChildPackages != null) {
16109                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16110                if (childRes != null) {
16111                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16112                    childRes.removedInfo.removedPackage = childPkg.packageName;
16113                    if (childPs != null) {
16114                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16115                    }
16116                    childRes.removedInfo.isUpdate = true;
16117                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16118                    childPackageUpdated = true;
16119                }
16120            }
16121            if (!childPackageUpdated) {
16122                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16123                childRemovedRes.removedPackage = childPkg.packageName;
16124                if (childPs != null) {
16125                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16126                }
16127                childRemovedRes.isUpdate = false;
16128                childRemovedRes.dataRemoved = true;
16129                synchronized (mPackages) {
16130                    if (childPs != null) {
16131                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16132                    }
16133                }
16134                if (res.removedInfo.removedChildPackages == null) {
16135                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16136                }
16137                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16138            }
16139        }
16140
16141        boolean sysPkg = (isSystemApp(oldPackage));
16142        if (sysPkg) {
16143            // Set the system/privileged/oem/vendor/product flags as needed
16144            final boolean privileged =
16145                    (oldPackage.applicationInfo.privateFlags
16146                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16147            final boolean oem =
16148                    (oldPackage.applicationInfo.privateFlags
16149                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16150            final boolean vendor =
16151                    (oldPackage.applicationInfo.privateFlags
16152                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16153            final boolean product =
16154                    (oldPackage.applicationInfo.privateFlags
16155                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16156            final @ParseFlags int systemParseFlags = parseFlags;
16157            final @ScanFlags int systemScanFlags = scanFlags
16158                    | SCAN_AS_SYSTEM
16159                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16160                    | (oem ? SCAN_AS_OEM : 0)
16161                    | (vendor ? SCAN_AS_VENDOR : 0)
16162                    | (product ? SCAN_AS_PRODUCT : 0);
16163
16164            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16165                    user, allUsers, installerPackageName, res, installReason);
16166        } else {
16167            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16168                    user, allUsers, installerPackageName, res, installReason);
16169        }
16170    }
16171
16172    @Override
16173    public List<String> getPreviousCodePaths(String packageName) {
16174        final int callingUid = Binder.getCallingUid();
16175        final List<String> result = new ArrayList<>();
16176        if (getInstantAppPackageName(callingUid) != null) {
16177            return result;
16178        }
16179        final PackageSetting ps = mSettings.mPackages.get(packageName);
16180        if (ps != null
16181                && ps.oldCodePaths != null
16182                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16183            result.addAll(ps.oldCodePaths);
16184        }
16185        return result;
16186    }
16187
16188    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16189            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16190            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16191            String installerPackageName, PackageInstalledInfo res, int installReason) {
16192        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16193                + deletedPackage);
16194
16195        String pkgName = deletedPackage.packageName;
16196        boolean deletedPkg = true;
16197        boolean addedPkg = false;
16198        boolean updatedSettings = false;
16199        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16200        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16201                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16202
16203        final long origUpdateTime = (pkg.mExtras != null)
16204                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16205
16206        // First delete the existing package while retaining the data directory
16207        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16208                res.removedInfo, true, pkg)) {
16209            // If the existing package wasn't successfully deleted
16210            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16211            deletedPkg = false;
16212        } else {
16213            // Successfully deleted the old package; proceed with replace.
16214
16215            // If deleted package lived in a container, give users a chance to
16216            // relinquish resources before killing.
16217            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16218                if (DEBUG_INSTALL) {
16219                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16220                }
16221                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16222                final ArrayList<String> pkgList = new ArrayList<String>(1);
16223                pkgList.add(deletedPackage.applicationInfo.packageName);
16224                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16225            }
16226
16227            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16228                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16229
16230            try {
16231                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16232                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16233                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16234                        installReason);
16235
16236                // Update the in-memory copy of the previous code paths.
16237                PackageSetting ps = mSettings.mPackages.get(pkgName);
16238                if (!killApp) {
16239                    if (ps.oldCodePaths == null) {
16240                        ps.oldCodePaths = new ArraySet<>();
16241                    }
16242                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16243                    if (deletedPackage.splitCodePaths != null) {
16244                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16245                    }
16246                } else {
16247                    ps.oldCodePaths = null;
16248                }
16249                if (ps.childPackageNames != null) {
16250                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16251                        final String childPkgName = ps.childPackageNames.get(i);
16252                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16253                        childPs.oldCodePaths = ps.oldCodePaths;
16254                    }
16255                }
16256                // set instant app status, but, only if it's explicitly specified
16257                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16258                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16259                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16260                prepareAppDataAfterInstallLIF(newPackage);
16261                addedPkg = true;
16262                mDexManager.notifyPackageUpdated(newPackage.packageName,
16263                        newPackage.baseCodePath, newPackage.splitCodePaths);
16264            } catch (PackageManagerException e) {
16265                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16266            }
16267        }
16268
16269        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16270            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16271
16272            // Revert all internal state mutations and added folders for the failed install
16273            if (addedPkg) {
16274                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16275                        res.removedInfo, true, null);
16276            }
16277
16278            // Restore the old package
16279            if (deletedPkg) {
16280                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16281                File restoreFile = new File(deletedPackage.codePath);
16282                // Parse old package
16283                boolean oldExternal = isExternal(deletedPackage);
16284                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16285                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16286                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16287                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16288                try {
16289                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16290                            null);
16291                } catch (PackageManagerException e) {
16292                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16293                            + e.getMessage());
16294                    return;
16295                }
16296
16297                synchronized (mPackages) {
16298                    // Ensure the installer package name up to date
16299                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16300
16301                    // Update permissions for restored package
16302                    mPermissionManager.updatePermissions(
16303                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16304                            mPermissionCallback);
16305
16306                    mSettings.writeLPr();
16307                }
16308
16309                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16310            }
16311        } else {
16312            synchronized (mPackages) {
16313                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16314                if (ps != null) {
16315                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16316                    if (res.removedInfo.removedChildPackages != null) {
16317                        final int childCount = res.removedInfo.removedChildPackages.size();
16318                        // Iterate in reverse as we may modify the collection
16319                        for (int i = childCount - 1; i >= 0; i--) {
16320                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16321                            if (res.addedChildPackages.containsKey(childPackageName)) {
16322                                res.removedInfo.removedChildPackages.removeAt(i);
16323                            } else {
16324                                PackageRemovedInfo childInfo = res.removedInfo
16325                                        .removedChildPackages.valueAt(i);
16326                                childInfo.removedForAllUsers = mPackages.get(
16327                                        childInfo.removedPackage) == null;
16328                            }
16329                        }
16330                    }
16331                }
16332            }
16333        }
16334    }
16335
16336    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16337            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16338            final @ScanFlags int scanFlags, UserHandle user,
16339            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16340            int installReason) {
16341        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16342                + ", old=" + deletedPackage);
16343
16344        final boolean disabledSystem;
16345
16346        // Remove existing system package
16347        removePackageLI(deletedPackage, true);
16348
16349        synchronized (mPackages) {
16350            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16351        }
16352        if (!disabledSystem) {
16353            // We didn't need to disable the .apk as a current system package,
16354            // which means we are replacing another update that is already
16355            // installed.  We need to make sure to delete the older one's .apk.
16356            res.removedInfo.args = createInstallArgsForExisting(0,
16357                    deletedPackage.applicationInfo.getCodePath(),
16358                    deletedPackage.applicationInfo.getResourcePath(),
16359                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16360        } else {
16361            res.removedInfo.args = null;
16362        }
16363
16364        // Successfully disabled the old package. Now proceed with re-installation
16365        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16366                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16367
16368        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16369        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16370                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16371
16372        PackageParser.Package newPackage = null;
16373        try {
16374            // Add the package to the internal data structures
16375            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16376
16377            // Set the update and install times
16378            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16379            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16380                    System.currentTimeMillis());
16381
16382            // Update the package dynamic state if succeeded
16383            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16384                // Now that the install succeeded make sure we remove data
16385                // directories for any child package the update removed.
16386                final int deletedChildCount = (deletedPackage.childPackages != null)
16387                        ? deletedPackage.childPackages.size() : 0;
16388                final int newChildCount = (newPackage.childPackages != null)
16389                        ? newPackage.childPackages.size() : 0;
16390                for (int i = 0; i < deletedChildCount; i++) {
16391                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16392                    boolean childPackageDeleted = true;
16393                    for (int j = 0; j < newChildCount; j++) {
16394                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16395                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16396                            childPackageDeleted = false;
16397                            break;
16398                        }
16399                    }
16400                    if (childPackageDeleted) {
16401                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16402                                deletedChildPkg.packageName);
16403                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16404                            PackageRemovedInfo removedChildRes = res.removedInfo
16405                                    .removedChildPackages.get(deletedChildPkg.packageName);
16406                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16407                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16408                        }
16409                    }
16410                }
16411
16412                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16413                        installReason);
16414                prepareAppDataAfterInstallLIF(newPackage);
16415
16416                mDexManager.notifyPackageUpdated(newPackage.packageName,
16417                            newPackage.baseCodePath, newPackage.splitCodePaths);
16418            }
16419        } catch (PackageManagerException e) {
16420            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16421            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16422        }
16423
16424        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16425            // Re installation failed. Restore old information
16426            // Remove new pkg information
16427            if (newPackage != null) {
16428                removeInstalledPackageLI(newPackage, true);
16429            }
16430            // Add back the old system package
16431            try {
16432                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16433            } catch (PackageManagerException e) {
16434                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16435            }
16436
16437            synchronized (mPackages) {
16438                if (disabledSystem) {
16439                    enableSystemPackageLPw(deletedPackage);
16440                }
16441
16442                // Ensure the installer package name up to date
16443                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16444
16445                // Update permissions for restored package
16446                mPermissionManager.updatePermissions(
16447                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16448                        mPermissionCallback);
16449
16450                mSettings.writeLPr();
16451            }
16452
16453            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16454                    + " after failed upgrade");
16455        }
16456    }
16457
16458    /**
16459     * Checks whether the parent or any of the child packages have a change shared
16460     * user. For a package to be a valid update the shred users of the parent and
16461     * the children should match. We may later support changing child shared users.
16462     * @param oldPkg The updated package.
16463     * @param newPkg The update package.
16464     * @return The shared user that change between the versions.
16465     */
16466    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16467            PackageParser.Package newPkg) {
16468        // Check parent shared user
16469        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16470            return newPkg.packageName;
16471        }
16472        // Check child shared users
16473        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16474        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16475        for (int i = 0; i < newChildCount; i++) {
16476            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16477            // If this child was present, did it have the same shared user?
16478            for (int j = 0; j < oldChildCount; j++) {
16479                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16480                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16481                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16482                    return newChildPkg.packageName;
16483                }
16484            }
16485        }
16486        return null;
16487    }
16488
16489    private void removeNativeBinariesLI(PackageSetting ps) {
16490        // Remove the lib path for the parent package
16491        if (ps != null) {
16492            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16493            // Remove the lib path for the child packages
16494            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16495            for (int i = 0; i < childCount; i++) {
16496                PackageSetting childPs = null;
16497                synchronized (mPackages) {
16498                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16499                }
16500                if (childPs != null) {
16501                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16502                            .legacyNativeLibraryPathString);
16503                }
16504            }
16505        }
16506    }
16507
16508    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16509        // Enable the parent package
16510        mSettings.enableSystemPackageLPw(pkg.packageName);
16511        // Enable the child packages
16512        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16513        for (int i = 0; i < childCount; i++) {
16514            PackageParser.Package childPkg = pkg.childPackages.get(i);
16515            mSettings.enableSystemPackageLPw(childPkg.packageName);
16516        }
16517    }
16518
16519    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16520            PackageParser.Package newPkg) {
16521        // Disable the parent package (parent always replaced)
16522        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16523        // Disable the child packages
16524        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16525        for (int i = 0; i < childCount; i++) {
16526            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16527            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16528            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16529        }
16530        return disabled;
16531    }
16532
16533    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16534            String installerPackageName) {
16535        // Enable the parent package
16536        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16537        // Enable the child packages
16538        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16539        for (int i = 0; i < childCount; i++) {
16540            PackageParser.Package childPkg = pkg.childPackages.get(i);
16541            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16542        }
16543    }
16544
16545    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16546            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16547        // Update the parent package setting
16548        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16549                res, user, installReason);
16550        // Update the child packages setting
16551        final int childCount = (newPackage.childPackages != null)
16552                ? newPackage.childPackages.size() : 0;
16553        for (int i = 0; i < childCount; i++) {
16554            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16555            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16556            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16557                    childRes.origUsers, childRes, user, installReason);
16558        }
16559    }
16560
16561    private void updateSettingsInternalLI(PackageParser.Package pkg,
16562            String installerPackageName, int[] allUsers, int[] installedForUsers,
16563            PackageInstalledInfo res, UserHandle user, int installReason) {
16564        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16565
16566        final String pkgName = pkg.packageName;
16567
16568        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16569        synchronized (mPackages) {
16570// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16571            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16572                    mPermissionCallback);
16573            // For system-bundled packages, we assume that installing an upgraded version
16574            // of the package implies that the user actually wants to run that new code,
16575            // so we enable the package.
16576            PackageSetting ps = mSettings.mPackages.get(pkgName);
16577            final int userId = user.getIdentifier();
16578            if (ps != null) {
16579                if (isSystemApp(pkg)) {
16580                    if (DEBUG_INSTALL) {
16581                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16582                    }
16583                    // Enable system package for requested users
16584                    if (res.origUsers != null) {
16585                        for (int origUserId : res.origUsers) {
16586                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16587                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16588                                        origUserId, installerPackageName);
16589                            }
16590                        }
16591                    }
16592                    // Also convey the prior install/uninstall state
16593                    if (allUsers != null && installedForUsers != null) {
16594                        for (int currentUserId : allUsers) {
16595                            final boolean installed = ArrayUtils.contains(
16596                                    installedForUsers, currentUserId);
16597                            if (DEBUG_INSTALL) {
16598                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16599                            }
16600                            ps.setInstalled(installed, currentUserId);
16601                        }
16602                        // these install state changes will be persisted in the
16603                        // upcoming call to mSettings.writeLPr().
16604                    }
16605                }
16606                // It's implied that when a user requests installation, they want the app to be
16607                // installed and enabled.
16608                if (userId != UserHandle.USER_ALL) {
16609                    ps.setInstalled(true, userId);
16610                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16611                } else {
16612                    for (int currentUserId : sUserManager.getUserIds()) {
16613                        ps.setInstalled(true, currentUserId);
16614                        ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, currentUserId,
16615                                installerPackageName);
16616                    }
16617                }
16618
16619                // When replacing an existing package, preserve the original install reason for all
16620                // users that had the package installed before.
16621                final Set<Integer> previousUserIds = new ArraySet<>();
16622                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16623                    final int installReasonCount = res.removedInfo.installReasons.size();
16624                    for (int i = 0; i < installReasonCount; i++) {
16625                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16626                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16627                        ps.setInstallReason(previousInstallReason, previousUserId);
16628                        previousUserIds.add(previousUserId);
16629                    }
16630                }
16631
16632                // Set install reason for users that are having the package newly installed.
16633                if (userId == UserHandle.USER_ALL) {
16634                    for (int currentUserId : sUserManager.getUserIds()) {
16635                        if (!previousUserIds.contains(currentUserId)) {
16636                            ps.setInstallReason(installReason, currentUserId);
16637                        }
16638                    }
16639                } else if (!previousUserIds.contains(userId)) {
16640                    ps.setInstallReason(installReason, userId);
16641                }
16642                mSettings.writeKernelMappingLPr(ps);
16643            }
16644            res.name = pkgName;
16645            res.uid = pkg.applicationInfo.uid;
16646            res.pkg = pkg;
16647            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16648            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16649            //to update install status
16650            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16651            mSettings.writeLPr();
16652            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16653        }
16654
16655        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16656    }
16657
16658    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16659        try {
16660            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16661            installPackageLI(args, res);
16662        } finally {
16663            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16664        }
16665    }
16666
16667    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16668        final int installFlags = args.installFlags;
16669        final String installerPackageName = args.installerPackageName;
16670        final String volumeUuid = args.volumeUuid;
16671        final File tmpPackageFile = new File(args.getCodePath());
16672        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16673        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16674                || (args.volumeUuid != null));
16675        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16676        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16677        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16678        final boolean virtualPreload =
16679                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16680        boolean replace = false;
16681        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16682        if (args.move != null) {
16683            // moving a complete application; perform an initial scan on the new install location
16684            scanFlags |= SCAN_INITIAL;
16685        }
16686        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16687            scanFlags |= SCAN_DONT_KILL_APP;
16688        }
16689        if (instantApp) {
16690            scanFlags |= SCAN_AS_INSTANT_APP;
16691        }
16692        if (fullApp) {
16693            scanFlags |= SCAN_AS_FULL_APP;
16694        }
16695        if (virtualPreload) {
16696            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16697        }
16698
16699        // Result object to be returned
16700        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16701        res.installerPackageName = installerPackageName;
16702
16703        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16704
16705        // Sanity check
16706        if (instantApp && (forwardLocked || onExternal)) {
16707            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16708                    + " external=" + onExternal);
16709            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16710            return;
16711        }
16712
16713        // Retrieve PackageSettings and parse package
16714        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16715                | PackageParser.PARSE_ENFORCE_CODE
16716                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16717                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16718                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16719        PackageParser pp = new PackageParser();
16720        pp.setSeparateProcesses(mSeparateProcesses);
16721        pp.setDisplayMetrics(mMetrics);
16722        pp.setCallback(mPackageParserCallback);
16723
16724        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16725        final PackageParser.Package pkg;
16726        try {
16727            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16728            DexMetadataHelper.validatePackageDexMetadata(pkg);
16729        } catch (PackageParserException e) {
16730            res.setError("Failed parse during installPackageLI", e);
16731            return;
16732        } finally {
16733            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16734        }
16735
16736        // Instant apps have several additional install-time checks.
16737        if (instantApp) {
16738            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16739                Slog.w(TAG,
16740                        "Instant app package " + pkg.packageName + " does not target at least O");
16741                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16742                        "Instant app package must target at least O");
16743                return;
16744            }
16745            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16746                Slog.w(TAG, "Instant app package " + pkg.packageName
16747                        + " does not target targetSandboxVersion 2");
16748                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16749                        "Instant app package must use targetSandboxVersion 2");
16750                return;
16751            }
16752            if (pkg.mSharedUserId != null) {
16753                Slog.w(TAG, "Instant app package " + pkg.packageName
16754                        + " may not declare sharedUserId.");
16755                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16756                        "Instant app package may not declare a sharedUserId");
16757                return;
16758            }
16759        }
16760
16761        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16762            // Static shared libraries have synthetic package names
16763            renameStaticSharedLibraryPackage(pkg);
16764
16765            // No static shared libs on external storage
16766            if (onExternal) {
16767                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16768                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16769                        "Packages declaring static-shared libs cannot be updated");
16770                return;
16771            }
16772        }
16773
16774        // If we are installing a clustered package add results for the children
16775        if (pkg.childPackages != null) {
16776            synchronized (mPackages) {
16777                final int childCount = pkg.childPackages.size();
16778                for (int i = 0; i < childCount; i++) {
16779                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16780                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16781                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16782                    childRes.pkg = childPkg;
16783                    childRes.name = childPkg.packageName;
16784                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16785                    if (childPs != null) {
16786                        childRes.origUsers = childPs.queryInstalledUsers(
16787                                sUserManager.getUserIds(), true);
16788                    }
16789                    if ((mPackages.containsKey(childPkg.packageName))) {
16790                        childRes.removedInfo = new PackageRemovedInfo(this);
16791                        childRes.removedInfo.removedPackage = childPkg.packageName;
16792                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16793                    }
16794                    if (res.addedChildPackages == null) {
16795                        res.addedChildPackages = new ArrayMap<>();
16796                    }
16797                    res.addedChildPackages.put(childPkg.packageName, childRes);
16798                }
16799            }
16800        }
16801
16802        // If package doesn't declare API override, mark that we have an install
16803        // time CPU ABI override.
16804        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16805            pkg.cpuAbiOverride = args.abiOverride;
16806        }
16807
16808        String pkgName = res.name = pkg.packageName;
16809        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16810            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16811                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16812                return;
16813            }
16814        }
16815
16816        try {
16817            // either use what we've been given or parse directly from the APK
16818            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
16819                pkg.setSigningDetails(args.signingDetails);
16820            } else {
16821                PackageParser.collectCertificates(pkg, false /* skipVerify */);
16822            }
16823        } catch (PackageParserException e) {
16824            res.setError("Failed collect during installPackageLI", e);
16825            return;
16826        }
16827
16828        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
16829                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
16830            Slog.w(TAG, "Instant app package " + pkg.packageName
16831                    + " is not signed with at least APK Signature Scheme v2");
16832            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16833                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
16834            return;
16835        }
16836
16837        // Get rid of all references to package scan path via parser.
16838        pp = null;
16839        String oldCodePath = null;
16840        boolean systemApp = false;
16841        synchronized (mPackages) {
16842            // Check if installing already existing package
16843            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16844                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16845                if (pkg.mOriginalPackages != null
16846                        && pkg.mOriginalPackages.contains(oldName)
16847                        && mPackages.containsKey(oldName)) {
16848                    // This package is derived from an original package,
16849                    // and this device has been updating from that original
16850                    // name.  We must continue using the original name, so
16851                    // rename the new package here.
16852                    pkg.setPackageName(oldName);
16853                    pkgName = pkg.packageName;
16854                    replace = true;
16855                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16856                            + oldName + " pkgName=" + pkgName);
16857                } else if (mPackages.containsKey(pkgName)) {
16858                    // This package, under its official name, already exists
16859                    // on the device; we should replace it.
16860                    replace = true;
16861                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16862                }
16863
16864                // Child packages are installed through the parent package
16865                if (pkg.parentPackage != null) {
16866                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16867                            "Package " + pkg.packageName + " is child of package "
16868                                    + pkg.parentPackage.parentPackage + ". Child packages "
16869                                    + "can be updated only through the parent package.");
16870                    return;
16871                }
16872
16873                if (replace) {
16874                    // Prevent apps opting out from runtime permissions
16875                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16876                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16877                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16878                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16879                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16880                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16881                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16882                                        + " doesn't support runtime permissions but the old"
16883                                        + " target SDK " + oldTargetSdk + " does.");
16884                        return;
16885                    }
16886                    // Prevent persistent apps from being updated
16887                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
16888                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
16889                                "Package " + oldPackage.packageName + " is a persistent app. "
16890                                        + "Persistent apps are not updateable.");
16891                        return;
16892                    }
16893                    // Prevent apps from downgrading their targetSandbox.
16894                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16895                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16896                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16897                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16898                                "Package " + pkg.packageName + " new target sandbox "
16899                                + newTargetSandbox + " is incompatible with the previous value of"
16900                                + oldTargetSandbox + ".");
16901                        return;
16902                    }
16903
16904                    // Prevent installing of child packages
16905                    if (oldPackage.parentPackage != null) {
16906                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16907                                "Package " + pkg.packageName + " is child of package "
16908                                        + oldPackage.parentPackage + ". Child packages "
16909                                        + "can be updated only through the parent package.");
16910                        return;
16911                    }
16912                }
16913            }
16914
16915            PackageSetting ps = mSettings.mPackages.get(pkgName);
16916            if (ps != null) {
16917                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16918
16919                // Static shared libs have same package with different versions where
16920                // we internally use a synthetic package name to allow multiple versions
16921                // of the same package, therefore we need to compare signatures against
16922                // the package setting for the latest library version.
16923                PackageSetting signatureCheckPs = ps;
16924                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16925                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16926                    if (libraryEntry != null) {
16927                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16928                    }
16929                }
16930
16931                // Quick sanity check that we're signed correctly if updating;
16932                // we'll check this again later when scanning, but we want to
16933                // bail early here before tripping over redefined permissions.
16934                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16935                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
16936                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
16937                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16938                                + pkg.packageName + " upgrade keys do not match the "
16939                                + "previously installed version");
16940                        return;
16941                    }
16942                } else {
16943                    try {
16944                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
16945                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
16946                        // We don't care about disabledPkgSetting on install for now.
16947                        final boolean compatMatch = verifySignatures(
16948                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
16949                                compareRecover);
16950                        // The new KeySets will be re-added later in the scanning process.
16951                        if (compatMatch) {
16952                            synchronized (mPackages) {
16953                                ksms.removeAppKeySetDataLPw(pkg.packageName);
16954                            }
16955                        }
16956                    } catch (PackageManagerException e) {
16957                        res.setError(e.error, e.getMessage());
16958                        return;
16959                    }
16960                }
16961
16962                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16963                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16964                    systemApp = (ps.pkg.applicationInfo.flags &
16965                            ApplicationInfo.FLAG_SYSTEM) != 0;
16966                }
16967                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16968            }
16969
16970            int N = pkg.permissions.size();
16971            for (int i = N-1; i >= 0; i--) {
16972                final PackageParser.Permission perm = pkg.permissions.get(i);
16973                final BasePermission bp =
16974                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
16975
16976                // Don't allow anyone but the system to define ephemeral permissions.
16977                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
16978                        && !systemApp) {
16979                    Slog.w(TAG, "Non-System package " + pkg.packageName
16980                            + " attempting to delcare ephemeral permission "
16981                            + perm.info.name + "; Removing ephemeral.");
16982                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
16983                }
16984
16985                // Check whether the newly-scanned package wants to define an already-defined perm
16986                if (bp != null) {
16987                    // If the defining package is signed with our cert, it's okay.  This
16988                    // also includes the "updating the same package" case, of course.
16989                    // "updating same package" could also involve key-rotation.
16990                    final boolean sigsOk;
16991                    final String sourcePackageName = bp.getSourcePackageName();
16992                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
16993                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16994                    if (sourcePackageName.equals(pkg.packageName)
16995                            && (ksms.shouldCheckUpgradeKeySetLocked(
16996                                    sourcePackageSetting, scanFlags))) {
16997                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
16998                    } else {
16999
17000                        // in the event of signing certificate rotation, we need to see if the
17001                        // package's certificate has rotated from the current one, or if it is an
17002                        // older certificate with which the current is ok with sharing permissions
17003                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17004                                        pkg.mSigningDetails,
17005                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17006                            sigsOk = true;
17007                        } else if (pkg.mSigningDetails.checkCapability(
17008                                        sourcePackageSetting.signatures.mSigningDetails,
17009                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17010
17011                            // the scanned package checks out, has signing certificate rotation
17012                            // history, and is newer; bring it over
17013                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17014                            sigsOk = true;
17015                        } else {
17016                            sigsOk = false;
17017                        }
17018                    }
17019                    if (!sigsOk) {
17020                        // If the owning package is the system itself, we log but allow
17021                        // install to proceed; we fail the install on all other permission
17022                        // redefinitions.
17023                        if (!sourcePackageName.equals("android")) {
17024                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17025                                    + pkg.packageName + " attempting to redeclare permission "
17026                                    + perm.info.name + " already owned by " + sourcePackageName);
17027                            res.origPermission = perm.info.name;
17028                            res.origPackage = sourcePackageName;
17029                            return;
17030                        } else {
17031                            Slog.w(TAG, "Package " + pkg.packageName
17032                                    + " attempting to redeclare system permission "
17033                                    + perm.info.name + "; ignoring new declaration");
17034                            pkg.permissions.remove(i);
17035                        }
17036                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17037                        // Prevent apps to change protection level to dangerous from any other
17038                        // type as this would allow a privilege escalation where an app adds a
17039                        // normal/signature permission in other app's group and later redefines
17040                        // it as dangerous leading to the group auto-grant.
17041                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17042                                == PermissionInfo.PROTECTION_DANGEROUS) {
17043                            if (bp != null && !bp.isRuntime()) {
17044                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17045                                        + "non-runtime permission " + perm.info.name
17046                                        + " to runtime; keeping old protection level");
17047                                perm.info.protectionLevel = bp.getProtectionLevel();
17048                            }
17049                        }
17050                    }
17051                }
17052            }
17053        }
17054
17055        if (systemApp) {
17056            if (onExternal) {
17057                // Abort update; system app can't be replaced with app on sdcard
17058                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17059                        "Cannot install updates to system apps on sdcard");
17060                return;
17061            } else if (instantApp) {
17062                // Abort update; system app can't be replaced with an instant app
17063                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17064                        "Cannot update a system app with an instant app");
17065                return;
17066            }
17067        }
17068
17069        if (args.move != null) {
17070            // We did an in-place move, so dex is ready to roll
17071            scanFlags |= SCAN_NO_DEX;
17072            scanFlags |= SCAN_MOVE;
17073
17074            synchronized (mPackages) {
17075                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17076                if (ps == null) {
17077                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17078                            "Missing settings for moved package " + pkgName);
17079                }
17080
17081                // We moved the entire application as-is, so bring over the
17082                // previously derived ABI information.
17083                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17084                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17085            }
17086
17087        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17088            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17089            scanFlags |= SCAN_NO_DEX;
17090
17091            try {
17092                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17093                    args.abiOverride : pkg.cpuAbiOverride);
17094                final boolean extractNativeLibs = !pkg.isLibrary();
17095                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17096            } catch (PackageManagerException pme) {
17097                Slog.e(TAG, "Error deriving application ABI", pme);
17098                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17099                return;
17100            }
17101
17102            // Shared libraries for the package need to be updated.
17103            synchronized (mPackages) {
17104                try {
17105                    updateSharedLibrariesLPr(pkg, null);
17106                } catch (PackageManagerException e) {
17107                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17108                }
17109            }
17110        }
17111
17112        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17113            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17114            return;
17115        }
17116
17117        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17118            String apkPath = null;
17119            synchronized (mPackages) {
17120                // Note that if the attacker managed to skip verify setup, for example by tampering
17121                // with the package settings, upon reboot we will do full apk verification when
17122                // verity is not detected.
17123                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17124                if (ps != null && ps.isPrivileged()) {
17125                    apkPath = pkg.baseCodePath;
17126                }
17127            }
17128
17129            if (apkPath != null) {
17130                final VerityUtils.SetupResult result =
17131                        VerityUtils.generateApkVeritySetupData(apkPath);
17132                if (result.isOk()) {
17133                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17134                    FileDescriptor fd = result.getUnownedFileDescriptor();
17135                    try {
17136                        mInstaller.installApkVerity(apkPath, fd);
17137                    } catch (InstallerException e) {
17138                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17139                                "Failed to set up verity: " + e);
17140                        return;
17141                    } finally {
17142                        IoUtils.closeQuietly(fd);
17143                    }
17144                } else if (result.isFailed()) {
17145                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17146                    return;
17147                } else {
17148                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17149                    // reboot.
17150                }
17151            }
17152        }
17153
17154        if (!instantApp) {
17155            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17156        } else {
17157            if (DEBUG_DOMAIN_VERIFICATION) {
17158                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17159            }
17160        }
17161
17162        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17163                "installPackageLI")) {
17164            if (replace) {
17165                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17166                    // Static libs have a synthetic package name containing the version
17167                    // and cannot be updated as an update would get a new package name,
17168                    // unless this is the exact same version code which is useful for
17169                    // development.
17170                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17171                    if (existingPkg != null &&
17172                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17173                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17174                                + "static-shared libs cannot be updated");
17175                        return;
17176                    }
17177                }
17178                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17179                        installerPackageName, res, args.installReason);
17180            } else {
17181                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17182                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17183            }
17184        }
17185
17186        // Prepare the application profiles for the new code paths.
17187        // This needs to be done before invoking dexopt so that any install-time profile
17188        // can be used for optimizations.
17189        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17190
17191        // Check whether we need to dexopt the app.
17192        //
17193        // NOTE: it is IMPORTANT to call dexopt:
17194        //   - after doRename which will sync the package data from PackageParser.Package and its
17195        //     corresponding ApplicationInfo.
17196        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17197        //     uid of the application (pkg.applicationInfo.uid).
17198        //     This update happens in place!
17199        //
17200        // We only need to dexopt if the package meets ALL of the following conditions:
17201        //   1) it is not forward locked.
17202        //   2) it is not on on an external ASEC container.
17203        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17204        //
17205        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17206        // complete, so we skip this step during installation. Instead, we'll take extra time
17207        // the first time the instant app starts. It's preferred to do it this way to provide
17208        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17209        // middle of running an instant app. The default behaviour can be overridden
17210        // via gservices.
17211        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17212                && !forwardLocked
17213                && !pkg.applicationInfo.isExternalAsec()
17214                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17215                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17216
17217        if (performDexopt) {
17218            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17219            // Do not run PackageDexOptimizer through the local performDexOpt
17220            // method because `pkg` may not be in `mPackages` yet.
17221            //
17222            // Also, don't fail application installs if the dexopt step fails.
17223            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17224                    REASON_INSTALL,
17225                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17226                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17227            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17228                    null /* instructionSets */,
17229                    getOrCreateCompilerPackageStats(pkg),
17230                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17231                    dexoptOptions);
17232            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17233        }
17234
17235        // Notify BackgroundDexOptService that the package has been changed.
17236        // If this is an update of a package which used to fail to compile,
17237        // BackgroundDexOptService will remove it from its blacklist.
17238        // TODO: Layering violation
17239        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17240
17241        synchronized (mPackages) {
17242            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17243            if (ps != null) {
17244                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17245                ps.setUpdateAvailable(false /*updateAvailable*/);
17246            }
17247
17248            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17249            for (int i = 0; i < childCount; i++) {
17250                PackageParser.Package childPkg = pkg.childPackages.get(i);
17251                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17252                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17253                if (childPs != null) {
17254                    childRes.newUsers = childPs.queryInstalledUsers(
17255                            sUserManager.getUserIds(), true);
17256                }
17257            }
17258
17259            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17260                updateSequenceNumberLP(ps, res.newUsers);
17261                updateInstantAppInstallerLocked(pkgName);
17262            }
17263        }
17264    }
17265
17266    private void startIntentFilterVerifications(int userId, boolean replacing,
17267            PackageParser.Package pkg) {
17268        if (mIntentFilterVerifierComponent == null) {
17269            Slog.w(TAG, "No IntentFilter verification will not be done as "
17270                    + "there is no IntentFilterVerifier available!");
17271            return;
17272        }
17273
17274        final int verifierUid = getPackageUid(
17275                mIntentFilterVerifierComponent.getPackageName(),
17276                MATCH_DEBUG_TRIAGED_MISSING,
17277                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17278
17279        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17280        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17281        mHandler.sendMessage(msg);
17282
17283        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17284        for (int i = 0; i < childCount; i++) {
17285            PackageParser.Package childPkg = pkg.childPackages.get(i);
17286            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17287            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17288            mHandler.sendMessage(msg);
17289        }
17290    }
17291
17292    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17293            PackageParser.Package pkg) {
17294        int size = pkg.activities.size();
17295        if (size == 0) {
17296            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17297                    "No activity, so no need to verify any IntentFilter!");
17298            return;
17299        }
17300
17301        final boolean hasDomainURLs = hasDomainURLs(pkg);
17302        if (!hasDomainURLs) {
17303            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17304                    "No domain URLs, so no need to verify any IntentFilter!");
17305            return;
17306        }
17307
17308        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17309                + " if any IntentFilter from the " + size
17310                + " Activities needs verification ...");
17311
17312        int count = 0;
17313        final String packageName = pkg.packageName;
17314
17315        synchronized (mPackages) {
17316            // If this is a new install and we see that we've already run verification for this
17317            // package, we have nothing to do: it means the state was restored from backup.
17318            if (!replacing) {
17319                IntentFilterVerificationInfo ivi =
17320                        mSettings.getIntentFilterVerificationLPr(packageName);
17321                if (ivi != null) {
17322                    if (DEBUG_DOMAIN_VERIFICATION) {
17323                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17324                                + ivi.getStatusString());
17325                    }
17326                    return;
17327                }
17328            }
17329
17330            // If any filters need to be verified, then all need to be.
17331            boolean needToVerify = false;
17332            for (PackageParser.Activity a : pkg.activities) {
17333                for (ActivityIntentInfo filter : a.intents) {
17334                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17335                        if (DEBUG_DOMAIN_VERIFICATION) {
17336                            Slog.d(TAG,
17337                                    "Intent filter needs verification, so processing all filters");
17338                        }
17339                        needToVerify = true;
17340                        break;
17341                    }
17342                }
17343            }
17344
17345            if (needToVerify) {
17346                final int verificationId = mIntentFilterVerificationToken++;
17347                for (PackageParser.Activity a : pkg.activities) {
17348                    for (ActivityIntentInfo filter : a.intents) {
17349                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17350                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17351                                    "Verification needed for IntentFilter:" + filter.toString());
17352                            mIntentFilterVerifier.addOneIntentFilterVerification(
17353                                    verifierUid, userId, verificationId, filter, packageName);
17354                            count++;
17355                        }
17356                    }
17357                }
17358            }
17359        }
17360
17361        if (count > 0) {
17362            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17363                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17364                    +  " for userId:" + userId);
17365            mIntentFilterVerifier.startVerifications(userId);
17366        } else {
17367            if (DEBUG_DOMAIN_VERIFICATION) {
17368                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17369            }
17370        }
17371    }
17372
17373    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17374        final ComponentName cn  = filter.activity.getComponentName();
17375        final String packageName = cn.getPackageName();
17376
17377        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17378                packageName);
17379        if (ivi == null) {
17380            return true;
17381        }
17382        int status = ivi.getStatus();
17383        switch (status) {
17384            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17385            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17386                return true;
17387
17388            default:
17389                // Nothing to do
17390                return false;
17391        }
17392    }
17393
17394    private static boolean isMultiArch(ApplicationInfo info) {
17395        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17396    }
17397
17398    private static boolean isExternal(PackageParser.Package pkg) {
17399        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17400    }
17401
17402    private static boolean isExternal(PackageSetting ps) {
17403        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17404    }
17405
17406    private static boolean isSystemApp(PackageParser.Package pkg) {
17407        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17408    }
17409
17410    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17411        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17412    }
17413
17414    private static boolean isOemApp(PackageParser.Package pkg) {
17415        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17416    }
17417
17418    private static boolean isVendorApp(PackageParser.Package pkg) {
17419        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17420    }
17421
17422    private static boolean isProductApp(PackageParser.Package pkg) {
17423        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17424    }
17425
17426    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17427        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17428    }
17429
17430    private static boolean isSystemApp(PackageSetting ps) {
17431        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17432    }
17433
17434    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17435        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17436    }
17437
17438    private int packageFlagsToInstallFlags(PackageSetting ps) {
17439        int installFlags = 0;
17440        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17441            // This existing package was an external ASEC install when we have
17442            // the external flag without a UUID
17443            installFlags |= PackageManager.INSTALL_EXTERNAL;
17444        }
17445        if (ps.isForwardLocked()) {
17446            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17447        }
17448        return installFlags;
17449    }
17450
17451    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17452        if (isExternal(pkg)) {
17453            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17454                return mSettings.getExternalVersion();
17455            } else {
17456                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17457            }
17458        } else {
17459            return mSettings.getInternalVersion();
17460        }
17461    }
17462
17463    private void deleteTempPackageFiles() {
17464        final FilenameFilter filter = new FilenameFilter() {
17465            public boolean accept(File dir, String name) {
17466                return name.startsWith("vmdl") && name.endsWith(".tmp");
17467            }
17468        };
17469        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17470            file.delete();
17471        }
17472    }
17473
17474    @Override
17475    public void deletePackageAsUser(String packageName, int versionCode,
17476            IPackageDeleteObserver observer, int userId, int flags) {
17477        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17478                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17479    }
17480
17481    @Override
17482    public void deletePackageVersioned(VersionedPackage versionedPackage,
17483            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17484        final int callingUid = Binder.getCallingUid();
17485        mContext.enforceCallingOrSelfPermission(
17486                android.Manifest.permission.DELETE_PACKAGES, null);
17487        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17488        Preconditions.checkNotNull(versionedPackage);
17489        Preconditions.checkNotNull(observer);
17490        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17491                PackageManager.VERSION_CODE_HIGHEST,
17492                Long.MAX_VALUE, "versionCode must be >= -1");
17493
17494        final String packageName = versionedPackage.getPackageName();
17495        final long versionCode = versionedPackage.getLongVersionCode();
17496        final String internalPackageName;
17497        synchronized (mPackages) {
17498            // Normalize package name to handle renamed packages and static libs
17499            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17500        }
17501
17502        final int uid = Binder.getCallingUid();
17503        if (!isOrphaned(internalPackageName)
17504                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17505            try {
17506                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17507                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17508                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17509                observer.onUserActionRequired(intent);
17510            } catch (RemoteException re) {
17511            }
17512            return;
17513        }
17514        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17515        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17516        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17517            mContext.enforceCallingOrSelfPermission(
17518                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17519                    "deletePackage for user " + userId);
17520        }
17521
17522        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17523            try {
17524                observer.onPackageDeleted(packageName,
17525                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17526            } catch (RemoteException re) {
17527            }
17528            return;
17529        }
17530
17531        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17532            try {
17533                observer.onPackageDeleted(packageName,
17534                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17535            } catch (RemoteException re) {
17536            }
17537            return;
17538        }
17539
17540        if (DEBUG_REMOVE) {
17541            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17542                    + " deleteAllUsers: " + deleteAllUsers + " version="
17543                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17544                    ? "VERSION_CODE_HIGHEST" : versionCode));
17545        }
17546        // Queue up an async operation since the package deletion may take a little while.
17547        mHandler.post(new Runnable() {
17548            public void run() {
17549                mHandler.removeCallbacks(this);
17550                int returnCode;
17551                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17552                boolean doDeletePackage = true;
17553                if (ps != null) {
17554                    final boolean targetIsInstantApp =
17555                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17556                    doDeletePackage = !targetIsInstantApp
17557                            || canViewInstantApps;
17558                }
17559                if (doDeletePackage) {
17560                    if (!deleteAllUsers) {
17561                        returnCode = deletePackageX(internalPackageName, versionCode,
17562                                userId, deleteFlags);
17563                    } else {
17564                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17565                                internalPackageName, users);
17566                        // If nobody is blocking uninstall, proceed with delete for all users
17567                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17568                            returnCode = deletePackageX(internalPackageName, versionCode,
17569                                    userId, deleteFlags);
17570                        } else {
17571                            // Otherwise uninstall individually for users with blockUninstalls=false
17572                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17573                            for (int userId : users) {
17574                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17575                                    returnCode = deletePackageX(internalPackageName, versionCode,
17576                                            userId, userFlags);
17577                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17578                                        Slog.w(TAG, "Package delete failed for user " + userId
17579                                                + ", returnCode " + returnCode);
17580                                    }
17581                                }
17582                            }
17583                            // The app has only been marked uninstalled for certain users.
17584                            // We still need to report that delete was blocked
17585                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17586                        }
17587                    }
17588                } else {
17589                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17590                }
17591                try {
17592                    observer.onPackageDeleted(packageName, returnCode, null);
17593                } catch (RemoteException e) {
17594                    Log.i(TAG, "Observer no longer exists.");
17595                } //end catch
17596            } //end run
17597        });
17598    }
17599
17600    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17601        if (pkg.staticSharedLibName != null) {
17602            return pkg.manifestPackageName;
17603        }
17604        return pkg.packageName;
17605    }
17606
17607    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17608        // Handle renamed packages
17609        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17610        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17611
17612        // Is this a static library?
17613        LongSparseArray<SharedLibraryEntry> versionedLib =
17614                mStaticLibsByDeclaringPackage.get(packageName);
17615        if (versionedLib == null || versionedLib.size() <= 0) {
17616            return packageName;
17617        }
17618
17619        // Figure out which lib versions the caller can see
17620        LongSparseLongArray versionsCallerCanSee = null;
17621        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17622        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17623                && callingAppId != Process.ROOT_UID) {
17624            versionsCallerCanSee = new LongSparseLongArray();
17625            String libName = versionedLib.valueAt(0).info.getName();
17626            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17627            if (uidPackages != null) {
17628                for (String uidPackage : uidPackages) {
17629                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17630                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17631                    if (libIdx >= 0) {
17632                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17633                        versionsCallerCanSee.append(libVersion, libVersion);
17634                    }
17635                }
17636            }
17637        }
17638
17639        // Caller can see nothing - done
17640        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17641            return packageName;
17642        }
17643
17644        // Find the version the caller can see and the app version code
17645        SharedLibraryEntry highestVersion = null;
17646        final int versionCount = versionedLib.size();
17647        for (int i = 0; i < versionCount; i++) {
17648            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17649            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17650                    libEntry.info.getLongVersion()) < 0) {
17651                continue;
17652            }
17653            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17654            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17655                if (libVersionCode == versionCode) {
17656                    return libEntry.apk;
17657                }
17658            } else if (highestVersion == null) {
17659                highestVersion = libEntry;
17660            } else if (libVersionCode  > highestVersion.info
17661                    .getDeclaringPackage().getLongVersionCode()) {
17662                highestVersion = libEntry;
17663            }
17664        }
17665
17666        if (highestVersion != null) {
17667            return highestVersion.apk;
17668        }
17669
17670        return packageName;
17671    }
17672
17673    boolean isCallerVerifier(int callingUid) {
17674        final int callingUserId = UserHandle.getUserId(callingUid);
17675        return mRequiredVerifierPackage != null &&
17676                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17677    }
17678
17679    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17680        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17681              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17682            return true;
17683        }
17684        final int callingUserId = UserHandle.getUserId(callingUid);
17685        // If the caller installed the pkgName, then allow it to silently uninstall.
17686        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17687            return true;
17688        }
17689
17690        // Allow package verifier to silently uninstall.
17691        if (mRequiredVerifierPackage != null &&
17692                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17693            return true;
17694        }
17695
17696        // Allow package uninstaller to silently uninstall.
17697        if (mRequiredUninstallerPackage != null &&
17698                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17699            return true;
17700        }
17701
17702        // Allow storage manager to silently uninstall.
17703        if (mStorageManagerPackage != null &&
17704                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17705            return true;
17706        }
17707
17708        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17709        // uninstall for device owner provisioning.
17710        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17711                == PERMISSION_GRANTED) {
17712            return true;
17713        }
17714
17715        return false;
17716    }
17717
17718    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17719        int[] result = EMPTY_INT_ARRAY;
17720        for (int userId : userIds) {
17721            if (getBlockUninstallForUser(packageName, userId)) {
17722                result = ArrayUtils.appendInt(result, userId);
17723            }
17724        }
17725        return result;
17726    }
17727
17728    @Override
17729    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17730        final int callingUid = Binder.getCallingUid();
17731        if (getInstantAppPackageName(callingUid) != null
17732                && !isCallerSameApp(packageName, callingUid)) {
17733            return false;
17734        }
17735        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17736    }
17737
17738    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17739        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17740                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17741        try {
17742            if (dpm != null) {
17743                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17744                        /* callingUserOnly =*/ false);
17745                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17746                        : deviceOwnerComponentName.getPackageName();
17747                // Does the package contains the device owner?
17748                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17749                // this check is probably not needed, since DO should be registered as a device
17750                // admin on some user too. (Original bug for this: b/17657954)
17751                if (packageName.equals(deviceOwnerPackageName)) {
17752                    return true;
17753                }
17754                // Does it contain a device admin for any user?
17755                int[] users;
17756                if (userId == UserHandle.USER_ALL) {
17757                    users = sUserManager.getUserIds();
17758                } else {
17759                    users = new int[]{userId};
17760                }
17761                for (int i = 0; i < users.length; ++i) {
17762                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17763                        return true;
17764                    }
17765                }
17766            }
17767        } catch (RemoteException e) {
17768        }
17769        return false;
17770    }
17771
17772    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17773        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17774    }
17775
17776    /**
17777     *  This method is an internal method that could be get invoked either
17778     *  to delete an installed package or to clean up a failed installation.
17779     *  After deleting an installed package, a broadcast is sent to notify any
17780     *  listeners that the package has been removed. For cleaning up a failed
17781     *  installation, the broadcast is not necessary since the package's
17782     *  installation wouldn't have sent the initial broadcast either
17783     *  The key steps in deleting a package are
17784     *  deleting the package information in internal structures like mPackages,
17785     *  deleting the packages base directories through installd
17786     *  updating mSettings to reflect current status
17787     *  persisting settings for later use
17788     *  sending a broadcast if necessary
17789     */
17790    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17791        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17792        final boolean res;
17793
17794        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17795                ? UserHandle.USER_ALL : userId;
17796
17797        if (isPackageDeviceAdmin(packageName, removeUser)) {
17798            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17799            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17800        }
17801
17802        PackageSetting uninstalledPs = null;
17803        PackageParser.Package pkg = null;
17804
17805        // for the uninstall-updates case and restricted profiles, remember the per-
17806        // user handle installed state
17807        int[] allUsers;
17808        synchronized (mPackages) {
17809            uninstalledPs = mSettings.mPackages.get(packageName);
17810            if (uninstalledPs == null) {
17811                Slog.w(TAG, "Not removing non-existent package " + packageName);
17812                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17813            }
17814
17815            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17816                    && uninstalledPs.versionCode != versionCode) {
17817                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17818                        + uninstalledPs.versionCode + " != " + versionCode);
17819                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17820            }
17821
17822            // Static shared libs can be declared by any package, so let us not
17823            // allow removing a package if it provides a lib others depend on.
17824            pkg = mPackages.get(packageName);
17825
17826            allUsers = sUserManager.getUserIds();
17827
17828            if (pkg != null && pkg.staticSharedLibName != null) {
17829                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17830                        pkg.staticSharedLibVersion);
17831                if (libEntry != null) {
17832                    for (int currUserId : allUsers) {
17833                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17834                            continue;
17835                        }
17836                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17837                                libEntry.info, 0, currUserId);
17838                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17839                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17840                                    + " hosting lib " + libEntry.info.getName() + " version "
17841                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
17842                                    + " for user " + currUserId);
17843                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17844                        }
17845                    }
17846                }
17847            }
17848
17849            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17850        }
17851
17852        final int freezeUser;
17853        if (isUpdatedSystemApp(uninstalledPs)
17854                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17855            // We're downgrading a system app, which will apply to all users, so
17856            // freeze them all during the downgrade
17857            freezeUser = UserHandle.USER_ALL;
17858        } else {
17859            freezeUser = removeUser;
17860        }
17861
17862        synchronized (mInstallLock) {
17863            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17864            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17865                    deleteFlags, "deletePackageX")) {
17866                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17867                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
17868            }
17869            synchronized (mPackages) {
17870                if (res) {
17871                    if (pkg != null) {
17872                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17873                    }
17874                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
17875                    updateInstantAppInstallerLocked(packageName);
17876                }
17877            }
17878        }
17879
17880        if (res) {
17881            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17882            info.sendPackageRemovedBroadcasts(killApp);
17883            info.sendSystemPackageUpdatedBroadcasts();
17884            info.sendSystemPackageAppearedBroadcasts();
17885        }
17886        // Force a gc here.
17887        Runtime.getRuntime().gc();
17888        // Delete the resources here after sending the broadcast to let
17889        // other processes clean up before deleting resources.
17890        if (info.args != null) {
17891            synchronized (mInstallLock) {
17892                info.args.doPostDeleteLI(true);
17893            }
17894        }
17895
17896        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17897    }
17898
17899    static class PackageRemovedInfo {
17900        final PackageSender packageSender;
17901        String removedPackage;
17902        String installerPackageName;
17903        int uid = -1;
17904        int removedAppId = -1;
17905        int[] origUsers;
17906        int[] removedUsers = null;
17907        int[] broadcastUsers = null;
17908        int[] instantUserIds = null;
17909        SparseArray<Integer> installReasons;
17910        boolean isRemovedPackageSystemUpdate = false;
17911        boolean isUpdate;
17912        boolean dataRemoved;
17913        boolean removedForAllUsers;
17914        boolean isStaticSharedLib;
17915        // Clean up resources deleted packages.
17916        InstallArgs args = null;
17917        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17918        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17919
17920        PackageRemovedInfo(PackageSender packageSender) {
17921            this.packageSender = packageSender;
17922        }
17923
17924        void sendPackageRemovedBroadcasts(boolean killApp) {
17925            sendPackageRemovedBroadcastInternal(killApp);
17926            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17927            for (int i = 0; i < childCount; i++) {
17928                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17929                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17930            }
17931        }
17932
17933        void sendSystemPackageUpdatedBroadcasts() {
17934            if (isRemovedPackageSystemUpdate) {
17935                sendSystemPackageUpdatedBroadcastsInternal();
17936                final int childCount = (removedChildPackages != null)
17937                        ? removedChildPackages.size() : 0;
17938                for (int i = 0; i < childCount; i++) {
17939                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17940                    if (childInfo.isRemovedPackageSystemUpdate) {
17941                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17942                    }
17943                }
17944            }
17945        }
17946
17947        void sendSystemPackageAppearedBroadcasts() {
17948            final int packageCount = (appearedChildPackages != null)
17949                    ? appearedChildPackages.size() : 0;
17950            for (int i = 0; i < packageCount; i++) {
17951                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17952                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
17953                    true /*sendBootCompleted*/, false /*startReceiver*/,
17954                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
17955            }
17956        }
17957
17958        private void sendSystemPackageUpdatedBroadcastsInternal() {
17959            Bundle extras = new Bundle(2);
17960            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17961            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17962            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17963                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17964            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17965                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17966            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
17967                null, null, 0, removedPackage, null, null, null);
17968            if (installerPackageName != null) {
17969                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17970                        removedPackage, extras, 0 /*flags*/,
17971                        installerPackageName, null, null, null);
17972                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17973                        removedPackage, extras, 0 /*flags*/,
17974                        installerPackageName, null, null, null);
17975            }
17976        }
17977
17978        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17979            // Don't send static shared library removal broadcasts as these
17980            // libs are visible only the the apps that depend on them an one
17981            // cannot remove the library if it has a dependency.
17982            if (isStaticSharedLib) {
17983                return;
17984            }
17985            Bundle extras = new Bundle(2);
17986            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17987            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17988            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17989            if (isUpdate || isRemovedPackageSystemUpdate) {
17990                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17991            }
17992            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17993            if (removedPackage != null) {
17994                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17995                    removedPackage, extras, 0, null /*targetPackage*/, null,
17996                    broadcastUsers, instantUserIds);
17997                if (installerPackageName != null) {
17998                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17999                            removedPackage, extras, 0 /*flags*/,
18000                            installerPackageName, null, broadcastUsers, instantUserIds);
18001                }
18002                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18003                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18004                        removedPackage, extras,
18005                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18006                        null, null, broadcastUsers, instantUserIds);
18007                    packageSender.notifyPackageRemoved(removedPackage);
18008                }
18009            }
18010            if (removedAppId >= 0) {
18011                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18012                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18013                    null, null, broadcastUsers, instantUserIds);
18014            }
18015        }
18016
18017        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18018            removedUsers = userIds;
18019            if (removedUsers == null) {
18020                broadcastUsers = null;
18021                return;
18022            }
18023
18024            broadcastUsers = EMPTY_INT_ARRAY;
18025            instantUserIds = EMPTY_INT_ARRAY;
18026            for (int i = userIds.length - 1; i >= 0; --i) {
18027                final int userId = userIds[i];
18028                if (deletedPackageSetting.getInstantApp(userId)) {
18029                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18030                } else {
18031                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18032                }
18033            }
18034        }
18035    }
18036
18037    /*
18038     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18039     * flag is not set, the data directory is removed as well.
18040     * make sure this flag is set for partially installed apps. If not its meaningless to
18041     * delete a partially installed application.
18042     */
18043    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18044            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18045        String packageName = ps.name;
18046        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18047        // Retrieve object to delete permissions for shared user later on
18048        final PackageParser.Package deletedPkg;
18049        final PackageSetting deletedPs;
18050        // reader
18051        synchronized (mPackages) {
18052            deletedPkg = mPackages.get(packageName);
18053            deletedPs = mSettings.mPackages.get(packageName);
18054            if (outInfo != null) {
18055                outInfo.removedPackage = packageName;
18056                outInfo.installerPackageName = ps.installerPackageName;
18057                outInfo.isStaticSharedLib = deletedPkg != null
18058                        && deletedPkg.staticSharedLibName != null;
18059                outInfo.populateUsers(deletedPs == null ? null
18060                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18061            }
18062        }
18063
18064        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18065
18066        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18067            final PackageParser.Package resolvedPkg;
18068            if (deletedPkg != null) {
18069                resolvedPkg = deletedPkg;
18070            } else {
18071                // We don't have a parsed package when it lives on an ejected
18072                // adopted storage device, so fake something together
18073                resolvedPkg = new PackageParser.Package(ps.name);
18074                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18075            }
18076            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18077                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18078            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18079            if (outInfo != null) {
18080                outInfo.dataRemoved = true;
18081            }
18082            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18083        }
18084
18085        int removedAppId = -1;
18086
18087        // writer
18088        synchronized (mPackages) {
18089            boolean installedStateChanged = false;
18090            if (deletedPs != null) {
18091                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18092                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18093                    clearDefaultBrowserIfNeeded(packageName);
18094                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18095                    removedAppId = mSettings.removePackageLPw(packageName);
18096                    if (outInfo != null) {
18097                        outInfo.removedAppId = removedAppId;
18098                    }
18099                    mPermissionManager.updatePermissions(
18100                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18101                    if (deletedPs.sharedUser != null) {
18102                        // Remove permissions associated with package. Since runtime
18103                        // permissions are per user we have to kill the removed package
18104                        // or packages running under the shared user of the removed
18105                        // package if revoking the permissions requested only by the removed
18106                        // package is successful and this causes a change in gids.
18107                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18108                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18109                                    userId);
18110                            if (userIdToKill == UserHandle.USER_ALL
18111                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18112                                // If gids changed for this user, kill all affected packages.
18113                                mHandler.post(new Runnable() {
18114                                    @Override
18115                                    public void run() {
18116                                        // This has to happen with no lock held.
18117                                        killApplication(deletedPs.name, deletedPs.appId,
18118                                                KILL_APP_REASON_GIDS_CHANGED);
18119                                    }
18120                                });
18121                                break;
18122                            }
18123                        }
18124                    }
18125                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18126                }
18127                // make sure to preserve per-user disabled state if this removal was just
18128                // a downgrade of a system app to the factory package
18129                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18130                    if (DEBUG_REMOVE) {
18131                        Slog.d(TAG, "Propagating install state across downgrade");
18132                    }
18133                    for (int userId : allUserHandles) {
18134                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18135                        if (DEBUG_REMOVE) {
18136                            Slog.d(TAG, "    user " + userId + " => " + installed);
18137                        }
18138                        if (installed != ps.getInstalled(userId)) {
18139                            installedStateChanged = true;
18140                        }
18141                        ps.setInstalled(installed, userId);
18142                    }
18143                }
18144            }
18145            // can downgrade to reader
18146            if (writeSettings) {
18147                // Save settings now
18148                mSettings.writeLPr();
18149            }
18150            if (installedStateChanged) {
18151                mSettings.writeKernelMappingLPr(ps);
18152            }
18153        }
18154        if (removedAppId != -1) {
18155            // A user ID was deleted here. Go through all users and remove it
18156            // from KeyStore.
18157            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18158        }
18159    }
18160
18161    static boolean locationIsPrivileged(String path) {
18162        try {
18163            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18164            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18165            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18166            return path.startsWith(privilegedAppDir.getCanonicalPath())
18167                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18168                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18169        } catch (IOException e) {
18170            Slog.e(TAG, "Unable to access code path " + path);
18171        }
18172        return false;
18173    }
18174
18175    static boolean locationIsOem(String path) {
18176        try {
18177            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18178        } catch (IOException e) {
18179            Slog.e(TAG, "Unable to access code path " + path);
18180        }
18181        return false;
18182    }
18183
18184    static boolean locationIsVendor(String path) {
18185        try {
18186            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath());
18187        } catch (IOException e) {
18188            Slog.e(TAG, "Unable to access code path " + path);
18189        }
18190        return false;
18191    }
18192
18193    static boolean locationIsProduct(String path) {
18194        try {
18195            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18196        } catch (IOException e) {
18197            Slog.e(TAG, "Unable to access code path " + path);
18198        }
18199        return false;
18200    }
18201
18202    /*
18203     * Tries to delete system package.
18204     */
18205    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18206            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18207            boolean writeSettings) {
18208        if (deletedPs.parentPackageName != null) {
18209            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18210            return false;
18211        }
18212
18213        final boolean applyUserRestrictions
18214                = (allUserHandles != null) && (outInfo.origUsers != null);
18215        final PackageSetting disabledPs;
18216        // Confirm if the system package has been updated
18217        // An updated system app can be deleted. This will also have to restore
18218        // the system pkg from system partition
18219        // reader
18220        synchronized (mPackages) {
18221            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18222        }
18223
18224        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18225                + " disabledPs=" + disabledPs);
18226
18227        if (disabledPs == null) {
18228            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18229            return false;
18230        } else if (DEBUG_REMOVE) {
18231            Slog.d(TAG, "Deleting system pkg from data partition");
18232        }
18233
18234        if (DEBUG_REMOVE) {
18235            if (applyUserRestrictions) {
18236                Slog.d(TAG, "Remembering install states:");
18237                for (int userId : allUserHandles) {
18238                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18239                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18240                }
18241            }
18242        }
18243
18244        // Delete the updated package
18245        outInfo.isRemovedPackageSystemUpdate = true;
18246        if (outInfo.removedChildPackages != null) {
18247            final int childCount = (deletedPs.childPackageNames != null)
18248                    ? deletedPs.childPackageNames.size() : 0;
18249            for (int i = 0; i < childCount; i++) {
18250                String childPackageName = deletedPs.childPackageNames.get(i);
18251                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18252                        .contains(childPackageName)) {
18253                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18254                            childPackageName);
18255                    if (childInfo != null) {
18256                        childInfo.isRemovedPackageSystemUpdate = true;
18257                    }
18258                }
18259            }
18260        }
18261
18262        if (disabledPs.versionCode < deletedPs.versionCode) {
18263            // Delete data for downgrades
18264            flags &= ~PackageManager.DELETE_KEEP_DATA;
18265        } else {
18266            // Preserve data by setting flag
18267            flags |= PackageManager.DELETE_KEEP_DATA;
18268        }
18269
18270        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18271                outInfo, writeSettings, disabledPs.pkg);
18272        if (!ret) {
18273            return false;
18274        }
18275
18276        // writer
18277        synchronized (mPackages) {
18278            // NOTE: The system package always needs to be enabled; even if it's for
18279            // a compressed stub. If we don't, installing the system package fails
18280            // during scan [scanning checks the disabled packages]. We will reverse
18281            // this later, after we've "installed" the stub.
18282            // Reinstate the old system package
18283            enableSystemPackageLPw(disabledPs.pkg);
18284            // Remove any native libraries from the upgraded package.
18285            removeNativeBinariesLI(deletedPs);
18286        }
18287
18288        // Install the system package
18289        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18290        try {
18291            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18292                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18293        } catch (PackageManagerException e) {
18294            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18295                    + e.getMessage());
18296            return false;
18297        } finally {
18298            if (disabledPs.pkg.isStub) {
18299                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18300            }
18301        }
18302        return true;
18303    }
18304
18305    /**
18306     * Installs a package that's already on the system partition.
18307     */
18308    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18309            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18310            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18311                    throws PackageManagerException {
18312        @ParseFlags int parseFlags =
18313                mDefParseFlags
18314                | PackageParser.PARSE_MUST_BE_APK
18315                | PackageParser.PARSE_IS_SYSTEM_DIR;
18316        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18317        if (isPrivileged || locationIsPrivileged(codePathString)) {
18318            scanFlags |= SCAN_AS_PRIVILEGED;
18319        }
18320        if (locationIsOem(codePathString)) {
18321            scanFlags |= SCAN_AS_OEM;
18322        }
18323        if (locationIsVendor(codePathString)) {
18324            scanFlags |= SCAN_AS_VENDOR;
18325        }
18326        if (locationIsProduct(codePathString)) {
18327            scanFlags |= SCAN_AS_PRODUCT;
18328        }
18329
18330        final File codePath = new File(codePathString);
18331        final PackageParser.Package pkg =
18332                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18333
18334        try {
18335            // update shared libraries for the newly re-installed system package
18336            updateSharedLibrariesLPr(pkg, null);
18337        } catch (PackageManagerException e) {
18338            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18339        }
18340
18341        prepareAppDataAfterInstallLIF(pkg);
18342
18343        // writer
18344        synchronized (mPackages) {
18345            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18346
18347            // Propagate the permissions state as we do not want to drop on the floor
18348            // runtime permissions. The update permissions method below will take
18349            // care of removing obsolete permissions and grant install permissions.
18350            if (origPermissionState != null) {
18351                ps.getPermissionsState().copyFrom(origPermissionState);
18352            }
18353            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18354                    mPermissionCallback);
18355
18356            final boolean applyUserRestrictions
18357                    = (allUserHandles != null) && (origUserHandles != null);
18358            if (applyUserRestrictions) {
18359                boolean installedStateChanged = false;
18360                if (DEBUG_REMOVE) {
18361                    Slog.d(TAG, "Propagating install state across reinstall");
18362                }
18363                for (int userId : allUserHandles) {
18364                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18365                    if (DEBUG_REMOVE) {
18366                        Slog.d(TAG, "    user " + userId + " => " + installed);
18367                    }
18368                    if (installed != ps.getInstalled(userId)) {
18369                        installedStateChanged = true;
18370                    }
18371                    ps.setInstalled(installed, userId);
18372
18373                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18374                }
18375                // Regardless of writeSettings we need to ensure that this restriction
18376                // state propagation is persisted
18377                mSettings.writeAllUsersPackageRestrictionsLPr();
18378                if (installedStateChanged) {
18379                    mSettings.writeKernelMappingLPr(ps);
18380                }
18381            }
18382            // can downgrade to reader here
18383            if (writeSettings) {
18384                mSettings.writeLPr();
18385            }
18386        }
18387        return pkg;
18388    }
18389
18390    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18391            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18392            PackageRemovedInfo outInfo, boolean writeSettings,
18393            PackageParser.Package replacingPackage) {
18394        synchronized (mPackages) {
18395            if (outInfo != null) {
18396                outInfo.uid = ps.appId;
18397            }
18398
18399            if (outInfo != null && outInfo.removedChildPackages != null) {
18400                final int childCount = (ps.childPackageNames != null)
18401                        ? ps.childPackageNames.size() : 0;
18402                for (int i = 0; i < childCount; i++) {
18403                    String childPackageName = ps.childPackageNames.get(i);
18404                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18405                    if (childPs == null) {
18406                        return false;
18407                    }
18408                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18409                            childPackageName);
18410                    if (childInfo != null) {
18411                        childInfo.uid = childPs.appId;
18412                    }
18413                }
18414            }
18415        }
18416
18417        // Delete package data from internal structures and also remove data if flag is set
18418        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18419
18420        // Delete the child packages data
18421        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18422        for (int i = 0; i < childCount; i++) {
18423            PackageSetting childPs;
18424            synchronized (mPackages) {
18425                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18426            }
18427            if (childPs != null) {
18428                PackageRemovedInfo childOutInfo = (outInfo != null
18429                        && outInfo.removedChildPackages != null)
18430                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18431                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18432                        && (replacingPackage != null
18433                        && !replacingPackage.hasChildPackage(childPs.name))
18434                        ? flags & ~DELETE_KEEP_DATA : flags;
18435                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18436                        deleteFlags, writeSettings);
18437            }
18438        }
18439
18440        // Delete application code and resources only for parent packages
18441        if (ps.parentPackageName == null) {
18442            if (deleteCodeAndResources && (outInfo != null)) {
18443                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18444                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18445                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18446            }
18447        }
18448
18449        return true;
18450    }
18451
18452    @Override
18453    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18454            int userId) {
18455        mContext.enforceCallingOrSelfPermission(
18456                android.Manifest.permission.DELETE_PACKAGES, null);
18457        synchronized (mPackages) {
18458            // Cannot block uninstall of static shared libs as they are
18459            // considered a part of the using app (emulating static linking).
18460            // Also static libs are installed always on internal storage.
18461            PackageParser.Package pkg = mPackages.get(packageName);
18462            if (pkg != null && pkg.staticSharedLibName != null) {
18463                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18464                        + " providing static shared library: " + pkg.staticSharedLibName);
18465                return false;
18466            }
18467            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18468            mSettings.writePackageRestrictionsLPr(userId);
18469        }
18470        return true;
18471    }
18472
18473    @Override
18474    public boolean getBlockUninstallForUser(String packageName, int userId) {
18475        synchronized (mPackages) {
18476            final PackageSetting ps = mSettings.mPackages.get(packageName);
18477            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18478                return false;
18479            }
18480            return mSettings.getBlockUninstallLPr(userId, packageName);
18481        }
18482    }
18483
18484    @Override
18485    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18486        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18487        synchronized (mPackages) {
18488            PackageSetting ps = mSettings.mPackages.get(packageName);
18489            if (ps == null) {
18490                Log.w(TAG, "Package doesn't exist: " + packageName);
18491                return false;
18492            }
18493            if (systemUserApp) {
18494                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18495            } else {
18496                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18497            }
18498            mSettings.writeLPr();
18499        }
18500        return true;
18501    }
18502
18503    /*
18504     * This method handles package deletion in general
18505     */
18506    private boolean deletePackageLIF(String packageName, UserHandle user,
18507            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18508            PackageRemovedInfo outInfo, boolean writeSettings,
18509            PackageParser.Package replacingPackage) {
18510        if (packageName == null) {
18511            Slog.w(TAG, "Attempt to delete null packageName.");
18512            return false;
18513        }
18514
18515        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18516
18517        PackageSetting ps;
18518        synchronized (mPackages) {
18519            ps = mSettings.mPackages.get(packageName);
18520            if (ps == null) {
18521                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18522                return false;
18523            }
18524
18525            if (ps.parentPackageName != null && (!isSystemApp(ps)
18526                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18527                if (DEBUG_REMOVE) {
18528                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18529                            + ((user == null) ? UserHandle.USER_ALL : user));
18530                }
18531                final int removedUserId = (user != null) ? user.getIdentifier()
18532                        : UserHandle.USER_ALL;
18533                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18534                    return false;
18535                }
18536                markPackageUninstalledForUserLPw(ps, user);
18537                scheduleWritePackageRestrictionsLocked(user);
18538                return true;
18539            }
18540        }
18541
18542        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18543                && user.getIdentifier() != UserHandle.USER_ALL)) {
18544            // The caller is asking that the package only be deleted for a single
18545            // user.  To do this, we just mark its uninstalled state and delete
18546            // its data. If this is a system app, we only allow this to happen if
18547            // they have set the special DELETE_SYSTEM_APP which requests different
18548            // semantics than normal for uninstalling system apps.
18549            markPackageUninstalledForUserLPw(ps, user);
18550
18551            if (!isSystemApp(ps)) {
18552                // Do not uninstall the APK if an app should be cached
18553                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18554                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18555                    // Other user still have this package installed, so all
18556                    // we need to do is clear this user's data and save that
18557                    // it is uninstalled.
18558                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18559                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18560                        return false;
18561                    }
18562                    scheduleWritePackageRestrictionsLocked(user);
18563                    return true;
18564                } else {
18565                    // We need to set it back to 'installed' so the uninstall
18566                    // broadcasts will be sent correctly.
18567                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18568                    ps.setInstalled(true, user.getIdentifier());
18569                    mSettings.writeKernelMappingLPr(ps);
18570                }
18571            } else {
18572                // This is a system app, so we assume that the
18573                // other users still have this package installed, so all
18574                // we need to do is clear this user's data and save that
18575                // it is uninstalled.
18576                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18577                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18578                    return false;
18579                }
18580                scheduleWritePackageRestrictionsLocked(user);
18581                return true;
18582            }
18583        }
18584
18585        // If we are deleting a composite package for all users, keep track
18586        // of result for each child.
18587        if (ps.childPackageNames != null && outInfo != null) {
18588            synchronized (mPackages) {
18589                final int childCount = ps.childPackageNames.size();
18590                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18591                for (int i = 0; i < childCount; i++) {
18592                    String childPackageName = ps.childPackageNames.get(i);
18593                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18594                    childInfo.removedPackage = childPackageName;
18595                    childInfo.installerPackageName = ps.installerPackageName;
18596                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18597                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18598                    if (childPs != null) {
18599                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18600                    }
18601                }
18602            }
18603        }
18604
18605        boolean ret = false;
18606        if (isSystemApp(ps)) {
18607            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18608            // When an updated system application is deleted we delete the existing resources
18609            // as well and fall back to existing code in system partition
18610            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18611        } else {
18612            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18613            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18614                    outInfo, writeSettings, replacingPackage);
18615        }
18616
18617        // Take a note whether we deleted the package for all users
18618        if (outInfo != null) {
18619            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18620            if (outInfo.removedChildPackages != null) {
18621                synchronized (mPackages) {
18622                    final int childCount = outInfo.removedChildPackages.size();
18623                    for (int i = 0; i < childCount; i++) {
18624                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18625                        if (childInfo != null) {
18626                            childInfo.removedForAllUsers = mPackages.get(
18627                                    childInfo.removedPackage) == null;
18628                        }
18629                    }
18630                }
18631            }
18632            // If we uninstalled an update to a system app there may be some
18633            // child packages that appeared as they are declared in the system
18634            // app but were not declared in the update.
18635            if (isSystemApp(ps)) {
18636                synchronized (mPackages) {
18637                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18638                    final int childCount = (updatedPs.childPackageNames != null)
18639                            ? updatedPs.childPackageNames.size() : 0;
18640                    for (int i = 0; i < childCount; i++) {
18641                        String childPackageName = updatedPs.childPackageNames.get(i);
18642                        if (outInfo.removedChildPackages == null
18643                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18644                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18645                            if (childPs == null) {
18646                                continue;
18647                            }
18648                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18649                            installRes.name = childPackageName;
18650                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18651                            installRes.pkg = mPackages.get(childPackageName);
18652                            installRes.uid = childPs.pkg.applicationInfo.uid;
18653                            if (outInfo.appearedChildPackages == null) {
18654                                outInfo.appearedChildPackages = new ArrayMap<>();
18655                            }
18656                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18657                        }
18658                    }
18659                }
18660            }
18661        }
18662
18663        return ret;
18664    }
18665
18666    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18667        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18668                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18669        for (int nextUserId : userIds) {
18670            if (DEBUG_REMOVE) {
18671                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18672            }
18673            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18674                    false /*installed*/,
18675                    true /*stopped*/,
18676                    true /*notLaunched*/,
18677                    false /*hidden*/,
18678                    false /*suspended*/,
18679                    false /*instantApp*/,
18680                    false /*virtualPreload*/,
18681                    null /*lastDisableAppCaller*/,
18682                    null /*enabledComponents*/,
18683                    null /*disabledComponents*/,
18684                    ps.readUserState(nextUserId).domainVerificationStatus,
18685                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18686                    null /*harmfulAppWarning*/);
18687        }
18688        mSettings.writeKernelMappingLPr(ps);
18689    }
18690
18691    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18692            PackageRemovedInfo outInfo) {
18693        final PackageParser.Package pkg;
18694        synchronized (mPackages) {
18695            pkg = mPackages.get(ps.name);
18696        }
18697
18698        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18699                : new int[] {userId};
18700        for (int nextUserId : userIds) {
18701            if (DEBUG_REMOVE) {
18702                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18703                        + nextUserId);
18704            }
18705
18706            destroyAppDataLIF(pkg, userId,
18707                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18708            destroyAppProfilesLIF(pkg, userId);
18709            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18710            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18711            schedulePackageCleaning(ps.name, nextUserId, false);
18712            synchronized (mPackages) {
18713                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18714                    scheduleWritePackageRestrictionsLocked(nextUserId);
18715                }
18716                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18717            }
18718        }
18719
18720        if (outInfo != null) {
18721            outInfo.removedPackage = ps.name;
18722            outInfo.installerPackageName = ps.installerPackageName;
18723            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18724            outInfo.removedAppId = ps.appId;
18725            outInfo.removedUsers = userIds;
18726            outInfo.broadcastUsers = userIds;
18727        }
18728
18729        return true;
18730    }
18731
18732    private static final class ClearStorageConnection implements ServiceConnection {
18733        IMediaContainerService mContainerService;
18734
18735        @Override
18736        public void onServiceConnected(ComponentName name, IBinder service) {
18737            synchronized (this) {
18738                mContainerService = IMediaContainerService.Stub
18739                        .asInterface(Binder.allowBlocking(service));
18740                notifyAll();
18741            }
18742        }
18743
18744        @Override
18745        public void onServiceDisconnected(ComponentName name) {
18746        }
18747    }
18748
18749    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18750        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18751
18752        final boolean mounted;
18753        if (Environment.isExternalStorageEmulated()) {
18754            mounted = true;
18755        } else {
18756            final String status = Environment.getExternalStorageState();
18757
18758            mounted = status.equals(Environment.MEDIA_MOUNTED)
18759                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18760        }
18761
18762        if (!mounted) {
18763            return;
18764        }
18765
18766        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18767        int[] users;
18768        if (userId == UserHandle.USER_ALL) {
18769            users = sUserManager.getUserIds();
18770        } else {
18771            users = new int[] { userId };
18772        }
18773        final ClearStorageConnection conn = new ClearStorageConnection();
18774        if (mContext.bindServiceAsUser(
18775                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18776            try {
18777                for (int curUser : users) {
18778                    long timeout = SystemClock.uptimeMillis() + 5000;
18779                    synchronized (conn) {
18780                        long now;
18781                        while (conn.mContainerService == null &&
18782                                (now = SystemClock.uptimeMillis()) < timeout) {
18783                            try {
18784                                conn.wait(timeout - now);
18785                            } catch (InterruptedException e) {
18786                            }
18787                        }
18788                    }
18789                    if (conn.mContainerService == null) {
18790                        return;
18791                    }
18792
18793                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18794                    clearDirectory(conn.mContainerService,
18795                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18796                    if (allData) {
18797                        clearDirectory(conn.mContainerService,
18798                                userEnv.buildExternalStorageAppDataDirs(packageName));
18799                        clearDirectory(conn.mContainerService,
18800                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18801                    }
18802                }
18803            } finally {
18804                mContext.unbindService(conn);
18805            }
18806        }
18807    }
18808
18809    @Override
18810    public void clearApplicationProfileData(String packageName) {
18811        enforceSystemOrRoot("Only the system can clear all profile data");
18812
18813        final PackageParser.Package pkg;
18814        synchronized (mPackages) {
18815            pkg = mPackages.get(packageName);
18816        }
18817
18818        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18819            synchronized (mInstallLock) {
18820                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18821            }
18822        }
18823    }
18824
18825    @Override
18826    public void clearApplicationUserData(final String packageName,
18827            final IPackageDataObserver observer, final int userId) {
18828        mContext.enforceCallingOrSelfPermission(
18829                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18830
18831        final int callingUid = Binder.getCallingUid();
18832        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18833                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18834
18835        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18836        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18837        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18838            throw new SecurityException("Cannot clear data for a protected package: "
18839                    + packageName);
18840        }
18841        // Queue up an async operation since the package deletion may take a little while.
18842        mHandler.post(new Runnable() {
18843            public void run() {
18844                mHandler.removeCallbacks(this);
18845                final boolean succeeded;
18846                if (!filterApp) {
18847                    try (PackageFreezer freezer = freezePackage(packageName,
18848                            "clearApplicationUserData")) {
18849                        synchronized (mInstallLock) {
18850                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18851                        }
18852                        clearExternalStorageDataSync(packageName, userId, true);
18853                        synchronized (mPackages) {
18854                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18855                                    packageName, userId);
18856                        }
18857                    }
18858                    if (succeeded) {
18859                        // invoke DeviceStorageMonitor's update method to clear any notifications
18860                        DeviceStorageMonitorInternal dsm = LocalServices
18861                                .getService(DeviceStorageMonitorInternal.class);
18862                        if (dsm != null) {
18863                            dsm.checkMemory();
18864                        }
18865                    }
18866                } else {
18867                    succeeded = false;
18868                }
18869                if (observer != null) {
18870                    try {
18871                        observer.onRemoveCompleted(packageName, succeeded);
18872                    } catch (RemoteException e) {
18873                        Log.i(TAG, "Observer no longer exists.");
18874                    }
18875                } //end if observer
18876            } //end run
18877        });
18878    }
18879
18880    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18881        if (packageName == null) {
18882            Slog.w(TAG, "Attempt to delete null packageName.");
18883            return false;
18884        }
18885
18886        // Try finding details about the requested package
18887        PackageParser.Package pkg;
18888        synchronized (mPackages) {
18889            pkg = mPackages.get(packageName);
18890            if (pkg == null) {
18891                final PackageSetting ps = mSettings.mPackages.get(packageName);
18892                if (ps != null) {
18893                    pkg = ps.pkg;
18894                }
18895            }
18896
18897            if (pkg == null) {
18898                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18899                return false;
18900            }
18901
18902            PackageSetting ps = (PackageSetting) pkg.mExtras;
18903            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18904        }
18905
18906        clearAppDataLIF(pkg, userId,
18907                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18908
18909        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18910        removeKeystoreDataIfNeeded(userId, appId);
18911
18912        UserManagerInternal umInternal = getUserManagerInternal();
18913        final int flags;
18914        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18915            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18916        } else if (umInternal.isUserRunning(userId)) {
18917            flags = StorageManager.FLAG_STORAGE_DE;
18918        } else {
18919            flags = 0;
18920        }
18921        prepareAppDataContentsLIF(pkg, userId, flags);
18922
18923        return true;
18924    }
18925
18926    /**
18927     * Reverts user permission state changes (permissions and flags) in
18928     * all packages for a given user.
18929     *
18930     * @param userId The device user for which to do a reset.
18931     */
18932    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18933        final int packageCount = mPackages.size();
18934        for (int i = 0; i < packageCount; i++) {
18935            PackageParser.Package pkg = mPackages.valueAt(i);
18936            PackageSetting ps = (PackageSetting) pkg.mExtras;
18937            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18938        }
18939    }
18940
18941    private void resetNetworkPolicies(int userId) {
18942        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18943    }
18944
18945    /**
18946     * Reverts user permission state changes (permissions and flags).
18947     *
18948     * @param ps The package for which to reset.
18949     * @param userId The device user for which to do a reset.
18950     */
18951    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18952            final PackageSetting ps, final int userId) {
18953        if (ps.pkg == null) {
18954            return;
18955        }
18956
18957        // These are flags that can change base on user actions.
18958        final int userSettableMask = FLAG_PERMISSION_USER_SET
18959                | FLAG_PERMISSION_USER_FIXED
18960                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18961                | FLAG_PERMISSION_REVIEW_REQUIRED;
18962
18963        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18964                | FLAG_PERMISSION_POLICY_FIXED;
18965
18966        boolean writeInstallPermissions = false;
18967        boolean writeRuntimePermissions = false;
18968
18969        final int permissionCount = ps.pkg.requestedPermissions.size();
18970        for (int i = 0; i < permissionCount; i++) {
18971            final String permName = ps.pkg.requestedPermissions.get(i);
18972            final BasePermission bp =
18973                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
18974            if (bp == null) {
18975                continue;
18976            }
18977
18978            // If shared user we just reset the state to which only this app contributed.
18979            if (ps.sharedUser != null) {
18980                boolean used = false;
18981                final int packageCount = ps.sharedUser.packages.size();
18982                for (int j = 0; j < packageCount; j++) {
18983                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18984                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18985                            && pkg.pkg.requestedPermissions.contains(permName)) {
18986                        used = true;
18987                        break;
18988                    }
18989                }
18990                if (used) {
18991                    continue;
18992                }
18993            }
18994
18995            final PermissionsState permissionsState = ps.getPermissionsState();
18996
18997            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
18998
18999            // Always clear the user settable flags.
19000            final boolean hasInstallState =
19001                    permissionsState.getInstallPermissionState(permName) != null;
19002            // If permission review is enabled and this is a legacy app, mark the
19003            // permission as requiring a review as this is the initial state.
19004            int flags = 0;
19005            if (mSettings.mPermissions.mPermissionReviewRequired
19006                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19007                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19008            }
19009            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19010                if (hasInstallState) {
19011                    writeInstallPermissions = true;
19012                } else {
19013                    writeRuntimePermissions = true;
19014                }
19015            }
19016
19017            // Below is only runtime permission handling.
19018            if (!bp.isRuntime()) {
19019                continue;
19020            }
19021
19022            // Never clobber system or policy.
19023            if ((oldFlags & policyOrSystemFlags) != 0) {
19024                continue;
19025            }
19026
19027            // If this permission was granted by default, make sure it is.
19028            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19029                if (permissionsState.grantRuntimePermission(bp, userId)
19030                        != PERMISSION_OPERATION_FAILURE) {
19031                    writeRuntimePermissions = true;
19032                }
19033            // If permission review is enabled the permissions for a legacy apps
19034            // are represented as constantly granted runtime ones, so don't revoke.
19035            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19036                // Otherwise, reset the permission.
19037                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19038                switch (revokeResult) {
19039                    case PERMISSION_OPERATION_SUCCESS:
19040                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19041                        writeRuntimePermissions = true;
19042                        final int appId = ps.appId;
19043                        mHandler.post(new Runnable() {
19044                            @Override
19045                            public void run() {
19046                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19047                            }
19048                        });
19049                    } break;
19050                }
19051            }
19052        }
19053
19054        // Synchronously write as we are taking permissions away.
19055        if (writeRuntimePermissions) {
19056            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19057        }
19058
19059        // Synchronously write as we are taking permissions away.
19060        if (writeInstallPermissions) {
19061            mSettings.writeLPr();
19062        }
19063    }
19064
19065    /**
19066     * Remove entries from the keystore daemon. Will only remove it if the
19067     * {@code appId} is valid.
19068     */
19069    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19070        if (appId < 0) {
19071            return;
19072        }
19073
19074        final KeyStore keyStore = KeyStore.getInstance();
19075        if (keyStore != null) {
19076            if (userId == UserHandle.USER_ALL) {
19077                for (final int individual : sUserManager.getUserIds()) {
19078                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19079                }
19080            } else {
19081                keyStore.clearUid(UserHandle.getUid(userId, appId));
19082            }
19083        } else {
19084            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19085        }
19086    }
19087
19088    @Override
19089    public void deleteApplicationCacheFiles(final String packageName,
19090            final IPackageDataObserver observer) {
19091        final int userId = UserHandle.getCallingUserId();
19092        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19093    }
19094
19095    @Override
19096    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19097            final IPackageDataObserver observer) {
19098        final int callingUid = Binder.getCallingUid();
19099        if (mContext.checkCallingOrSelfPermission(
19100                android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
19101                != PackageManager.PERMISSION_GRANTED) {
19102            // If the caller has the old delete cache permission, silently ignore.  Else throw.
19103            if (mContext.checkCallingOrSelfPermission(
19104                    android.Manifest.permission.DELETE_CACHE_FILES)
19105                    == PackageManager.PERMISSION_GRANTED) {
19106                Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
19107                        android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
19108                        ", silently ignoring");
19109                return;
19110            }
19111            mContext.enforceCallingOrSelfPermission(
19112                    android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
19113        }
19114        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19115                /* requireFullPermission= */ true, /* checkShell= */ false,
19116                "delete application cache files");
19117        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19118                android.Manifest.permission.ACCESS_INSTANT_APPS);
19119
19120        final PackageParser.Package pkg;
19121        synchronized (mPackages) {
19122            pkg = mPackages.get(packageName);
19123        }
19124
19125        // Queue up an async operation since the package deletion may take a little while.
19126        mHandler.post(new Runnable() {
19127            public void run() {
19128                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19129                boolean doClearData = true;
19130                if (ps != null) {
19131                    final boolean targetIsInstantApp =
19132                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19133                    doClearData = !targetIsInstantApp
19134                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19135                }
19136                if (doClearData) {
19137                    synchronized (mInstallLock) {
19138                        final int flags = StorageManager.FLAG_STORAGE_DE
19139                                | StorageManager.FLAG_STORAGE_CE;
19140                        // We're only clearing cache files, so we don't care if the
19141                        // app is unfrozen and still able to run
19142                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19143                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19144                    }
19145                    clearExternalStorageDataSync(packageName, userId, false);
19146                }
19147                if (observer != null) {
19148                    try {
19149                        observer.onRemoveCompleted(packageName, true);
19150                    } catch (RemoteException e) {
19151                        Log.i(TAG, "Observer no longer exists.");
19152                    }
19153                }
19154            }
19155        });
19156    }
19157
19158    @Override
19159    public void getPackageSizeInfo(final String packageName, int userHandle,
19160            final IPackageStatsObserver observer) {
19161        throw new UnsupportedOperationException(
19162                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19163    }
19164
19165    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19166        final PackageSetting ps;
19167        synchronized (mPackages) {
19168            ps = mSettings.mPackages.get(packageName);
19169            if (ps == null) {
19170                Slog.w(TAG, "Failed to find settings for " + packageName);
19171                return false;
19172            }
19173        }
19174
19175        final String[] packageNames = { packageName };
19176        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19177        final String[] codePaths = { ps.codePathString };
19178
19179        try {
19180            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19181                    ps.appId, ceDataInodes, codePaths, stats);
19182
19183            // For now, ignore code size of packages on system partition
19184            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19185                stats.codeSize = 0;
19186            }
19187
19188            // External clients expect these to be tracked separately
19189            stats.dataSize -= stats.cacheSize;
19190
19191        } catch (InstallerException e) {
19192            Slog.w(TAG, String.valueOf(e));
19193            return false;
19194        }
19195
19196        return true;
19197    }
19198
19199    private int getUidTargetSdkVersionLockedLPr(int uid) {
19200        Object obj = mSettings.getUserIdLPr(uid);
19201        if (obj instanceof SharedUserSetting) {
19202            final SharedUserSetting sus = (SharedUserSetting) obj;
19203            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19204            final Iterator<PackageSetting> it = sus.packages.iterator();
19205            while (it.hasNext()) {
19206                final PackageSetting ps = it.next();
19207                if (ps.pkg != null) {
19208                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19209                    if (v < vers) vers = v;
19210                }
19211            }
19212            return vers;
19213        } else if (obj instanceof PackageSetting) {
19214            final PackageSetting ps = (PackageSetting) obj;
19215            if (ps.pkg != null) {
19216                return ps.pkg.applicationInfo.targetSdkVersion;
19217            }
19218        }
19219        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19220    }
19221
19222    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19223        final PackageParser.Package p = mPackages.get(packageName);
19224        if (p != null) {
19225            return p.applicationInfo.targetSdkVersion;
19226        }
19227        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19228    }
19229
19230    @Override
19231    public void addPreferredActivity(IntentFilter filter, int match,
19232            ComponentName[] set, ComponentName activity, int userId) {
19233        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19234                "Adding preferred");
19235    }
19236
19237    private void addPreferredActivityInternal(IntentFilter filter, int match,
19238            ComponentName[] set, ComponentName activity, boolean always, int userId,
19239            String opname) {
19240        // writer
19241        int callingUid = Binder.getCallingUid();
19242        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19243                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19244        if (filter.countActions() == 0) {
19245            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19246            return;
19247        }
19248        synchronized (mPackages) {
19249            if (mContext.checkCallingOrSelfPermission(
19250                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19251                    != PackageManager.PERMISSION_GRANTED) {
19252                if (getUidTargetSdkVersionLockedLPr(callingUid)
19253                        < Build.VERSION_CODES.FROYO) {
19254                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19255                            + callingUid);
19256                    return;
19257                }
19258                mContext.enforceCallingOrSelfPermission(
19259                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19260            }
19261
19262            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19263            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19264                    + userId + ":");
19265            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19266            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19267            scheduleWritePackageRestrictionsLocked(userId);
19268            postPreferredActivityChangedBroadcast(userId);
19269        }
19270    }
19271
19272    private void postPreferredActivityChangedBroadcast(int userId) {
19273        mHandler.post(() -> {
19274            final IActivityManager am = ActivityManager.getService();
19275            if (am == null) {
19276                return;
19277            }
19278
19279            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19280            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19281            try {
19282                am.broadcastIntent(null, intent, null, null,
19283                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19284                        null, false, false, userId);
19285            } catch (RemoteException e) {
19286            }
19287        });
19288    }
19289
19290    @Override
19291    public void replacePreferredActivity(IntentFilter filter, int match,
19292            ComponentName[] set, ComponentName activity, int userId) {
19293        if (filter.countActions() != 1) {
19294            throw new IllegalArgumentException(
19295                    "replacePreferredActivity expects filter to have only 1 action.");
19296        }
19297        if (filter.countDataAuthorities() != 0
19298                || filter.countDataPaths() != 0
19299                || filter.countDataSchemes() > 1
19300                || filter.countDataTypes() != 0) {
19301            throw new IllegalArgumentException(
19302                    "replacePreferredActivity expects filter to have no data authorities, " +
19303                    "paths, or types; and at most one scheme.");
19304        }
19305
19306        final int callingUid = Binder.getCallingUid();
19307        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19308                true /* requireFullPermission */, false /* checkShell */,
19309                "replace preferred activity");
19310        synchronized (mPackages) {
19311            if (mContext.checkCallingOrSelfPermission(
19312                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19313                    != PackageManager.PERMISSION_GRANTED) {
19314                if (getUidTargetSdkVersionLockedLPr(callingUid)
19315                        < Build.VERSION_CODES.FROYO) {
19316                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19317                            + Binder.getCallingUid());
19318                    return;
19319                }
19320                mContext.enforceCallingOrSelfPermission(
19321                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19322            }
19323
19324            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19325            if (pir != null) {
19326                // Get all of the existing entries that exactly match this filter.
19327                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19328                if (existing != null && existing.size() == 1) {
19329                    PreferredActivity cur = existing.get(0);
19330                    if (DEBUG_PREFERRED) {
19331                        Slog.i(TAG, "Checking replace of preferred:");
19332                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19333                        if (!cur.mPref.mAlways) {
19334                            Slog.i(TAG, "  -- CUR; not mAlways!");
19335                        } else {
19336                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19337                            Slog.i(TAG, "  -- CUR: mSet="
19338                                    + Arrays.toString(cur.mPref.mSetComponents));
19339                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19340                            Slog.i(TAG, "  -- NEW: mMatch="
19341                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19342                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19343                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19344                        }
19345                    }
19346                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19347                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19348                            && cur.mPref.sameSet(set)) {
19349                        // Setting the preferred activity to what it happens to be already
19350                        if (DEBUG_PREFERRED) {
19351                            Slog.i(TAG, "Replacing with same preferred activity "
19352                                    + cur.mPref.mShortComponent + " for user "
19353                                    + userId + ":");
19354                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19355                        }
19356                        return;
19357                    }
19358                }
19359
19360                if (existing != null) {
19361                    if (DEBUG_PREFERRED) {
19362                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19363                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19364                    }
19365                    for (int i = 0; i < existing.size(); i++) {
19366                        PreferredActivity pa = existing.get(i);
19367                        if (DEBUG_PREFERRED) {
19368                            Slog.i(TAG, "Removing existing preferred activity "
19369                                    + pa.mPref.mComponent + ":");
19370                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19371                        }
19372                        pir.removeFilter(pa);
19373                    }
19374                }
19375            }
19376            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19377                    "Replacing preferred");
19378        }
19379    }
19380
19381    @Override
19382    public void clearPackagePreferredActivities(String packageName) {
19383        final int callingUid = Binder.getCallingUid();
19384        if (getInstantAppPackageName(callingUid) != null) {
19385            return;
19386        }
19387        // writer
19388        synchronized (mPackages) {
19389            PackageParser.Package pkg = mPackages.get(packageName);
19390            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19391                if (mContext.checkCallingOrSelfPermission(
19392                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19393                        != PackageManager.PERMISSION_GRANTED) {
19394                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19395                            < Build.VERSION_CODES.FROYO) {
19396                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19397                                + callingUid);
19398                        return;
19399                    }
19400                    mContext.enforceCallingOrSelfPermission(
19401                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19402                }
19403            }
19404            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19405            if (ps != null
19406                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19407                return;
19408            }
19409            int user = UserHandle.getCallingUserId();
19410            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19411                scheduleWritePackageRestrictionsLocked(user);
19412            }
19413        }
19414    }
19415
19416    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19417    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19418        ArrayList<PreferredActivity> removed = null;
19419        boolean changed = false;
19420        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19421            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19422            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19423            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19424                continue;
19425            }
19426            Iterator<PreferredActivity> it = pir.filterIterator();
19427            while (it.hasNext()) {
19428                PreferredActivity pa = it.next();
19429                // Mark entry for removal only if it matches the package name
19430                // and the entry is of type "always".
19431                if (packageName == null ||
19432                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19433                                && pa.mPref.mAlways)) {
19434                    if (removed == null) {
19435                        removed = new ArrayList<PreferredActivity>();
19436                    }
19437                    removed.add(pa);
19438                }
19439            }
19440            if (removed != null) {
19441                for (int j=0; j<removed.size(); j++) {
19442                    PreferredActivity pa = removed.get(j);
19443                    pir.removeFilter(pa);
19444                }
19445                changed = true;
19446            }
19447        }
19448        if (changed) {
19449            postPreferredActivityChangedBroadcast(userId);
19450        }
19451        return changed;
19452    }
19453
19454    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19455    private void clearIntentFilterVerificationsLPw(int userId) {
19456        final int packageCount = mPackages.size();
19457        for (int i = 0; i < packageCount; i++) {
19458            PackageParser.Package pkg = mPackages.valueAt(i);
19459            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19460        }
19461    }
19462
19463    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19464    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19465        if (userId == UserHandle.USER_ALL) {
19466            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19467                    sUserManager.getUserIds())) {
19468                for (int oneUserId : sUserManager.getUserIds()) {
19469                    scheduleWritePackageRestrictionsLocked(oneUserId);
19470                }
19471            }
19472        } else {
19473            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19474                scheduleWritePackageRestrictionsLocked(userId);
19475            }
19476        }
19477    }
19478
19479    /** Clears state for all users, and touches intent filter verification policy */
19480    void clearDefaultBrowserIfNeeded(String packageName) {
19481        for (int oneUserId : sUserManager.getUserIds()) {
19482            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19483        }
19484    }
19485
19486    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19487        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19488        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19489            if (packageName.equals(defaultBrowserPackageName)) {
19490                setDefaultBrowserPackageName(null, userId);
19491            }
19492        }
19493    }
19494
19495    @Override
19496    public void resetApplicationPreferences(int userId) {
19497        mContext.enforceCallingOrSelfPermission(
19498                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19499        final long identity = Binder.clearCallingIdentity();
19500        // writer
19501        try {
19502            synchronized (mPackages) {
19503                clearPackagePreferredActivitiesLPw(null, userId);
19504                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19505                // TODO: We have to reset the default SMS and Phone. This requires
19506                // significant refactoring to keep all default apps in the package
19507                // manager (cleaner but more work) or have the services provide
19508                // callbacks to the package manager to request a default app reset.
19509                applyFactoryDefaultBrowserLPw(userId);
19510                clearIntentFilterVerificationsLPw(userId);
19511                primeDomainVerificationsLPw(userId);
19512                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19513                scheduleWritePackageRestrictionsLocked(userId);
19514            }
19515            resetNetworkPolicies(userId);
19516        } finally {
19517            Binder.restoreCallingIdentity(identity);
19518        }
19519    }
19520
19521    @Override
19522    public int getPreferredActivities(List<IntentFilter> outFilters,
19523            List<ComponentName> outActivities, String packageName) {
19524        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19525            return 0;
19526        }
19527        int num = 0;
19528        final int userId = UserHandle.getCallingUserId();
19529        // reader
19530        synchronized (mPackages) {
19531            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19532            if (pir != null) {
19533                final Iterator<PreferredActivity> it = pir.filterIterator();
19534                while (it.hasNext()) {
19535                    final PreferredActivity pa = it.next();
19536                    if (packageName == null
19537                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19538                                    && pa.mPref.mAlways)) {
19539                        if (outFilters != null) {
19540                            outFilters.add(new IntentFilter(pa));
19541                        }
19542                        if (outActivities != null) {
19543                            outActivities.add(pa.mPref.mComponent);
19544                        }
19545                    }
19546                }
19547            }
19548        }
19549
19550        return num;
19551    }
19552
19553    @Override
19554    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19555            int userId) {
19556        int callingUid = Binder.getCallingUid();
19557        if (callingUid != Process.SYSTEM_UID) {
19558            throw new SecurityException(
19559                    "addPersistentPreferredActivity can only be run by the system");
19560        }
19561        if (filter.countActions() == 0) {
19562            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19563            return;
19564        }
19565        synchronized (mPackages) {
19566            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19567                    ":");
19568            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19569            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19570                    new PersistentPreferredActivity(filter, activity));
19571            scheduleWritePackageRestrictionsLocked(userId);
19572            postPreferredActivityChangedBroadcast(userId);
19573        }
19574    }
19575
19576    @Override
19577    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19578        int callingUid = Binder.getCallingUid();
19579        if (callingUid != Process.SYSTEM_UID) {
19580            throw new SecurityException(
19581                    "clearPackagePersistentPreferredActivities can only be run by the system");
19582        }
19583        ArrayList<PersistentPreferredActivity> removed = null;
19584        boolean changed = false;
19585        synchronized (mPackages) {
19586            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19587                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19588                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19589                        .valueAt(i);
19590                if (userId != thisUserId) {
19591                    continue;
19592                }
19593                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19594                while (it.hasNext()) {
19595                    PersistentPreferredActivity ppa = it.next();
19596                    // Mark entry for removal only if it matches the package name.
19597                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19598                        if (removed == null) {
19599                            removed = new ArrayList<PersistentPreferredActivity>();
19600                        }
19601                        removed.add(ppa);
19602                    }
19603                }
19604                if (removed != null) {
19605                    for (int j=0; j<removed.size(); j++) {
19606                        PersistentPreferredActivity ppa = removed.get(j);
19607                        ppir.removeFilter(ppa);
19608                    }
19609                    changed = true;
19610                }
19611            }
19612
19613            if (changed) {
19614                scheduleWritePackageRestrictionsLocked(userId);
19615                postPreferredActivityChangedBroadcast(userId);
19616            }
19617        }
19618    }
19619
19620    /**
19621     * Common machinery for picking apart a restored XML blob and passing
19622     * it to a caller-supplied functor to be applied to the running system.
19623     */
19624    private void restoreFromXml(XmlPullParser parser, int userId,
19625            String expectedStartTag, BlobXmlRestorer functor)
19626            throws IOException, XmlPullParserException {
19627        int type;
19628        while ((type = parser.next()) != XmlPullParser.START_TAG
19629                && type != XmlPullParser.END_DOCUMENT) {
19630        }
19631        if (type != XmlPullParser.START_TAG) {
19632            // oops didn't find a start tag?!
19633            if (DEBUG_BACKUP) {
19634                Slog.e(TAG, "Didn't find start tag during restore");
19635            }
19636            return;
19637        }
19638Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19639        // this is supposed to be TAG_PREFERRED_BACKUP
19640        if (!expectedStartTag.equals(parser.getName())) {
19641            if (DEBUG_BACKUP) {
19642                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19643            }
19644            return;
19645        }
19646
19647        // skip interfering stuff, then we're aligned with the backing implementation
19648        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19649Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19650        functor.apply(parser, userId);
19651    }
19652
19653    private interface BlobXmlRestorer {
19654        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19655    }
19656
19657    /**
19658     * Non-Binder method, support for the backup/restore mechanism: write the
19659     * full set of preferred activities in its canonical XML format.  Returns the
19660     * XML output as a byte array, or null if there is none.
19661     */
19662    @Override
19663    public byte[] getPreferredActivityBackup(int userId) {
19664        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19665            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19666        }
19667
19668        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19669        try {
19670            final XmlSerializer serializer = new FastXmlSerializer();
19671            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19672            serializer.startDocument(null, true);
19673            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19674
19675            synchronized (mPackages) {
19676                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19677            }
19678
19679            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19680            serializer.endDocument();
19681            serializer.flush();
19682        } catch (Exception e) {
19683            if (DEBUG_BACKUP) {
19684                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19685            }
19686            return null;
19687        }
19688
19689        return dataStream.toByteArray();
19690    }
19691
19692    @Override
19693    public void restorePreferredActivities(byte[] backup, int userId) {
19694        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19695            throw new SecurityException("Only the system may call restorePreferredActivities()");
19696        }
19697
19698        try {
19699            final XmlPullParser parser = Xml.newPullParser();
19700            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19701            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19702                    new BlobXmlRestorer() {
19703                        @Override
19704                        public void apply(XmlPullParser parser, int userId)
19705                                throws XmlPullParserException, IOException {
19706                            synchronized (mPackages) {
19707                                mSettings.readPreferredActivitiesLPw(parser, userId);
19708                            }
19709                        }
19710                    } );
19711        } catch (Exception e) {
19712            if (DEBUG_BACKUP) {
19713                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19714            }
19715        }
19716    }
19717
19718    /**
19719     * Non-Binder method, support for the backup/restore mechanism: write the
19720     * default browser (etc) settings in its canonical XML format.  Returns the default
19721     * browser XML representation as a byte array, or null if there is none.
19722     */
19723    @Override
19724    public byte[] getDefaultAppsBackup(int userId) {
19725        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19726            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19727        }
19728
19729        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19730        try {
19731            final XmlSerializer serializer = new FastXmlSerializer();
19732            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19733            serializer.startDocument(null, true);
19734            serializer.startTag(null, TAG_DEFAULT_APPS);
19735
19736            synchronized (mPackages) {
19737                mSettings.writeDefaultAppsLPr(serializer, userId);
19738            }
19739
19740            serializer.endTag(null, TAG_DEFAULT_APPS);
19741            serializer.endDocument();
19742            serializer.flush();
19743        } catch (Exception e) {
19744            if (DEBUG_BACKUP) {
19745                Slog.e(TAG, "Unable to write default apps for backup", e);
19746            }
19747            return null;
19748        }
19749
19750        return dataStream.toByteArray();
19751    }
19752
19753    @Override
19754    public void restoreDefaultApps(byte[] backup, int userId) {
19755        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19756            throw new SecurityException("Only the system may call restoreDefaultApps()");
19757        }
19758
19759        try {
19760            final XmlPullParser parser = Xml.newPullParser();
19761            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19762            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19763                    new BlobXmlRestorer() {
19764                        @Override
19765                        public void apply(XmlPullParser parser, int userId)
19766                                throws XmlPullParserException, IOException {
19767                            synchronized (mPackages) {
19768                                mSettings.readDefaultAppsLPw(parser, userId);
19769                            }
19770                        }
19771                    } );
19772        } catch (Exception e) {
19773            if (DEBUG_BACKUP) {
19774                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19775            }
19776        }
19777    }
19778
19779    @Override
19780    public byte[] getIntentFilterVerificationBackup(int userId) {
19781        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19782            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19783        }
19784
19785        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19786        try {
19787            final XmlSerializer serializer = new FastXmlSerializer();
19788            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19789            serializer.startDocument(null, true);
19790            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19791
19792            synchronized (mPackages) {
19793                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19794            }
19795
19796            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19797            serializer.endDocument();
19798            serializer.flush();
19799        } catch (Exception e) {
19800            if (DEBUG_BACKUP) {
19801                Slog.e(TAG, "Unable to write default apps for backup", e);
19802            }
19803            return null;
19804        }
19805
19806        return dataStream.toByteArray();
19807    }
19808
19809    @Override
19810    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19811        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19812            throw new SecurityException("Only the system may call restorePreferredActivities()");
19813        }
19814
19815        try {
19816            final XmlPullParser parser = Xml.newPullParser();
19817            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19818            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19819                    new BlobXmlRestorer() {
19820                        @Override
19821                        public void apply(XmlPullParser parser, int userId)
19822                                throws XmlPullParserException, IOException {
19823                            synchronized (mPackages) {
19824                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19825                                mSettings.writeLPr();
19826                            }
19827                        }
19828                    } );
19829        } catch (Exception e) {
19830            if (DEBUG_BACKUP) {
19831                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19832            }
19833        }
19834    }
19835
19836    @Override
19837    public byte[] getPermissionGrantBackup(int userId) {
19838        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19839            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19840        }
19841
19842        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19843        try {
19844            final XmlSerializer serializer = new FastXmlSerializer();
19845            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19846            serializer.startDocument(null, true);
19847            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19848
19849            synchronized (mPackages) {
19850                serializeRuntimePermissionGrantsLPr(serializer, userId);
19851            }
19852
19853            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19854            serializer.endDocument();
19855            serializer.flush();
19856        } catch (Exception e) {
19857            if (DEBUG_BACKUP) {
19858                Slog.e(TAG, "Unable to write default apps for backup", e);
19859            }
19860            return null;
19861        }
19862
19863        return dataStream.toByteArray();
19864    }
19865
19866    @Override
19867    public void restorePermissionGrants(byte[] backup, int userId) {
19868        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19869            throw new SecurityException("Only the system may call restorePermissionGrants()");
19870        }
19871
19872        try {
19873            final XmlPullParser parser = Xml.newPullParser();
19874            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19875            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19876                    new BlobXmlRestorer() {
19877                        @Override
19878                        public void apply(XmlPullParser parser, int userId)
19879                                throws XmlPullParserException, IOException {
19880                            synchronized (mPackages) {
19881                                processRestoredPermissionGrantsLPr(parser, userId);
19882                            }
19883                        }
19884                    } );
19885        } catch (Exception e) {
19886            if (DEBUG_BACKUP) {
19887                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19888            }
19889        }
19890    }
19891
19892    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19893            throws IOException {
19894        serializer.startTag(null, TAG_ALL_GRANTS);
19895
19896        final int N = mSettings.mPackages.size();
19897        for (int i = 0; i < N; i++) {
19898            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19899            boolean pkgGrantsKnown = false;
19900
19901            PermissionsState packagePerms = ps.getPermissionsState();
19902
19903            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19904                final int grantFlags = state.getFlags();
19905                // only look at grants that are not system/policy fixed
19906                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19907                    final boolean isGranted = state.isGranted();
19908                    // And only back up the user-twiddled state bits
19909                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19910                        final String packageName = mSettings.mPackages.keyAt(i);
19911                        if (!pkgGrantsKnown) {
19912                            serializer.startTag(null, TAG_GRANT);
19913                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19914                            pkgGrantsKnown = true;
19915                        }
19916
19917                        final boolean userSet =
19918                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19919                        final boolean userFixed =
19920                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19921                        final boolean revoke =
19922                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19923
19924                        serializer.startTag(null, TAG_PERMISSION);
19925                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19926                        if (isGranted) {
19927                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19928                        }
19929                        if (userSet) {
19930                            serializer.attribute(null, ATTR_USER_SET, "true");
19931                        }
19932                        if (userFixed) {
19933                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19934                        }
19935                        if (revoke) {
19936                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19937                        }
19938                        serializer.endTag(null, TAG_PERMISSION);
19939                    }
19940                }
19941            }
19942
19943            if (pkgGrantsKnown) {
19944                serializer.endTag(null, TAG_GRANT);
19945            }
19946        }
19947
19948        serializer.endTag(null, TAG_ALL_GRANTS);
19949    }
19950
19951    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19952            throws XmlPullParserException, IOException {
19953        String pkgName = null;
19954        int outerDepth = parser.getDepth();
19955        int type;
19956        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19957                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19958            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19959                continue;
19960            }
19961
19962            final String tagName = parser.getName();
19963            if (tagName.equals(TAG_GRANT)) {
19964                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19965                if (DEBUG_BACKUP) {
19966                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19967                }
19968            } else if (tagName.equals(TAG_PERMISSION)) {
19969
19970                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19971                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19972
19973                int newFlagSet = 0;
19974                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19975                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19976                }
19977                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19978                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19979                }
19980                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19981                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19982                }
19983                if (DEBUG_BACKUP) {
19984                    Slog.v(TAG, "  + Restoring grant:"
19985                            + " pkg=" + pkgName
19986                            + " perm=" + permName
19987                            + " granted=" + isGranted
19988                            + " bits=0x" + Integer.toHexString(newFlagSet));
19989                }
19990                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19991                if (ps != null) {
19992                    // Already installed so we apply the grant immediately
19993                    if (DEBUG_BACKUP) {
19994                        Slog.v(TAG, "        + already installed; applying");
19995                    }
19996                    PermissionsState perms = ps.getPermissionsState();
19997                    BasePermission bp =
19998                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19999                    if (bp != null) {
20000                        if (isGranted) {
20001                            perms.grantRuntimePermission(bp, userId);
20002                        }
20003                        if (newFlagSet != 0) {
20004                            perms.updatePermissionFlags(
20005                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20006                        }
20007                    }
20008                } else {
20009                    // Need to wait for post-restore install to apply the grant
20010                    if (DEBUG_BACKUP) {
20011                        Slog.v(TAG, "        - not yet installed; saving for later");
20012                    }
20013                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20014                            isGranted, newFlagSet, userId);
20015                }
20016            } else {
20017                PackageManagerService.reportSettingsProblem(Log.WARN,
20018                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20019                XmlUtils.skipCurrentTag(parser);
20020            }
20021        }
20022
20023        scheduleWriteSettingsLocked();
20024        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20025    }
20026
20027    @Override
20028    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20029            int sourceUserId, int targetUserId, int flags) {
20030        mContext.enforceCallingOrSelfPermission(
20031                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20032        int callingUid = Binder.getCallingUid();
20033        enforceOwnerRights(ownerPackage, callingUid);
20034        PackageManagerServiceUtils.enforceShellRestriction(
20035                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20036        if (intentFilter.countActions() == 0) {
20037            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20038            return;
20039        }
20040        synchronized (mPackages) {
20041            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20042                    ownerPackage, targetUserId, flags);
20043            CrossProfileIntentResolver resolver =
20044                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20045            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20046            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20047            if (existing != null) {
20048                int size = existing.size();
20049                for (int i = 0; i < size; i++) {
20050                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20051                        return;
20052                    }
20053                }
20054            }
20055            resolver.addFilter(newFilter);
20056            scheduleWritePackageRestrictionsLocked(sourceUserId);
20057        }
20058    }
20059
20060    @Override
20061    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20062        mContext.enforceCallingOrSelfPermission(
20063                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20064        final int callingUid = Binder.getCallingUid();
20065        enforceOwnerRights(ownerPackage, callingUid);
20066        PackageManagerServiceUtils.enforceShellRestriction(
20067                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20068        synchronized (mPackages) {
20069            CrossProfileIntentResolver resolver =
20070                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20071            ArraySet<CrossProfileIntentFilter> set =
20072                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20073            for (CrossProfileIntentFilter filter : set) {
20074                if (filter.getOwnerPackage().equals(ownerPackage)) {
20075                    resolver.removeFilter(filter);
20076                }
20077            }
20078            scheduleWritePackageRestrictionsLocked(sourceUserId);
20079        }
20080    }
20081
20082    // Enforcing that callingUid is owning pkg on userId
20083    private void enforceOwnerRights(String pkg, int callingUid) {
20084        // The system owns everything.
20085        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20086            return;
20087        }
20088        final int callingUserId = UserHandle.getUserId(callingUid);
20089        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20090        if (pi == null) {
20091            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20092                    + callingUserId);
20093        }
20094        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20095            throw new SecurityException("Calling uid " + callingUid
20096                    + " does not own package " + pkg);
20097        }
20098    }
20099
20100    @Override
20101    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20102        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20103            return null;
20104        }
20105        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20106    }
20107
20108    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20109        UserManagerService ums = UserManagerService.getInstance();
20110        if (ums != null) {
20111            final UserInfo parent = ums.getProfileParent(userId);
20112            final int launcherUid = (parent != null) ? parent.id : userId;
20113            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20114            if (launcherComponent != null) {
20115                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20116                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20117                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20118                        .setPackage(launcherComponent.getPackageName());
20119                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20120            }
20121        }
20122    }
20123
20124    /**
20125     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20126     * then reports the most likely home activity or null if there are more than one.
20127     */
20128    private ComponentName getDefaultHomeActivity(int userId) {
20129        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20130        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20131        if (cn != null) {
20132            return cn;
20133        }
20134
20135        // Find the launcher with the highest priority and return that component if there are no
20136        // other home activity with the same priority.
20137        int lastPriority = Integer.MIN_VALUE;
20138        ComponentName lastComponent = null;
20139        final int size = allHomeCandidates.size();
20140        for (int i = 0; i < size; i++) {
20141            final ResolveInfo ri = allHomeCandidates.get(i);
20142            if (ri.priority > lastPriority) {
20143                lastComponent = ri.activityInfo.getComponentName();
20144                lastPriority = ri.priority;
20145            } else if (ri.priority == lastPriority) {
20146                // Two components found with same priority.
20147                lastComponent = null;
20148            }
20149        }
20150        return lastComponent;
20151    }
20152
20153    private Intent getHomeIntent() {
20154        Intent intent = new Intent(Intent.ACTION_MAIN);
20155        intent.addCategory(Intent.CATEGORY_HOME);
20156        intent.addCategory(Intent.CATEGORY_DEFAULT);
20157        return intent;
20158    }
20159
20160    private IntentFilter getHomeFilter() {
20161        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20162        filter.addCategory(Intent.CATEGORY_HOME);
20163        filter.addCategory(Intent.CATEGORY_DEFAULT);
20164        return filter;
20165    }
20166
20167    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20168            int userId) {
20169        Intent intent  = getHomeIntent();
20170        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20171                PackageManager.GET_META_DATA, userId);
20172        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20173                true, false, false, userId);
20174
20175        allHomeCandidates.clear();
20176        if (list != null) {
20177            for (ResolveInfo ri : list) {
20178                allHomeCandidates.add(ri);
20179            }
20180        }
20181        return (preferred == null || preferred.activityInfo == null)
20182                ? null
20183                : new ComponentName(preferred.activityInfo.packageName,
20184                        preferred.activityInfo.name);
20185    }
20186
20187    @Override
20188    public void setHomeActivity(ComponentName comp, int userId) {
20189        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20190            return;
20191        }
20192        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20193        getHomeActivitiesAsUser(homeActivities, userId);
20194
20195        boolean found = false;
20196
20197        final int size = homeActivities.size();
20198        final ComponentName[] set = new ComponentName[size];
20199        for (int i = 0; i < size; i++) {
20200            final ResolveInfo candidate = homeActivities.get(i);
20201            final ActivityInfo info = candidate.activityInfo;
20202            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20203            set[i] = activityName;
20204            if (!found && activityName.equals(comp)) {
20205                found = true;
20206            }
20207        }
20208        if (!found) {
20209            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20210                    + userId);
20211        }
20212        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20213                set, comp, userId);
20214    }
20215
20216    private @Nullable String getSetupWizardPackageName() {
20217        final Intent intent = new Intent(Intent.ACTION_MAIN);
20218        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20219
20220        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20221                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20222                        | MATCH_DISABLED_COMPONENTS,
20223                UserHandle.myUserId());
20224        if (matches.size() == 1) {
20225            return matches.get(0).getComponentInfo().packageName;
20226        } else {
20227            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20228                    + ": matches=" + matches);
20229            return null;
20230        }
20231    }
20232
20233    private @Nullable String getStorageManagerPackageName() {
20234        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20235
20236        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20237                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20238                        | MATCH_DISABLED_COMPONENTS,
20239                UserHandle.myUserId());
20240        if (matches.size() == 1) {
20241            return matches.get(0).getComponentInfo().packageName;
20242        } else {
20243            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20244                    + matches.size() + ": matches=" + matches);
20245            return null;
20246        }
20247    }
20248
20249    @Override
20250    public void setApplicationEnabledSetting(String appPackageName,
20251            int newState, int flags, int userId, String callingPackage) {
20252        if (!sUserManager.exists(userId)) return;
20253        if (callingPackage == null) {
20254            callingPackage = Integer.toString(Binder.getCallingUid());
20255        }
20256        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20257    }
20258
20259    @Override
20260    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20261        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20262        synchronized (mPackages) {
20263            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20264            if (pkgSetting != null) {
20265                pkgSetting.setUpdateAvailable(updateAvailable);
20266            }
20267        }
20268    }
20269
20270    @Override
20271    public void setComponentEnabledSetting(ComponentName componentName,
20272            int newState, int flags, int userId) {
20273        if (!sUserManager.exists(userId)) return;
20274        setEnabledSetting(componentName.getPackageName(),
20275                componentName.getClassName(), newState, flags, userId, null);
20276    }
20277
20278    private void setEnabledSetting(final String packageName, String className, int newState,
20279            final int flags, int userId, String callingPackage) {
20280        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20281              || newState == COMPONENT_ENABLED_STATE_ENABLED
20282              || newState == COMPONENT_ENABLED_STATE_DISABLED
20283              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20284              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20285            throw new IllegalArgumentException("Invalid new component state: "
20286                    + newState);
20287        }
20288        PackageSetting pkgSetting;
20289        final int callingUid = Binder.getCallingUid();
20290        final int permission;
20291        if (callingUid == Process.SYSTEM_UID) {
20292            permission = PackageManager.PERMISSION_GRANTED;
20293        } else {
20294            permission = mContext.checkCallingOrSelfPermission(
20295                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20296        }
20297        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20298                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20299        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20300        boolean sendNow = false;
20301        boolean isApp = (className == null);
20302        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20303        String componentName = isApp ? packageName : className;
20304        int packageUid = -1;
20305        ArrayList<String> components;
20306
20307        // reader
20308        synchronized (mPackages) {
20309            pkgSetting = mSettings.mPackages.get(packageName);
20310            if (pkgSetting == null) {
20311                if (!isCallerInstantApp) {
20312                    if (className == null) {
20313                        throw new IllegalArgumentException("Unknown package: " + packageName);
20314                    }
20315                    throw new IllegalArgumentException(
20316                            "Unknown component: " + packageName + "/" + className);
20317                } else {
20318                    // throw SecurityException to prevent leaking package information
20319                    throw new SecurityException(
20320                            "Attempt to change component state; "
20321                            + "pid=" + Binder.getCallingPid()
20322                            + ", uid=" + callingUid
20323                            + (className == null
20324                                    ? ", package=" + packageName
20325                                    : ", component=" + packageName + "/" + className));
20326                }
20327            }
20328        }
20329
20330        // Limit who can change which apps
20331        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20332            // Don't allow apps that don't have permission to modify other apps
20333            if (!allowedByPermission
20334                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20335                throw new SecurityException(
20336                        "Attempt to change component state; "
20337                        + "pid=" + Binder.getCallingPid()
20338                        + ", uid=" + callingUid
20339                        + (className == null
20340                                ? ", package=" + packageName
20341                                : ", component=" + packageName + "/" + className));
20342            }
20343            // Don't allow changing protected packages.
20344            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20345                throw new SecurityException("Cannot disable a protected package: " + packageName);
20346            }
20347        }
20348
20349        synchronized (mPackages) {
20350            if (callingUid == Process.SHELL_UID
20351                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20352                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20353                // unless it is a test package.
20354                int oldState = pkgSetting.getEnabled(userId);
20355                if (className == null
20356                        &&
20357                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20358                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20359                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20360                        &&
20361                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20362                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20363                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20364                    // ok
20365                } else {
20366                    throw new SecurityException(
20367                            "Shell cannot change component state for " + packageName + "/"
20368                                    + className + " to " + newState);
20369                }
20370            }
20371        }
20372        if (className == null) {
20373            // We're dealing with an application/package level state change
20374            synchronized (mPackages) {
20375                if (pkgSetting.getEnabled(userId) == newState) {
20376                    // Nothing to do
20377                    return;
20378                }
20379            }
20380            // If we're enabling a system stub, there's a little more work to do.
20381            // Prior to enabling the package, we need to decompress the APK(s) to the
20382            // data partition and then replace the version on the system partition.
20383            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20384            final boolean isSystemStub = deletedPkg.isStub
20385                    && deletedPkg.isSystem();
20386            if (isSystemStub
20387                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20388                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20389                final File codePath = decompressPackage(deletedPkg);
20390                if (codePath == null) {
20391                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20392                    return;
20393                }
20394                // TODO remove direct parsing of the package object during internal cleanup
20395                // of scan package
20396                // We need to call parse directly here for no other reason than we need
20397                // the new package in order to disable the old one [we use the information
20398                // for some internal optimization to optionally create a new package setting
20399                // object on replace]. However, we can't get the package from the scan
20400                // because the scan modifies live structures and we need to remove the
20401                // old [system] package from the system before a scan can be attempted.
20402                // Once scan is indempotent we can remove this parse and use the package
20403                // object we scanned, prior to adding it to package settings.
20404                final PackageParser pp = new PackageParser();
20405                pp.setSeparateProcesses(mSeparateProcesses);
20406                pp.setDisplayMetrics(mMetrics);
20407                pp.setCallback(mPackageParserCallback);
20408                final PackageParser.Package tmpPkg;
20409                try {
20410                    final @ParseFlags int parseFlags = mDefParseFlags
20411                            | PackageParser.PARSE_MUST_BE_APK
20412                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20413                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20414                } catch (PackageParserException e) {
20415                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20416                    return;
20417                }
20418                synchronized (mInstallLock) {
20419                    // Disable the stub and remove any package entries
20420                    removePackageLI(deletedPkg, true);
20421                    synchronized (mPackages) {
20422                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20423                    }
20424                    final PackageParser.Package pkg;
20425                    try (PackageFreezer freezer =
20426                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20427                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20428                                | PackageParser.PARSE_ENFORCE_CODE;
20429                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20430                                0 /*currentTime*/, null /*user*/);
20431                        prepareAppDataAfterInstallLIF(pkg);
20432                        synchronized (mPackages) {
20433                            try {
20434                                updateSharedLibrariesLPr(pkg, null);
20435                            } catch (PackageManagerException e) {
20436                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20437                            }
20438                            mPermissionManager.updatePermissions(
20439                                    pkg.packageName, pkg, true, mPackages.values(),
20440                                    mPermissionCallback);
20441                            mSettings.writeLPr();
20442                        }
20443                    } catch (PackageManagerException e) {
20444                        // Whoops! Something went wrong; try to roll back to the stub
20445                        Slog.w(TAG, "Failed to install compressed system package:"
20446                                + pkgSetting.name, e);
20447                        // Remove the failed install
20448                        removeCodePathLI(codePath);
20449
20450                        // Install the system package
20451                        try (PackageFreezer freezer =
20452                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20453                            synchronized (mPackages) {
20454                                // NOTE: The system package always needs to be enabled; even
20455                                // if it's for a compressed stub. If we don't, installing the
20456                                // system package fails during scan [scanning checks the disabled
20457                                // packages]. We will reverse this later, after we've "installed"
20458                                // the stub.
20459                                // This leaves us in a fragile state; the stub should never be
20460                                // enabled, so, cross your fingers and hope nothing goes wrong
20461                                // until we can disable the package later.
20462                                enableSystemPackageLPw(deletedPkg);
20463                            }
20464                            installPackageFromSystemLIF(deletedPkg.codePath,
20465                                    false /*isPrivileged*/, null /*allUserHandles*/,
20466                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20467                                    true /*writeSettings*/);
20468                        } catch (PackageManagerException pme) {
20469                            Slog.w(TAG, "Failed to restore system package:"
20470                                    + deletedPkg.packageName, pme);
20471                        } finally {
20472                            synchronized (mPackages) {
20473                                mSettings.disableSystemPackageLPw(
20474                                        deletedPkg.packageName, true /*replaced*/);
20475                                mSettings.writeLPr();
20476                            }
20477                        }
20478                        return;
20479                    }
20480                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20481                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20482                    mDexManager.notifyPackageUpdated(pkg.packageName,
20483                            pkg.baseCodePath, pkg.splitCodePaths);
20484                }
20485            }
20486            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20487                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20488                // Don't care about who enables an app.
20489                callingPackage = null;
20490            }
20491            synchronized (mPackages) {
20492                pkgSetting.setEnabled(newState, userId, callingPackage);
20493            }
20494        } else {
20495            synchronized (mPackages) {
20496                // We're dealing with a component level state change
20497                // First, verify that this is a valid class name.
20498                PackageParser.Package pkg = pkgSetting.pkg;
20499                if (pkg == null || !pkg.hasComponentClassName(className)) {
20500                    if (pkg != null &&
20501                            pkg.applicationInfo.targetSdkVersion >=
20502                                    Build.VERSION_CODES.JELLY_BEAN) {
20503                        throw new IllegalArgumentException("Component class " + className
20504                                + " does not exist in " + packageName);
20505                    } else {
20506                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20507                                + className + " does not exist in " + packageName);
20508                    }
20509                }
20510                switch (newState) {
20511                    case COMPONENT_ENABLED_STATE_ENABLED:
20512                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20513                            return;
20514                        }
20515                        break;
20516                    case COMPONENT_ENABLED_STATE_DISABLED:
20517                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20518                            return;
20519                        }
20520                        break;
20521                    case COMPONENT_ENABLED_STATE_DEFAULT:
20522                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20523                            return;
20524                        }
20525                        break;
20526                    default:
20527                        Slog.e(TAG, "Invalid new component state: " + newState);
20528                        return;
20529                }
20530            }
20531        }
20532        synchronized (mPackages) {
20533            scheduleWritePackageRestrictionsLocked(userId);
20534            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20535            final long callingId = Binder.clearCallingIdentity();
20536            try {
20537                updateInstantAppInstallerLocked(packageName);
20538            } finally {
20539                Binder.restoreCallingIdentity(callingId);
20540            }
20541            components = mPendingBroadcasts.get(userId, packageName);
20542            final boolean newPackage = components == null;
20543            if (newPackage) {
20544                components = new ArrayList<String>();
20545            }
20546            if (!components.contains(componentName)) {
20547                components.add(componentName);
20548            }
20549            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20550                sendNow = true;
20551                // Purge entry from pending broadcast list if another one exists already
20552                // since we are sending one right away.
20553                mPendingBroadcasts.remove(userId, packageName);
20554            } else {
20555                if (newPackage) {
20556                    mPendingBroadcasts.put(userId, packageName, components);
20557                }
20558                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20559                    // Schedule a message
20560                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20561                }
20562            }
20563        }
20564
20565        long callingId = Binder.clearCallingIdentity();
20566        try {
20567            if (sendNow) {
20568                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20569                sendPackageChangedBroadcast(packageName,
20570                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20571            }
20572        } finally {
20573            Binder.restoreCallingIdentity(callingId);
20574        }
20575    }
20576
20577    @Override
20578    public void flushPackageRestrictionsAsUser(int userId) {
20579        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20580            return;
20581        }
20582        if (!sUserManager.exists(userId)) {
20583            return;
20584        }
20585        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20586                false /* checkShell */, "flushPackageRestrictions");
20587        synchronized (mPackages) {
20588            mSettings.writePackageRestrictionsLPr(userId);
20589            mDirtyUsers.remove(userId);
20590            if (mDirtyUsers.isEmpty()) {
20591                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20592            }
20593        }
20594    }
20595
20596    private void sendPackageChangedBroadcast(String packageName,
20597            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20598        if (DEBUG_INSTALL)
20599            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20600                    + componentNames);
20601        Bundle extras = new Bundle(4);
20602        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20603        String nameList[] = new String[componentNames.size()];
20604        componentNames.toArray(nameList);
20605        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20606        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20607        extras.putInt(Intent.EXTRA_UID, packageUid);
20608        // If this is not reporting a change of the overall package, then only send it
20609        // to registered receivers.  We don't want to launch a swath of apps for every
20610        // little component state change.
20611        final int flags = !componentNames.contains(packageName)
20612                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20613        final int userId = UserHandle.getUserId(packageUid);
20614        final boolean isInstantApp = isInstantApp(packageName, userId);
20615        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20616        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20617        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20618                userIds, instantUserIds);
20619    }
20620
20621    @Override
20622    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20623        if (!sUserManager.exists(userId)) return;
20624        final int callingUid = Binder.getCallingUid();
20625        if (getInstantAppPackageName(callingUid) != null) {
20626            return;
20627        }
20628        final int permission = mContext.checkCallingOrSelfPermission(
20629                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20630        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20631        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20632                true /* requireFullPermission */, true /* checkShell */, "stop package");
20633        // writer
20634        synchronized (mPackages) {
20635            final PackageSetting ps = mSettings.mPackages.get(packageName);
20636            if (!filterAppAccessLPr(ps, callingUid, userId)
20637                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20638                            allowedByPermission, callingUid, userId)) {
20639                scheduleWritePackageRestrictionsLocked(userId);
20640            }
20641        }
20642    }
20643
20644    @Override
20645    public String getInstallerPackageName(String packageName) {
20646        final int callingUid = Binder.getCallingUid();
20647        if (getInstantAppPackageName(callingUid) != null) {
20648            return null;
20649        }
20650        // reader
20651        synchronized (mPackages) {
20652            final PackageSetting ps = mSettings.mPackages.get(packageName);
20653            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20654                return null;
20655            }
20656            return mSettings.getInstallerPackageNameLPr(packageName);
20657        }
20658    }
20659
20660    public boolean isOrphaned(String packageName) {
20661        // reader
20662        synchronized (mPackages) {
20663            return mSettings.isOrphaned(packageName);
20664        }
20665    }
20666
20667    @Override
20668    public int getApplicationEnabledSetting(String packageName, int userId) {
20669        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20670        int callingUid = Binder.getCallingUid();
20671        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20672                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20673        // reader
20674        synchronized (mPackages) {
20675            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20676                return COMPONENT_ENABLED_STATE_DISABLED;
20677            }
20678            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20679        }
20680    }
20681
20682    @Override
20683    public int getComponentEnabledSetting(ComponentName component, int userId) {
20684        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20685        int callingUid = Binder.getCallingUid();
20686        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20687                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20688        synchronized (mPackages) {
20689            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20690                    component, TYPE_UNKNOWN, userId)) {
20691                return COMPONENT_ENABLED_STATE_DISABLED;
20692            }
20693            return mSettings.getComponentEnabledSettingLPr(component, userId);
20694        }
20695    }
20696
20697    @Override
20698    public void enterSafeMode() {
20699        enforceSystemOrRoot("Only the system can request entering safe mode");
20700
20701        if (!mSystemReady) {
20702            mSafeMode = true;
20703        }
20704    }
20705
20706    @Override
20707    public void systemReady() {
20708        enforceSystemOrRoot("Only the system can claim the system is ready");
20709
20710        mSystemReady = true;
20711        final ContentResolver resolver = mContext.getContentResolver();
20712        ContentObserver co = new ContentObserver(mHandler) {
20713            @Override
20714            public void onChange(boolean selfChange) {
20715                mWebInstantAppsDisabled =
20716                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20717                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20718            }
20719        };
20720        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20721                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20722                false, co, UserHandle.USER_SYSTEM);
20723        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
20724                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20725        co.onChange(true);
20726
20727        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20728        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20729        // it is done.
20730        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20731            @Override
20732            public void onChange(boolean selfChange) {
20733                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20734                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20735                        oobEnabled == 1 ? "true" : "false");
20736            }
20737        };
20738        mContext.getContentResolver().registerContentObserver(
20739                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20740                UserHandle.USER_SYSTEM);
20741        // At boot, restore the value from the setting, which persists across reboot.
20742        privAppOobObserver.onChange(true);
20743
20744        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20745        // disabled after already being started.
20746        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20747                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20748
20749        // Read the compatibilty setting when the system is ready.
20750        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20751                mContext.getContentResolver(),
20752                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20753        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20754        if (DEBUG_SETTINGS) {
20755            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20756        }
20757
20758        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20759
20760        synchronized (mPackages) {
20761            // Verify that all of the preferred activity components actually
20762            // exist.  It is possible for applications to be updated and at
20763            // that point remove a previously declared activity component that
20764            // had been set as a preferred activity.  We try to clean this up
20765            // the next time we encounter that preferred activity, but it is
20766            // possible for the user flow to never be able to return to that
20767            // situation so here we do a sanity check to make sure we haven't
20768            // left any junk around.
20769            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20770            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20771                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20772                removed.clear();
20773                for (PreferredActivity pa : pir.filterSet()) {
20774                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20775                        removed.add(pa);
20776                    }
20777                }
20778                if (removed.size() > 0) {
20779                    for (int r=0; r<removed.size(); r++) {
20780                        PreferredActivity pa = removed.get(r);
20781                        Slog.w(TAG, "Removing dangling preferred activity: "
20782                                + pa.mPref.mComponent);
20783                        pir.removeFilter(pa);
20784                    }
20785                    mSettings.writePackageRestrictionsLPr(
20786                            mSettings.mPreferredActivities.keyAt(i));
20787                }
20788            }
20789
20790            for (int userId : UserManagerService.getInstance().getUserIds()) {
20791                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20792                    grantPermissionsUserIds = ArrayUtils.appendInt(
20793                            grantPermissionsUserIds, userId);
20794                }
20795            }
20796        }
20797        sUserManager.systemReady();
20798        // If we upgraded grant all default permissions before kicking off.
20799        for (int userId : grantPermissionsUserIds) {
20800            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20801        }
20802
20803        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20804            // If we did not grant default permissions, we preload from this the
20805            // default permission exceptions lazily to ensure we don't hit the
20806            // disk on a new user creation.
20807            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20808        }
20809
20810        // Now that we've scanned all packages, and granted any default
20811        // permissions, ensure permissions are updated. Beware of dragons if you
20812        // try optimizing this.
20813        synchronized (mPackages) {
20814            mPermissionManager.updateAllPermissions(
20815                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20816                    mPermissionCallback);
20817        }
20818
20819        // Kick off any messages waiting for system ready
20820        if (mPostSystemReadyMessages != null) {
20821            for (Message msg : mPostSystemReadyMessages) {
20822                msg.sendToTarget();
20823            }
20824            mPostSystemReadyMessages = null;
20825        }
20826
20827        // Watch for external volumes that come and go over time
20828        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20829        storage.registerListener(mStorageListener);
20830
20831        mInstallerService.systemReady();
20832        mPackageDexOptimizer.systemReady();
20833
20834        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20835                StorageManagerInternal.class);
20836        StorageManagerInternal.addExternalStoragePolicy(
20837                new StorageManagerInternal.ExternalStorageMountPolicy() {
20838            @Override
20839            public int getMountMode(int uid, String packageName) {
20840                if (Process.isIsolated(uid)) {
20841                    return Zygote.MOUNT_EXTERNAL_NONE;
20842                }
20843                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20844                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20845                }
20846                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20847                    return Zygote.MOUNT_EXTERNAL_READ;
20848                }
20849                return Zygote.MOUNT_EXTERNAL_WRITE;
20850            }
20851
20852            @Override
20853            public boolean hasExternalStorage(int uid, String packageName) {
20854                return true;
20855            }
20856        });
20857
20858        // Now that we're mostly running, clean up stale users and apps
20859        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20860        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20861
20862        mPermissionManager.systemReady();
20863    }
20864
20865    public void waitForAppDataPrepared() {
20866        if (mPrepareAppDataFuture == null) {
20867            return;
20868        }
20869        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20870        mPrepareAppDataFuture = null;
20871    }
20872
20873    @Override
20874    public boolean isSafeMode() {
20875        // allow instant applications
20876        return mSafeMode;
20877    }
20878
20879    @Override
20880    public boolean hasSystemUidErrors() {
20881        // allow instant applications
20882        return mHasSystemUidErrors;
20883    }
20884
20885    static String arrayToString(int[] array) {
20886        StringBuffer buf = new StringBuffer(128);
20887        buf.append('[');
20888        if (array != null) {
20889            for (int i=0; i<array.length; i++) {
20890                if (i > 0) buf.append(", ");
20891                buf.append(array[i]);
20892            }
20893        }
20894        buf.append(']');
20895        return buf.toString();
20896    }
20897
20898    @Override
20899    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20900            FileDescriptor err, String[] args, ShellCallback callback,
20901            ResultReceiver resultReceiver) {
20902        (new PackageManagerShellCommand(this)).exec(
20903                this, in, out, err, args, callback, resultReceiver);
20904    }
20905
20906    @Override
20907    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20908        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20909
20910        DumpState dumpState = new DumpState();
20911        boolean fullPreferred = false;
20912        boolean checkin = false;
20913
20914        String packageName = null;
20915        ArraySet<String> permissionNames = null;
20916
20917        int opti = 0;
20918        while (opti < args.length) {
20919            String opt = args[opti];
20920            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20921                break;
20922            }
20923            opti++;
20924
20925            if ("-a".equals(opt)) {
20926                // Right now we only know how to print all.
20927            } else if ("-h".equals(opt)) {
20928                pw.println("Package manager dump options:");
20929                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20930                pw.println("    --checkin: dump for a checkin");
20931                pw.println("    -f: print details of intent filters");
20932                pw.println("    -h: print this help");
20933                pw.println("  cmd may be one of:");
20934                pw.println("    l[ibraries]: list known shared libraries");
20935                pw.println("    f[eatures]: list device features");
20936                pw.println("    k[eysets]: print known keysets");
20937                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20938                pw.println("    perm[issions]: dump permissions");
20939                pw.println("    permission [name ...]: dump declaration and use of given permission");
20940                pw.println("    pref[erred]: print preferred package settings");
20941                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20942                pw.println("    prov[iders]: dump content providers");
20943                pw.println("    p[ackages]: dump installed packages");
20944                pw.println("    s[hared-users]: dump shared user IDs");
20945                pw.println("    m[essages]: print collected runtime messages");
20946                pw.println("    v[erifiers]: print package verifier info");
20947                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20948                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20949                pw.println("    version: print database version info");
20950                pw.println("    write: write current settings now");
20951                pw.println("    installs: details about install sessions");
20952                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20953                pw.println("    dexopt: dump dexopt state");
20954                pw.println("    compiler-stats: dump compiler statistics");
20955                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20956                pw.println("    service-permissions: dump permissions required by services");
20957                pw.println("    <package.name>: info about given package");
20958                return;
20959            } else if ("--checkin".equals(opt)) {
20960                checkin = true;
20961            } else if ("-f".equals(opt)) {
20962                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20963            } else if ("--proto".equals(opt)) {
20964                dumpProto(fd);
20965                return;
20966            } else {
20967                pw.println("Unknown argument: " + opt + "; use -h for help");
20968            }
20969        }
20970
20971        // Is the caller requesting to dump a particular piece of data?
20972        if (opti < args.length) {
20973            String cmd = args[opti];
20974            opti++;
20975            // Is this a package name?
20976            if ("android".equals(cmd) || cmd.contains(".")) {
20977                packageName = cmd;
20978                // When dumping a single package, we always dump all of its
20979                // filter information since the amount of data will be reasonable.
20980                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20981            } else if ("check-permission".equals(cmd)) {
20982                if (opti >= args.length) {
20983                    pw.println("Error: check-permission missing permission argument");
20984                    return;
20985                }
20986                String perm = args[opti];
20987                opti++;
20988                if (opti >= args.length) {
20989                    pw.println("Error: check-permission missing package argument");
20990                    return;
20991                }
20992
20993                String pkg = args[opti];
20994                opti++;
20995                int user = UserHandle.getUserId(Binder.getCallingUid());
20996                if (opti < args.length) {
20997                    try {
20998                        user = Integer.parseInt(args[opti]);
20999                    } catch (NumberFormatException e) {
21000                        pw.println("Error: check-permission user argument is not a number: "
21001                                + args[opti]);
21002                        return;
21003                    }
21004                }
21005
21006                // Normalize package name to handle renamed packages and static libs
21007                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21008
21009                pw.println(checkPermission(perm, pkg, user));
21010                return;
21011            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21012                dumpState.setDump(DumpState.DUMP_LIBS);
21013            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21014                dumpState.setDump(DumpState.DUMP_FEATURES);
21015            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21016                if (opti >= args.length) {
21017                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21018                            | DumpState.DUMP_SERVICE_RESOLVERS
21019                            | DumpState.DUMP_RECEIVER_RESOLVERS
21020                            | DumpState.DUMP_CONTENT_RESOLVERS);
21021                } else {
21022                    while (opti < args.length) {
21023                        String name = args[opti];
21024                        if ("a".equals(name) || "activity".equals(name)) {
21025                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21026                        } else if ("s".equals(name) || "service".equals(name)) {
21027                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21028                        } else if ("r".equals(name) || "receiver".equals(name)) {
21029                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21030                        } else if ("c".equals(name) || "content".equals(name)) {
21031                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21032                        } else {
21033                            pw.println("Error: unknown resolver table type: " + name);
21034                            return;
21035                        }
21036                        opti++;
21037                    }
21038                }
21039            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21040                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21041            } else if ("permission".equals(cmd)) {
21042                if (opti >= args.length) {
21043                    pw.println("Error: permission requires permission name");
21044                    return;
21045                }
21046                permissionNames = new ArraySet<>();
21047                while (opti < args.length) {
21048                    permissionNames.add(args[opti]);
21049                    opti++;
21050                }
21051                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21052                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21053            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21054                dumpState.setDump(DumpState.DUMP_PREFERRED);
21055            } else if ("preferred-xml".equals(cmd)) {
21056                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21057                if (opti < args.length && "--full".equals(args[opti])) {
21058                    fullPreferred = true;
21059                    opti++;
21060                }
21061            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21062                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21063            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21064                dumpState.setDump(DumpState.DUMP_PACKAGES);
21065            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21066                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21067            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21068                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21069            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21070                dumpState.setDump(DumpState.DUMP_MESSAGES);
21071            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21072                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21073            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21074                    || "intent-filter-verifiers".equals(cmd)) {
21075                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21076            } else if ("version".equals(cmd)) {
21077                dumpState.setDump(DumpState.DUMP_VERSION);
21078            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21079                dumpState.setDump(DumpState.DUMP_KEYSETS);
21080            } else if ("installs".equals(cmd)) {
21081                dumpState.setDump(DumpState.DUMP_INSTALLS);
21082            } else if ("frozen".equals(cmd)) {
21083                dumpState.setDump(DumpState.DUMP_FROZEN);
21084            } else if ("volumes".equals(cmd)) {
21085                dumpState.setDump(DumpState.DUMP_VOLUMES);
21086            } else if ("dexopt".equals(cmd)) {
21087                dumpState.setDump(DumpState.DUMP_DEXOPT);
21088            } else if ("compiler-stats".equals(cmd)) {
21089                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21090            } else if ("changes".equals(cmd)) {
21091                dumpState.setDump(DumpState.DUMP_CHANGES);
21092            } else if ("service-permissions".equals(cmd)) {
21093                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21094            } else if ("write".equals(cmd)) {
21095                synchronized (mPackages) {
21096                    mSettings.writeLPr();
21097                    pw.println("Settings written.");
21098                    return;
21099                }
21100            }
21101        }
21102
21103        if (checkin) {
21104            pw.println("vers,1");
21105        }
21106
21107        // reader
21108        synchronized (mPackages) {
21109            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21110                if (!checkin) {
21111                    if (dumpState.onTitlePrinted())
21112                        pw.println();
21113                    pw.println("Database versions:");
21114                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21115                }
21116            }
21117
21118            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21119                if (!checkin) {
21120                    if (dumpState.onTitlePrinted())
21121                        pw.println();
21122                    pw.println("Verifiers:");
21123                    pw.print("  Required: ");
21124                    pw.print(mRequiredVerifierPackage);
21125                    pw.print(" (uid=");
21126                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21127                            UserHandle.USER_SYSTEM));
21128                    pw.println(")");
21129                } else if (mRequiredVerifierPackage != null) {
21130                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21131                    pw.print(",");
21132                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21133                            UserHandle.USER_SYSTEM));
21134                }
21135            }
21136
21137            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21138                    packageName == null) {
21139                if (mIntentFilterVerifierComponent != null) {
21140                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21141                    if (!checkin) {
21142                        if (dumpState.onTitlePrinted())
21143                            pw.println();
21144                        pw.println("Intent Filter Verifier:");
21145                        pw.print("  Using: ");
21146                        pw.print(verifierPackageName);
21147                        pw.print(" (uid=");
21148                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21149                                UserHandle.USER_SYSTEM));
21150                        pw.println(")");
21151                    } else if (verifierPackageName != null) {
21152                        pw.print("ifv,"); pw.print(verifierPackageName);
21153                        pw.print(",");
21154                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21155                                UserHandle.USER_SYSTEM));
21156                    }
21157                } else {
21158                    pw.println();
21159                    pw.println("No Intent Filter Verifier available!");
21160                }
21161            }
21162
21163            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21164                boolean printedHeader = false;
21165                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21166                while (it.hasNext()) {
21167                    String libName = it.next();
21168                    LongSparseArray<SharedLibraryEntry> versionedLib
21169                            = mSharedLibraries.get(libName);
21170                    if (versionedLib == null) {
21171                        continue;
21172                    }
21173                    final int versionCount = versionedLib.size();
21174                    for (int i = 0; i < versionCount; i++) {
21175                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21176                        if (!checkin) {
21177                            if (!printedHeader) {
21178                                if (dumpState.onTitlePrinted())
21179                                    pw.println();
21180                                pw.println("Libraries:");
21181                                printedHeader = true;
21182                            }
21183                            pw.print("  ");
21184                        } else {
21185                            pw.print("lib,");
21186                        }
21187                        pw.print(libEntry.info.getName());
21188                        if (libEntry.info.isStatic()) {
21189                            pw.print(" version=" + libEntry.info.getLongVersion());
21190                        }
21191                        if (!checkin) {
21192                            pw.print(" -> ");
21193                        }
21194                        if (libEntry.path != null) {
21195                            pw.print(" (jar) ");
21196                            pw.print(libEntry.path);
21197                        } else {
21198                            pw.print(" (apk) ");
21199                            pw.print(libEntry.apk);
21200                        }
21201                        pw.println();
21202                    }
21203                }
21204            }
21205
21206            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21207                if (dumpState.onTitlePrinted())
21208                    pw.println();
21209                if (!checkin) {
21210                    pw.println("Features:");
21211                }
21212
21213                synchronized (mAvailableFeatures) {
21214                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21215                        if (checkin) {
21216                            pw.print("feat,");
21217                            pw.print(feat.name);
21218                            pw.print(",");
21219                            pw.println(feat.version);
21220                        } else {
21221                            pw.print("  ");
21222                            pw.print(feat.name);
21223                            if (feat.version > 0) {
21224                                pw.print(" version=");
21225                                pw.print(feat.version);
21226                            }
21227                            pw.println();
21228                        }
21229                    }
21230                }
21231            }
21232
21233            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21234                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21235                        : "Activity Resolver Table:", "  ", packageName,
21236                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21237                    dumpState.setTitlePrinted(true);
21238                }
21239            }
21240            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21241                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21242                        : "Receiver Resolver Table:", "  ", packageName,
21243                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21244                    dumpState.setTitlePrinted(true);
21245                }
21246            }
21247            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21248                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21249                        : "Service Resolver Table:", "  ", packageName,
21250                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21251                    dumpState.setTitlePrinted(true);
21252                }
21253            }
21254            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21255                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21256                        : "Provider Resolver Table:", "  ", packageName,
21257                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21258                    dumpState.setTitlePrinted(true);
21259                }
21260            }
21261
21262            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21263                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21264                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21265                    int user = mSettings.mPreferredActivities.keyAt(i);
21266                    if (pir.dump(pw,
21267                            dumpState.getTitlePrinted()
21268                                ? "\nPreferred Activities User " + user + ":"
21269                                : "Preferred Activities User " + user + ":", "  ",
21270                            packageName, true, false)) {
21271                        dumpState.setTitlePrinted(true);
21272                    }
21273                }
21274            }
21275
21276            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21277                pw.flush();
21278                FileOutputStream fout = new FileOutputStream(fd);
21279                BufferedOutputStream str = new BufferedOutputStream(fout);
21280                XmlSerializer serializer = new FastXmlSerializer();
21281                try {
21282                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21283                    serializer.startDocument(null, true);
21284                    serializer.setFeature(
21285                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21286                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21287                    serializer.endDocument();
21288                    serializer.flush();
21289                } catch (IllegalArgumentException e) {
21290                    pw.println("Failed writing: " + e);
21291                } catch (IllegalStateException e) {
21292                    pw.println("Failed writing: " + e);
21293                } catch (IOException e) {
21294                    pw.println("Failed writing: " + e);
21295                }
21296            }
21297
21298            if (!checkin
21299                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21300                    && packageName == null) {
21301                pw.println();
21302                int count = mSettings.mPackages.size();
21303                if (count == 0) {
21304                    pw.println("No applications!");
21305                    pw.println();
21306                } else {
21307                    final String prefix = "  ";
21308                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21309                    if (allPackageSettings.size() == 0) {
21310                        pw.println("No domain preferred apps!");
21311                        pw.println();
21312                    } else {
21313                        pw.println("App verification status:");
21314                        pw.println();
21315                        count = 0;
21316                        for (PackageSetting ps : allPackageSettings) {
21317                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21318                            if (ivi == null || ivi.getPackageName() == null) continue;
21319                            pw.println(prefix + "Package: " + ivi.getPackageName());
21320                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21321                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21322                            pw.println();
21323                            count++;
21324                        }
21325                        if (count == 0) {
21326                            pw.println(prefix + "No app verification established.");
21327                            pw.println();
21328                        }
21329                        for (int userId : sUserManager.getUserIds()) {
21330                            pw.println("App linkages for user " + userId + ":");
21331                            pw.println();
21332                            count = 0;
21333                            for (PackageSetting ps : allPackageSettings) {
21334                                final long status = ps.getDomainVerificationStatusForUser(userId);
21335                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21336                                        && !DEBUG_DOMAIN_VERIFICATION) {
21337                                    continue;
21338                                }
21339                                pw.println(prefix + "Package: " + ps.name);
21340                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21341                                String statusStr = IntentFilterVerificationInfo.
21342                                        getStatusStringFromValue(status);
21343                                pw.println(prefix + "Status:  " + statusStr);
21344                                pw.println();
21345                                count++;
21346                            }
21347                            if (count == 0) {
21348                                pw.println(prefix + "No configured app linkages.");
21349                                pw.println();
21350                            }
21351                        }
21352                    }
21353                }
21354            }
21355
21356            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21357                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21358            }
21359
21360            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21361                boolean printedSomething = false;
21362                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21363                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21364                        continue;
21365                    }
21366                    if (!printedSomething) {
21367                        if (dumpState.onTitlePrinted())
21368                            pw.println();
21369                        pw.println("Registered ContentProviders:");
21370                        printedSomething = true;
21371                    }
21372                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21373                    pw.print("    "); pw.println(p.toString());
21374                }
21375                printedSomething = false;
21376                for (Map.Entry<String, PackageParser.Provider> entry :
21377                        mProvidersByAuthority.entrySet()) {
21378                    PackageParser.Provider p = entry.getValue();
21379                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21380                        continue;
21381                    }
21382                    if (!printedSomething) {
21383                        if (dumpState.onTitlePrinted())
21384                            pw.println();
21385                        pw.println("ContentProvider Authorities:");
21386                        printedSomething = true;
21387                    }
21388                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21389                    pw.print("    "); pw.println(p.toString());
21390                    if (p.info != null && p.info.applicationInfo != null) {
21391                        final String appInfo = p.info.applicationInfo.toString();
21392                        pw.print("      applicationInfo="); pw.println(appInfo);
21393                    }
21394                }
21395            }
21396
21397            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21398                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21399            }
21400
21401            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21402                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21403            }
21404
21405            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21406                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21407            }
21408
21409            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21410                if (dumpState.onTitlePrinted()) pw.println();
21411                pw.println("Package Changes:");
21412                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21413                final int K = mChangedPackages.size();
21414                for (int i = 0; i < K; i++) {
21415                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21416                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21417                    final int N = changes.size();
21418                    if (N == 0) {
21419                        pw.print("    "); pw.println("No packages changed");
21420                    } else {
21421                        for (int j = 0; j < N; j++) {
21422                            final String pkgName = changes.valueAt(j);
21423                            final int sequenceNumber = changes.keyAt(j);
21424                            pw.print("    ");
21425                            pw.print("seq=");
21426                            pw.print(sequenceNumber);
21427                            pw.print(", package=");
21428                            pw.println(pkgName);
21429                        }
21430                    }
21431                }
21432            }
21433
21434            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21435                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21436            }
21437
21438            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21439                // XXX should handle packageName != null by dumping only install data that
21440                // the given package is involved with.
21441                if (dumpState.onTitlePrinted()) pw.println();
21442
21443                try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120)) {
21444                    ipw.println();
21445                    ipw.println("Frozen packages:");
21446                    ipw.increaseIndent();
21447                    if (mFrozenPackages.size() == 0) {
21448                        ipw.println("(none)");
21449                    } else {
21450                        for (int i = 0; i < mFrozenPackages.size(); i++) {
21451                            ipw.println(mFrozenPackages.valueAt(i));
21452                        }
21453                    }
21454                    ipw.decreaseIndent();
21455                }
21456            }
21457
21458            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21459                if (dumpState.onTitlePrinted()) pw.println();
21460
21461                try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120)) {
21462                    ipw.println();
21463                    ipw.println("Loaded volumes:");
21464                    ipw.increaseIndent();
21465                    if (mLoadedVolumes.size() == 0) {
21466                        ipw.println("(none)");
21467                    } else {
21468                        for (int i = 0; i < mLoadedVolumes.size(); i++) {
21469                            ipw.println(mLoadedVolumes.valueAt(i));
21470                        }
21471                    }
21472                    ipw.decreaseIndent();
21473                }
21474            }
21475
21476            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21477                    && packageName == null) {
21478                if (dumpState.onTitlePrinted()) pw.println();
21479                pw.println("Service permissions:");
21480
21481                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21482                while (filterIterator.hasNext()) {
21483                    final ServiceIntentInfo info = filterIterator.next();
21484                    final ServiceInfo serviceInfo = info.service.info;
21485                    final String permission = serviceInfo.permission;
21486                    if (permission != null) {
21487                        pw.print("    ");
21488                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21489                        pw.print(": ");
21490                        pw.println(permission);
21491                    }
21492                }
21493            }
21494
21495            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21496                if (dumpState.onTitlePrinted()) pw.println();
21497                dumpDexoptStateLPr(pw, packageName);
21498            }
21499
21500            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21501                if (dumpState.onTitlePrinted()) pw.println();
21502                dumpCompilerStatsLPr(pw, packageName);
21503            }
21504
21505            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21506                if (dumpState.onTitlePrinted()) pw.println();
21507                mSettings.dumpReadMessagesLPr(pw, dumpState);
21508
21509                pw.println();
21510                pw.println("Package warning messages:");
21511                dumpCriticalInfo(pw, null);
21512            }
21513
21514            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21515                dumpCriticalInfo(pw, "msg,");
21516            }
21517        }
21518
21519        // PackageInstaller should be called outside of mPackages lock
21520        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21521            // XXX should handle packageName != null by dumping only install data that
21522            // the given package is involved with.
21523            if (dumpState.onTitlePrinted()) pw.println();
21524            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21525        }
21526    }
21527
21528    private void dumpProto(FileDescriptor fd) {
21529        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21530
21531        synchronized (mPackages) {
21532            final long requiredVerifierPackageToken =
21533                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21534            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21535            proto.write(
21536                    PackageServiceDumpProto.PackageShortProto.UID,
21537                    getPackageUid(
21538                            mRequiredVerifierPackage,
21539                            MATCH_DEBUG_TRIAGED_MISSING,
21540                            UserHandle.USER_SYSTEM));
21541            proto.end(requiredVerifierPackageToken);
21542
21543            if (mIntentFilterVerifierComponent != null) {
21544                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21545                final long verifierPackageToken =
21546                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21547                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21548                proto.write(
21549                        PackageServiceDumpProto.PackageShortProto.UID,
21550                        getPackageUid(
21551                                verifierPackageName,
21552                                MATCH_DEBUG_TRIAGED_MISSING,
21553                                UserHandle.USER_SYSTEM));
21554                proto.end(verifierPackageToken);
21555            }
21556
21557            dumpSharedLibrariesProto(proto);
21558            dumpFeaturesProto(proto);
21559            mSettings.dumpPackagesProto(proto);
21560            mSettings.dumpSharedUsersProto(proto);
21561            dumpCriticalInfo(proto);
21562        }
21563        proto.flush();
21564    }
21565
21566    private void dumpFeaturesProto(ProtoOutputStream proto) {
21567        synchronized (mAvailableFeatures) {
21568            final int count = mAvailableFeatures.size();
21569            for (int i = 0; i < count; i++) {
21570                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21571            }
21572        }
21573    }
21574
21575    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21576        final int count = mSharedLibraries.size();
21577        for (int i = 0; i < count; i++) {
21578            final String libName = mSharedLibraries.keyAt(i);
21579            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21580            if (versionedLib == null) {
21581                continue;
21582            }
21583            final int versionCount = versionedLib.size();
21584            for (int j = 0; j < versionCount; j++) {
21585                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21586                final long sharedLibraryToken =
21587                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21588                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21589                final boolean isJar = (libEntry.path != null);
21590                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21591                if (isJar) {
21592                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21593                } else {
21594                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21595                }
21596                proto.end(sharedLibraryToken);
21597            }
21598        }
21599    }
21600
21601    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21602        try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ")) {
21603            ipw.println();
21604            ipw.println("Dexopt state:");
21605            ipw.increaseIndent();
21606            Collection<PackageParser.Package> packages = null;
21607            if (packageName != null) {
21608                PackageParser.Package targetPackage = mPackages.get(packageName);
21609                if (targetPackage != null) {
21610                    packages = Collections.singletonList(targetPackage);
21611                } else {
21612                    ipw.println("Unable to find package: " + packageName);
21613                    return;
21614                }
21615            } else {
21616                packages = mPackages.values();
21617            }
21618
21619            for (PackageParser.Package pkg : packages) {
21620                ipw.println("[" + pkg.packageName + "]");
21621                ipw.increaseIndent();
21622                mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21623                        mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21624                ipw.decreaseIndent();
21625            }
21626        }
21627    }
21628
21629    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21630        try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ")) {
21631            ipw.println();
21632            ipw.println("Compiler stats:");
21633            ipw.increaseIndent();
21634            Collection<PackageParser.Package> packages = null;
21635            if (packageName != null) {
21636                PackageParser.Package targetPackage = mPackages.get(packageName);
21637                if (targetPackage != null) {
21638                    packages = Collections.singletonList(targetPackage);
21639                } else {
21640                    ipw.println("Unable to find package: " + packageName);
21641                    return;
21642                }
21643            } else {
21644                packages = mPackages.values();
21645            }
21646
21647            for (PackageParser.Package pkg : packages) {
21648                ipw.println("[" + pkg.packageName + "]");
21649                ipw.increaseIndent();
21650
21651                CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21652                if (stats == null) {
21653                    ipw.println("(No recorded stats)");
21654                } else {
21655                    stats.dump(ipw);
21656                }
21657                ipw.decreaseIndent();
21658            }
21659        }
21660    }
21661
21662    private String dumpDomainString(String packageName) {
21663        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21664                .getList();
21665        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21666
21667        ArraySet<String> result = new ArraySet<>();
21668        if (iviList.size() > 0) {
21669            for (IntentFilterVerificationInfo ivi : iviList) {
21670                for (String host : ivi.getDomains()) {
21671                    result.add(host);
21672                }
21673            }
21674        }
21675        if (filters != null && filters.size() > 0) {
21676            for (IntentFilter filter : filters) {
21677                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21678                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21679                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21680                    result.addAll(filter.getHostsList());
21681                }
21682            }
21683        }
21684
21685        StringBuilder sb = new StringBuilder(result.size() * 16);
21686        for (String domain : result) {
21687            if (sb.length() > 0) sb.append(" ");
21688            sb.append(domain);
21689        }
21690        return sb.toString();
21691    }
21692
21693    // ------- apps on sdcard specific code -------
21694    static final boolean DEBUG_SD_INSTALL = false;
21695
21696    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21697
21698    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21699
21700    private boolean mMediaMounted = false;
21701
21702    static String getEncryptKey() {
21703        try {
21704            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21705                    SD_ENCRYPTION_KEYSTORE_NAME);
21706            if (sdEncKey == null) {
21707                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21708                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21709                if (sdEncKey == null) {
21710                    Slog.e(TAG, "Failed to create encryption keys");
21711                    return null;
21712                }
21713            }
21714            return sdEncKey;
21715        } catch (NoSuchAlgorithmException nsae) {
21716            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21717            return null;
21718        } catch (IOException ioe) {
21719            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21720            return null;
21721        }
21722    }
21723
21724    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21725            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21726        final int size = infos.size();
21727        final String[] packageNames = new String[size];
21728        final int[] packageUids = new int[size];
21729        for (int i = 0; i < size; i++) {
21730            final ApplicationInfo info = infos.get(i);
21731            packageNames[i] = info.packageName;
21732            packageUids[i] = info.uid;
21733        }
21734        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21735                finishedReceiver);
21736    }
21737
21738    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21739            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21740        sendResourcesChangedBroadcast(mediaStatus, replacing,
21741                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21742    }
21743
21744    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21745            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21746        int size = pkgList.length;
21747        if (size > 0) {
21748            // Send broadcasts here
21749            Bundle extras = new Bundle();
21750            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21751            if (uidArr != null) {
21752                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21753            }
21754            if (replacing) {
21755                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21756            }
21757            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21758                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21759            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
21760        }
21761    }
21762
21763    private void loadPrivatePackages(final VolumeInfo vol) {
21764        mHandler.post(new Runnable() {
21765            @Override
21766            public void run() {
21767                loadPrivatePackagesInner(vol);
21768            }
21769        });
21770    }
21771
21772    private void loadPrivatePackagesInner(VolumeInfo vol) {
21773        final String volumeUuid = vol.fsUuid;
21774        if (TextUtils.isEmpty(volumeUuid)) {
21775            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21776            return;
21777        }
21778
21779        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21780        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21781        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21782
21783        final VersionInfo ver;
21784        final List<PackageSetting> packages;
21785        synchronized (mPackages) {
21786            ver = mSettings.findOrCreateVersion(volumeUuid);
21787            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21788        }
21789
21790        for (PackageSetting ps : packages) {
21791            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21792            synchronized (mInstallLock) {
21793                final PackageParser.Package pkg;
21794                try {
21795                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21796                    loaded.add(pkg.applicationInfo);
21797
21798                } catch (PackageManagerException e) {
21799                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21800                }
21801
21802                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21803                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21804                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21805                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21806                }
21807            }
21808        }
21809
21810        // Reconcile app data for all started/unlocked users
21811        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21812        final UserManager um = mContext.getSystemService(UserManager.class);
21813        UserManagerInternal umInternal = getUserManagerInternal();
21814        for (UserInfo user : um.getUsers()) {
21815            final int flags;
21816            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21817                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21818            } else if (umInternal.isUserRunning(user.id)) {
21819                flags = StorageManager.FLAG_STORAGE_DE;
21820            } else {
21821                continue;
21822            }
21823
21824            try {
21825                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21826                synchronized (mInstallLock) {
21827                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21828                }
21829            } catch (IllegalStateException e) {
21830                // Device was probably ejected, and we'll process that event momentarily
21831                Slog.w(TAG, "Failed to prepare storage: " + e);
21832            }
21833        }
21834
21835        synchronized (mPackages) {
21836            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
21837            if (sdkUpdated) {
21838                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21839                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21840            }
21841            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
21842                    mPermissionCallback);
21843
21844            // Yay, everything is now upgraded
21845            ver.forceCurrent();
21846
21847            mSettings.writeLPr();
21848        }
21849
21850        for (PackageFreezer freezer : freezers) {
21851            freezer.close();
21852        }
21853
21854        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21855        sendResourcesChangedBroadcast(true, false, loaded, null);
21856        mLoadedVolumes.add(vol.getId());
21857    }
21858
21859    private void unloadPrivatePackages(final VolumeInfo vol) {
21860        mHandler.post(new Runnable() {
21861            @Override
21862            public void run() {
21863                unloadPrivatePackagesInner(vol);
21864            }
21865        });
21866    }
21867
21868    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21869        final String volumeUuid = vol.fsUuid;
21870        if (TextUtils.isEmpty(volumeUuid)) {
21871            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21872            return;
21873        }
21874
21875        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21876        synchronized (mInstallLock) {
21877        synchronized (mPackages) {
21878            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21879            for (PackageSetting ps : packages) {
21880                if (ps.pkg == null) continue;
21881
21882                final ApplicationInfo info = ps.pkg.applicationInfo;
21883                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21884                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21885
21886                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21887                        "unloadPrivatePackagesInner")) {
21888                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21889                            false, null)) {
21890                        unloaded.add(info);
21891                    } else {
21892                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21893                    }
21894                }
21895
21896                // Try very hard to release any references to this package
21897                // so we don't risk the system server being killed due to
21898                // open FDs
21899                AttributeCache.instance().removePackage(ps.name);
21900            }
21901
21902            mSettings.writeLPr();
21903        }
21904        }
21905
21906        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21907        sendResourcesChangedBroadcast(false, false, unloaded, null);
21908        mLoadedVolumes.remove(vol.getId());
21909
21910        // Try very hard to release any references to this path so we don't risk
21911        // the system server being killed due to open FDs
21912        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21913
21914        for (int i = 0; i < 3; i++) {
21915            System.gc();
21916            System.runFinalization();
21917        }
21918    }
21919
21920    private void assertPackageKnown(String volumeUuid, String packageName)
21921            throws PackageManagerException {
21922        synchronized (mPackages) {
21923            // Normalize package name to handle renamed packages
21924            packageName = normalizePackageNameLPr(packageName);
21925
21926            final PackageSetting ps = mSettings.mPackages.get(packageName);
21927            if (ps == null) {
21928                throw new PackageManagerException("Package " + packageName + " is unknown");
21929            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21930                throw new PackageManagerException(
21931                        "Package " + packageName + " found on unknown volume " + volumeUuid
21932                                + "; expected volume " + ps.volumeUuid);
21933            }
21934        }
21935    }
21936
21937    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21938            throws PackageManagerException {
21939        synchronized (mPackages) {
21940            // Normalize package name to handle renamed packages
21941            packageName = normalizePackageNameLPr(packageName);
21942
21943            final PackageSetting ps = mSettings.mPackages.get(packageName);
21944            if (ps == null) {
21945                throw new PackageManagerException("Package " + packageName + " is unknown");
21946            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21947                throw new PackageManagerException(
21948                        "Package " + packageName + " found on unknown volume " + volumeUuid
21949                                + "; expected volume " + ps.volumeUuid);
21950            } else if (!ps.getInstalled(userId)) {
21951                throw new PackageManagerException(
21952                        "Package " + packageName + " not installed for user " + userId);
21953            }
21954        }
21955    }
21956
21957    private List<String> collectAbsoluteCodePaths() {
21958        synchronized (mPackages) {
21959            List<String> codePaths = new ArrayList<>();
21960            final int packageCount = mSettings.mPackages.size();
21961            for (int i = 0; i < packageCount; i++) {
21962                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21963                codePaths.add(ps.codePath.getAbsolutePath());
21964            }
21965            return codePaths;
21966        }
21967    }
21968
21969    /**
21970     * Examine all apps present on given mounted volume, and destroy apps that
21971     * aren't expected, either due to uninstallation or reinstallation on
21972     * another volume.
21973     */
21974    private void reconcileApps(String volumeUuid) {
21975        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21976        List<File> filesToDelete = null;
21977
21978        final File[] files = FileUtils.listFilesOrEmpty(
21979                Environment.getDataAppDirectory(volumeUuid));
21980        for (File file : files) {
21981            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21982                    && !PackageInstallerService.isStageName(file.getName());
21983            if (!isPackage) {
21984                // Ignore entries which are not packages
21985                continue;
21986            }
21987
21988            String absolutePath = file.getAbsolutePath();
21989
21990            boolean pathValid = false;
21991            final int absoluteCodePathCount = absoluteCodePaths.size();
21992            for (int i = 0; i < absoluteCodePathCount; i++) {
21993                String absoluteCodePath = absoluteCodePaths.get(i);
21994                if (absolutePath.startsWith(absoluteCodePath)) {
21995                    pathValid = true;
21996                    break;
21997                }
21998            }
21999
22000            if (!pathValid) {
22001                if (filesToDelete == null) {
22002                    filesToDelete = new ArrayList<>();
22003                }
22004                filesToDelete.add(file);
22005            }
22006        }
22007
22008        if (filesToDelete != null) {
22009            final int fileToDeleteCount = filesToDelete.size();
22010            for (int i = 0; i < fileToDeleteCount; i++) {
22011                File fileToDelete = filesToDelete.get(i);
22012                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22013                synchronized (mInstallLock) {
22014                    removeCodePathLI(fileToDelete);
22015                }
22016            }
22017        }
22018    }
22019
22020    /**
22021     * Reconcile all app data for the given user.
22022     * <p>
22023     * Verifies that directories exist and that ownership and labeling is
22024     * correct for all installed apps on all mounted volumes.
22025     */
22026    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22027        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22028        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22029            final String volumeUuid = vol.getFsUuid();
22030            synchronized (mInstallLock) {
22031                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22032            }
22033        }
22034    }
22035
22036    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22037            boolean migrateAppData) {
22038        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22039    }
22040
22041    /**
22042     * Reconcile all app data on given mounted volume.
22043     * <p>
22044     * Destroys app data that isn't expected, either due to uninstallation or
22045     * reinstallation on another volume.
22046     * <p>
22047     * Verifies that directories exist and that ownership and labeling is
22048     * correct for all installed apps.
22049     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22050     */
22051    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22052            boolean migrateAppData, boolean onlyCoreApps) {
22053        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22054                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22055        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22056
22057        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22058        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22059
22060        // First look for stale data that doesn't belong, and check if things
22061        // have changed since we did our last restorecon
22062        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22063            if (StorageManager.isFileEncryptedNativeOrEmulated()
22064                    && !StorageManager.isUserKeyUnlocked(userId)) {
22065                throw new RuntimeException(
22066                        "Yikes, someone asked us to reconcile CE storage while " + userId
22067                                + " was still locked; this would have caused massive data loss!");
22068            }
22069
22070            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22071            for (File file : files) {
22072                final String packageName = file.getName();
22073                try {
22074                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22075                } catch (PackageManagerException e) {
22076                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22077                    try {
22078                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22079                                StorageManager.FLAG_STORAGE_CE, 0);
22080                    } catch (InstallerException e2) {
22081                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22082                    }
22083                }
22084            }
22085        }
22086        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22087            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22088            for (File file : files) {
22089                final String packageName = file.getName();
22090                try {
22091                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22092                } catch (PackageManagerException e) {
22093                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22094                    try {
22095                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22096                                StorageManager.FLAG_STORAGE_DE, 0);
22097                    } catch (InstallerException e2) {
22098                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22099                    }
22100                }
22101            }
22102        }
22103
22104        // Ensure that data directories are ready to roll for all packages
22105        // installed for this volume and user
22106        final List<PackageSetting> packages;
22107        synchronized (mPackages) {
22108            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22109        }
22110        int preparedCount = 0;
22111        for (PackageSetting ps : packages) {
22112            final String packageName = ps.name;
22113            if (ps.pkg == null) {
22114                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22115                // TODO: might be due to legacy ASEC apps; we should circle back
22116                // and reconcile again once they're scanned
22117                continue;
22118            }
22119            // Skip non-core apps if requested
22120            if (onlyCoreApps && !ps.pkg.coreApp) {
22121                result.add(packageName);
22122                continue;
22123            }
22124
22125            if (ps.getInstalled(userId)) {
22126                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22127                preparedCount++;
22128            }
22129        }
22130
22131        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22132        return result;
22133    }
22134
22135    /**
22136     * Prepare app data for the given app just after it was installed or
22137     * upgraded. This method carefully only touches users that it's installed
22138     * for, and it forces a restorecon to handle any seinfo changes.
22139     * <p>
22140     * Verifies that directories exist and that ownership and labeling is
22141     * correct for all installed apps. If there is an ownership mismatch, it
22142     * will try recovering system apps by wiping data; third-party app data is
22143     * left intact.
22144     * <p>
22145     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22146     */
22147    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22148        final PackageSetting ps;
22149        synchronized (mPackages) {
22150            ps = mSettings.mPackages.get(pkg.packageName);
22151            mSettings.writeKernelMappingLPr(ps);
22152        }
22153
22154        final UserManager um = mContext.getSystemService(UserManager.class);
22155        UserManagerInternal umInternal = getUserManagerInternal();
22156        for (UserInfo user : um.getUsers()) {
22157            final int flags;
22158            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22159                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22160            } else if (umInternal.isUserRunning(user.id)) {
22161                flags = StorageManager.FLAG_STORAGE_DE;
22162            } else {
22163                continue;
22164            }
22165
22166            if (ps.getInstalled(user.id)) {
22167                // TODO: when user data is locked, mark that we're still dirty
22168                prepareAppDataLIF(pkg, user.id, flags);
22169            }
22170        }
22171    }
22172
22173    /**
22174     * Prepare app data for the given app.
22175     * <p>
22176     * Verifies that directories exist and that ownership and labeling is
22177     * correct for all installed apps. If there is an ownership mismatch, this
22178     * will try recovering system apps by wiping data; third-party app data is
22179     * left intact.
22180     */
22181    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22182        if (pkg == null) {
22183            Slog.wtf(TAG, "Package was null!", new Throwable());
22184            return;
22185        }
22186        prepareAppDataLeafLIF(pkg, userId, flags);
22187        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22188        for (int i = 0; i < childCount; i++) {
22189            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22190        }
22191    }
22192
22193    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22194            boolean maybeMigrateAppData) {
22195        prepareAppDataLIF(pkg, userId, flags);
22196
22197        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22198            // We may have just shuffled around app data directories, so
22199            // prepare them one more time
22200            prepareAppDataLIF(pkg, userId, flags);
22201        }
22202    }
22203
22204    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22205        if (DEBUG_APP_DATA) {
22206            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22207                    + Integer.toHexString(flags));
22208        }
22209
22210        final String volumeUuid = pkg.volumeUuid;
22211        final String packageName = pkg.packageName;
22212        final ApplicationInfo app = pkg.applicationInfo;
22213        final int appId = UserHandle.getAppId(app.uid);
22214
22215        Preconditions.checkNotNull(app.seInfo);
22216
22217        long ceDataInode = -1;
22218        try {
22219            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22220                    appId, app.seInfo, app.targetSdkVersion);
22221        } catch (InstallerException e) {
22222            if (app.isSystemApp()) {
22223                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22224                        + ", but trying to recover: " + e);
22225                destroyAppDataLeafLIF(pkg, userId, flags);
22226                try {
22227                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22228                            appId, app.seInfo, app.targetSdkVersion);
22229                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22230                } catch (InstallerException e2) {
22231                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22232                }
22233            } else {
22234                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22235            }
22236        }
22237        // Prepare the application profiles.
22238        mArtManagerService.prepareAppProfiles(pkg, userId);
22239
22240        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22241            // TODO: mark this structure as dirty so we persist it!
22242            synchronized (mPackages) {
22243                final PackageSetting ps = mSettings.mPackages.get(packageName);
22244                if (ps != null) {
22245                    ps.setCeDataInode(ceDataInode, userId);
22246                }
22247            }
22248        }
22249
22250        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22251    }
22252
22253    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22254        if (pkg == null) {
22255            Slog.wtf(TAG, "Package was null!", new Throwable());
22256            return;
22257        }
22258        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22259        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22260        for (int i = 0; i < childCount; i++) {
22261            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22262        }
22263    }
22264
22265    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22266        final String volumeUuid = pkg.volumeUuid;
22267        final String packageName = pkg.packageName;
22268        final ApplicationInfo app = pkg.applicationInfo;
22269
22270        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22271            // Create a native library symlink only if we have native libraries
22272            // and if the native libraries are 32 bit libraries. We do not provide
22273            // this symlink for 64 bit libraries.
22274            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22275                final String nativeLibPath = app.nativeLibraryDir;
22276                try {
22277                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22278                            nativeLibPath, userId);
22279                } catch (InstallerException e) {
22280                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22281                }
22282            }
22283        }
22284    }
22285
22286    /**
22287     * For system apps on non-FBE devices, this method migrates any existing
22288     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22289     * requested by the app.
22290     */
22291    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22292        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22293                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22294            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22295                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22296            try {
22297                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22298                        storageTarget);
22299            } catch (InstallerException e) {
22300                logCriticalInfo(Log.WARN,
22301                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22302            }
22303            return true;
22304        } else {
22305            return false;
22306        }
22307    }
22308
22309    public PackageFreezer freezePackage(String packageName, String killReason) {
22310        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22311    }
22312
22313    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22314        return new PackageFreezer(packageName, userId, killReason);
22315    }
22316
22317    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22318            String killReason) {
22319        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22320    }
22321
22322    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22323            String killReason) {
22324        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22325            return new PackageFreezer();
22326        } else {
22327            return freezePackage(packageName, userId, killReason);
22328        }
22329    }
22330
22331    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22332            String killReason) {
22333        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22334    }
22335
22336    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22337            String killReason) {
22338        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22339            return new PackageFreezer();
22340        } else {
22341            return freezePackage(packageName, userId, killReason);
22342        }
22343    }
22344
22345    /**
22346     * Class that freezes and kills the given package upon creation, and
22347     * unfreezes it upon closing. This is typically used when doing surgery on
22348     * app code/data to prevent the app from running while you're working.
22349     */
22350    private class PackageFreezer implements AutoCloseable {
22351        private final String mPackageName;
22352        private final PackageFreezer[] mChildren;
22353
22354        private final boolean mWeFroze;
22355
22356        private final AtomicBoolean mClosed = new AtomicBoolean();
22357        private final CloseGuard mCloseGuard = CloseGuard.get();
22358
22359        /**
22360         * Create and return a stub freezer that doesn't actually do anything,
22361         * typically used when someone requested
22362         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22363         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22364         */
22365        public PackageFreezer() {
22366            mPackageName = null;
22367            mChildren = null;
22368            mWeFroze = false;
22369            mCloseGuard.open("close");
22370        }
22371
22372        public PackageFreezer(String packageName, int userId, String killReason) {
22373            synchronized (mPackages) {
22374                mPackageName = packageName;
22375                mWeFroze = mFrozenPackages.add(mPackageName);
22376
22377                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22378                if (ps != null) {
22379                    killApplication(ps.name, ps.appId, userId, killReason);
22380                }
22381
22382                final PackageParser.Package p = mPackages.get(packageName);
22383                if (p != null && p.childPackages != null) {
22384                    final int N = p.childPackages.size();
22385                    mChildren = new PackageFreezer[N];
22386                    for (int i = 0; i < N; i++) {
22387                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22388                                userId, killReason);
22389                    }
22390                } else {
22391                    mChildren = null;
22392                }
22393            }
22394            mCloseGuard.open("close");
22395        }
22396
22397        @Override
22398        protected void finalize() throws Throwable {
22399            try {
22400                if (mCloseGuard != null) {
22401                    mCloseGuard.warnIfOpen();
22402                }
22403
22404                close();
22405            } finally {
22406                super.finalize();
22407            }
22408        }
22409
22410        @Override
22411        public void close() {
22412            mCloseGuard.close();
22413            if (mClosed.compareAndSet(false, true)) {
22414                synchronized (mPackages) {
22415                    if (mWeFroze) {
22416                        mFrozenPackages.remove(mPackageName);
22417                    }
22418
22419                    if (mChildren != null) {
22420                        for (PackageFreezer freezer : mChildren) {
22421                            freezer.close();
22422                        }
22423                    }
22424                }
22425            }
22426        }
22427    }
22428
22429    /**
22430     * Verify that given package is currently frozen.
22431     */
22432    private void checkPackageFrozen(String packageName) {
22433        synchronized (mPackages) {
22434            if (!mFrozenPackages.contains(packageName)) {
22435                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22436            }
22437        }
22438    }
22439
22440    @Override
22441    public int movePackage(final String packageName, final String volumeUuid) {
22442        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22443
22444        final int callingUid = Binder.getCallingUid();
22445        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22446        final int moveId = mNextMoveId.getAndIncrement();
22447        mHandler.post(new Runnable() {
22448            @Override
22449            public void run() {
22450                try {
22451                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22452                } catch (PackageManagerException e) {
22453                    Slog.w(TAG, "Failed to move " + packageName, e);
22454                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22455                }
22456            }
22457        });
22458        return moveId;
22459    }
22460
22461    private void movePackageInternal(final String packageName, final String volumeUuid,
22462            final int moveId, final int callingUid, UserHandle user)
22463                    throws PackageManagerException {
22464        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22465        final PackageManager pm = mContext.getPackageManager();
22466
22467        final boolean currentAsec;
22468        final String currentVolumeUuid;
22469        final File codeFile;
22470        final String installerPackageName;
22471        final String packageAbiOverride;
22472        final int appId;
22473        final String seinfo;
22474        final String label;
22475        final int targetSdkVersion;
22476        final PackageFreezer freezer;
22477        final int[] installedUserIds;
22478
22479        // reader
22480        synchronized (mPackages) {
22481            final PackageParser.Package pkg = mPackages.get(packageName);
22482            final PackageSetting ps = mSettings.mPackages.get(packageName);
22483            if (pkg == null
22484                    || ps == null
22485                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22486                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22487            }
22488            if (pkg.applicationInfo.isSystemApp()) {
22489                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22490                        "Cannot move system application");
22491            }
22492
22493            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22494            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22495                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22496            if (isInternalStorage && !allow3rdPartyOnInternal) {
22497                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22498                        "3rd party apps are not allowed on internal storage");
22499            }
22500
22501            if (pkg.applicationInfo.isExternalAsec()) {
22502                currentAsec = true;
22503                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22504            } else if (pkg.applicationInfo.isForwardLocked()) {
22505                currentAsec = true;
22506                currentVolumeUuid = "forward_locked";
22507            } else {
22508                currentAsec = false;
22509                currentVolumeUuid = ps.volumeUuid;
22510
22511                final File probe = new File(pkg.codePath);
22512                final File probeOat = new File(probe, "oat");
22513                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22514                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22515                            "Move only supported for modern cluster style installs");
22516                }
22517            }
22518
22519            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22520                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22521                        "Package already moved to " + volumeUuid);
22522            }
22523            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22524                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22525                        "Device admin cannot be moved");
22526            }
22527
22528            if (mFrozenPackages.contains(packageName)) {
22529                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22530                        "Failed to move already frozen package");
22531            }
22532
22533            codeFile = new File(pkg.codePath);
22534            installerPackageName = ps.installerPackageName;
22535            packageAbiOverride = ps.cpuAbiOverrideString;
22536            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22537            seinfo = pkg.applicationInfo.seInfo;
22538            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22539            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22540            freezer = freezePackage(packageName, "movePackageInternal");
22541            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22542        }
22543
22544        final Bundle extras = new Bundle();
22545        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22546        extras.putString(Intent.EXTRA_TITLE, label);
22547        mMoveCallbacks.notifyCreated(moveId, extras);
22548
22549        int installFlags;
22550        final boolean moveCompleteApp;
22551        final File measurePath;
22552
22553        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22554            installFlags = INSTALL_INTERNAL;
22555            moveCompleteApp = !currentAsec;
22556            measurePath = Environment.getDataAppDirectory(volumeUuid);
22557        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22558            installFlags = INSTALL_EXTERNAL;
22559            moveCompleteApp = false;
22560            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22561        } else {
22562            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22563            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22564                    || !volume.isMountedWritable()) {
22565                freezer.close();
22566                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22567                        "Move location not mounted private volume");
22568            }
22569
22570            Preconditions.checkState(!currentAsec);
22571
22572            installFlags = INSTALL_INTERNAL;
22573            moveCompleteApp = true;
22574            measurePath = Environment.getDataAppDirectory(volumeUuid);
22575        }
22576
22577        // If we're moving app data around, we need all the users unlocked
22578        if (moveCompleteApp) {
22579            for (int userId : installedUserIds) {
22580                if (StorageManager.isFileEncryptedNativeOrEmulated()
22581                        && !StorageManager.isUserKeyUnlocked(userId)) {
22582                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22583                            "User " + userId + " must be unlocked");
22584                }
22585            }
22586        }
22587
22588        final PackageStats stats = new PackageStats(null, -1);
22589        synchronized (mInstaller) {
22590            for (int userId : installedUserIds) {
22591                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22592                    freezer.close();
22593                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22594                            "Failed to measure package size");
22595                }
22596            }
22597        }
22598
22599        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22600                + stats.dataSize);
22601
22602        final long startFreeBytes = measurePath.getUsableSpace();
22603        final long sizeBytes;
22604        if (moveCompleteApp) {
22605            sizeBytes = stats.codeSize + stats.dataSize;
22606        } else {
22607            sizeBytes = stats.codeSize;
22608        }
22609
22610        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22611            freezer.close();
22612            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22613                    "Not enough free space to move");
22614        }
22615
22616        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22617
22618        final CountDownLatch installedLatch = new CountDownLatch(1);
22619        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22620            @Override
22621            public void onUserActionRequired(Intent intent) throws RemoteException {
22622                throw new IllegalStateException();
22623            }
22624
22625            @Override
22626            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22627                    Bundle extras) throws RemoteException {
22628                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22629                        + PackageManager.installStatusToString(returnCode, msg));
22630
22631                installedLatch.countDown();
22632                freezer.close();
22633
22634                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22635                switch (status) {
22636                    case PackageInstaller.STATUS_SUCCESS:
22637                        mMoveCallbacks.notifyStatusChanged(moveId,
22638                                PackageManager.MOVE_SUCCEEDED);
22639                        break;
22640                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22641                        mMoveCallbacks.notifyStatusChanged(moveId,
22642                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22643                        break;
22644                    default:
22645                        mMoveCallbacks.notifyStatusChanged(moveId,
22646                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22647                        break;
22648                }
22649            }
22650        };
22651
22652        final MoveInfo move;
22653        if (moveCompleteApp) {
22654            // Kick off a thread to report progress estimates
22655            new Thread() {
22656                @Override
22657                public void run() {
22658                    while (true) {
22659                        try {
22660                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22661                                break;
22662                            }
22663                        } catch (InterruptedException ignored) {
22664                        }
22665
22666                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22667                        final int progress = 10 + (int) MathUtils.constrain(
22668                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22669                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22670                    }
22671                }
22672            }.start();
22673
22674            final String dataAppName = codeFile.getName();
22675            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22676                    dataAppName, appId, seinfo, targetSdkVersion);
22677        } else {
22678            move = null;
22679        }
22680
22681        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22682
22683        final Message msg = mHandler.obtainMessage(INIT_COPY);
22684        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22685        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22686                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22687                packageAbiOverride, null /*grantedPermissions*/,
22688                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22689        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22690        msg.obj = params;
22691
22692        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22693                System.identityHashCode(msg.obj));
22694        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22695                System.identityHashCode(msg.obj));
22696
22697        mHandler.sendMessage(msg);
22698    }
22699
22700    @Override
22701    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22702        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22703
22704        final int realMoveId = mNextMoveId.getAndIncrement();
22705        final Bundle extras = new Bundle();
22706        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22707        mMoveCallbacks.notifyCreated(realMoveId, extras);
22708
22709        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22710            @Override
22711            public void onCreated(int moveId, Bundle extras) {
22712                // Ignored
22713            }
22714
22715            @Override
22716            public void onStatusChanged(int moveId, int status, long estMillis) {
22717                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22718            }
22719        };
22720
22721        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22722        storage.setPrimaryStorageUuid(volumeUuid, callback);
22723        return realMoveId;
22724    }
22725
22726    @Override
22727    public int getMoveStatus(int moveId) {
22728        mContext.enforceCallingOrSelfPermission(
22729                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22730        return mMoveCallbacks.mLastStatus.get(moveId);
22731    }
22732
22733    @Override
22734    public void registerMoveCallback(IPackageMoveObserver callback) {
22735        mContext.enforceCallingOrSelfPermission(
22736                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22737        mMoveCallbacks.register(callback);
22738    }
22739
22740    @Override
22741    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22742        mContext.enforceCallingOrSelfPermission(
22743                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22744        mMoveCallbacks.unregister(callback);
22745    }
22746
22747    @Override
22748    public boolean setInstallLocation(int loc) {
22749        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22750                null);
22751        if (getInstallLocation() == loc) {
22752            return true;
22753        }
22754        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22755                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22756            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22757                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22758            return true;
22759        }
22760        return false;
22761   }
22762
22763    @Override
22764    public int getInstallLocation() {
22765        // allow instant app access
22766        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22767                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22768                PackageHelper.APP_INSTALL_AUTO);
22769    }
22770
22771    /** Called by UserManagerService */
22772    void cleanUpUser(UserManagerService userManager, int userHandle) {
22773        synchronized (mPackages) {
22774            mDirtyUsers.remove(userHandle);
22775            mUserNeedsBadging.delete(userHandle);
22776            mSettings.removeUserLPw(userHandle);
22777            mPendingBroadcasts.remove(userHandle);
22778            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22779            removeUnusedPackagesLPw(userManager, userHandle);
22780        }
22781    }
22782
22783    /**
22784     * We're removing userHandle and would like to remove any downloaded packages
22785     * that are no longer in use by any other user.
22786     * @param userHandle the user being removed
22787     */
22788    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22789        final boolean DEBUG_CLEAN_APKS = false;
22790        int [] users = userManager.getUserIds();
22791        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22792        while (psit.hasNext()) {
22793            PackageSetting ps = psit.next();
22794            if (ps.pkg == null) {
22795                continue;
22796            }
22797            final String packageName = ps.pkg.packageName;
22798            // Skip over if system app
22799            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22800                continue;
22801            }
22802            if (DEBUG_CLEAN_APKS) {
22803                Slog.i(TAG, "Checking package " + packageName);
22804            }
22805            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22806            if (keep) {
22807                if (DEBUG_CLEAN_APKS) {
22808                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22809                }
22810            } else {
22811                for (int i = 0; i < users.length; i++) {
22812                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22813                        keep = true;
22814                        if (DEBUG_CLEAN_APKS) {
22815                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22816                                    + users[i]);
22817                        }
22818                        break;
22819                    }
22820                }
22821            }
22822            if (!keep) {
22823                if (DEBUG_CLEAN_APKS) {
22824                    Slog.i(TAG, "  Removing package " + packageName);
22825                }
22826                mHandler.post(new Runnable() {
22827                    public void run() {
22828                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22829                                userHandle, 0);
22830                    } //end run
22831                });
22832            }
22833        }
22834    }
22835
22836    /** Called by UserManagerService */
22837    void createNewUser(int userId, String[] disallowedPackages) {
22838        synchronized (mInstallLock) {
22839            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22840        }
22841        synchronized (mPackages) {
22842            scheduleWritePackageRestrictionsLocked(userId);
22843            scheduleWritePackageListLocked(userId);
22844            applyFactoryDefaultBrowserLPw(userId);
22845            primeDomainVerificationsLPw(userId);
22846        }
22847    }
22848
22849    void onNewUserCreated(final int userId) {
22850        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22851        synchronized(mPackages) {
22852            // If permission review for legacy apps is required, we represent
22853            // dagerous permissions for such apps as always granted runtime
22854            // permissions to keep per user flag state whether review is needed.
22855            // Hence, if a new user is added we have to propagate dangerous
22856            // permission grants for these legacy apps.
22857            if (mSettings.mPermissions.mPermissionReviewRequired) {
22858// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
22859                mPermissionManager.updateAllPermissions(
22860                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
22861                        mPermissionCallback);
22862            }
22863        }
22864    }
22865
22866    @Override
22867    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22868        mContext.enforceCallingOrSelfPermission(
22869                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22870                "Only package verification agents can read the verifier device identity");
22871
22872        synchronized (mPackages) {
22873            return mSettings.getVerifierDeviceIdentityLPw();
22874        }
22875    }
22876
22877    @Override
22878    public void setPermissionEnforced(String permission, boolean enforced) {
22879        // TODO: Now that we no longer change GID for storage, this should to away.
22880        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22881                "setPermissionEnforced");
22882        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22883            synchronized (mPackages) {
22884                if (mSettings.mReadExternalStorageEnforced == null
22885                        || mSettings.mReadExternalStorageEnforced != enforced) {
22886                    mSettings.mReadExternalStorageEnforced =
22887                            enforced ? Boolean.TRUE : Boolean.FALSE;
22888                    mSettings.writeLPr();
22889                }
22890            }
22891            // kill any non-foreground processes so we restart them and
22892            // grant/revoke the GID.
22893            final IActivityManager am = ActivityManager.getService();
22894            if (am != null) {
22895                final long token = Binder.clearCallingIdentity();
22896                try {
22897                    am.killProcessesBelowForeground("setPermissionEnforcement");
22898                } catch (RemoteException e) {
22899                } finally {
22900                    Binder.restoreCallingIdentity(token);
22901                }
22902            }
22903        } else {
22904            throw new IllegalArgumentException("No selective enforcement for " + permission);
22905        }
22906    }
22907
22908    @Override
22909    @Deprecated
22910    public boolean isPermissionEnforced(String permission) {
22911        // allow instant applications
22912        return true;
22913    }
22914
22915    @Override
22916    public boolean isStorageLow() {
22917        // allow instant applications
22918        final long token = Binder.clearCallingIdentity();
22919        try {
22920            final DeviceStorageMonitorInternal
22921                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22922            if (dsm != null) {
22923                return dsm.isMemoryLow();
22924            } else {
22925                return false;
22926            }
22927        } finally {
22928            Binder.restoreCallingIdentity(token);
22929        }
22930    }
22931
22932    @Override
22933    public IPackageInstaller getPackageInstaller() {
22934        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22935            return null;
22936        }
22937        return mInstallerService;
22938    }
22939
22940    @Override
22941    public IArtManager getArtManager() {
22942        return mArtManagerService;
22943    }
22944
22945    private boolean userNeedsBadging(int userId) {
22946        int index = mUserNeedsBadging.indexOfKey(userId);
22947        if (index < 0) {
22948            final UserInfo userInfo;
22949            final long token = Binder.clearCallingIdentity();
22950            try {
22951                userInfo = sUserManager.getUserInfo(userId);
22952            } finally {
22953                Binder.restoreCallingIdentity(token);
22954            }
22955            final boolean b;
22956            if (userInfo != null && userInfo.isManagedProfile()) {
22957                b = true;
22958            } else {
22959                b = false;
22960            }
22961            mUserNeedsBadging.put(userId, b);
22962            return b;
22963        }
22964        return mUserNeedsBadging.valueAt(index);
22965    }
22966
22967    @Override
22968    public KeySet getKeySetByAlias(String packageName, String alias) {
22969        if (packageName == null || alias == null) {
22970            return null;
22971        }
22972        synchronized(mPackages) {
22973            final PackageParser.Package pkg = mPackages.get(packageName);
22974            if (pkg == null) {
22975                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22976                throw new IllegalArgumentException("Unknown package: " + packageName);
22977            }
22978            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22979            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
22980                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
22981                throw new IllegalArgumentException("Unknown package: " + packageName);
22982            }
22983            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22984            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22985        }
22986    }
22987
22988    @Override
22989    public KeySet getSigningKeySet(String packageName) {
22990        if (packageName == null) {
22991            return null;
22992        }
22993        synchronized(mPackages) {
22994            final int callingUid = Binder.getCallingUid();
22995            final int callingUserId = UserHandle.getUserId(callingUid);
22996            final PackageParser.Package pkg = mPackages.get(packageName);
22997            if (pkg == null) {
22998                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22999                throw new IllegalArgumentException("Unknown package: " + packageName);
23000            }
23001            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23002            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23003                // filter and pretend the package doesn't exist
23004                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23005                        + ", uid:" + callingUid);
23006                throw new IllegalArgumentException("Unknown package: " + packageName);
23007            }
23008            if (pkg.applicationInfo.uid != callingUid
23009                    && Process.SYSTEM_UID != callingUid) {
23010                throw new SecurityException("May not access signing KeySet of other apps.");
23011            }
23012            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23013            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23014        }
23015    }
23016
23017    @Override
23018    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23019        final int callingUid = Binder.getCallingUid();
23020        if (getInstantAppPackageName(callingUid) != null) {
23021            return false;
23022        }
23023        if (packageName == null || ks == null) {
23024            return false;
23025        }
23026        synchronized(mPackages) {
23027            final PackageParser.Package pkg = mPackages.get(packageName);
23028            if (pkg == null
23029                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23030                            UserHandle.getUserId(callingUid))) {
23031                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23032                throw new IllegalArgumentException("Unknown package: " + packageName);
23033            }
23034            IBinder ksh = ks.getToken();
23035            if (ksh instanceof KeySetHandle) {
23036                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23037                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23038            }
23039            return false;
23040        }
23041    }
23042
23043    @Override
23044    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23045        final int callingUid = Binder.getCallingUid();
23046        if (getInstantAppPackageName(callingUid) != null) {
23047            return false;
23048        }
23049        if (packageName == null || ks == null) {
23050            return false;
23051        }
23052        synchronized(mPackages) {
23053            final PackageParser.Package pkg = mPackages.get(packageName);
23054            if (pkg == null
23055                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23056                            UserHandle.getUserId(callingUid))) {
23057                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23058                throw new IllegalArgumentException("Unknown package: " + packageName);
23059            }
23060            IBinder ksh = ks.getToken();
23061            if (ksh instanceof KeySetHandle) {
23062                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23063                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23064            }
23065            return false;
23066        }
23067    }
23068
23069    private void deletePackageIfUnusedLPr(final String packageName) {
23070        PackageSetting ps = mSettings.mPackages.get(packageName);
23071        if (ps == null) {
23072            return;
23073        }
23074        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23075            // TODO Implement atomic delete if package is unused
23076            // It is currently possible that the package will be deleted even if it is installed
23077            // after this method returns.
23078            mHandler.post(new Runnable() {
23079                public void run() {
23080                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23081                            0, PackageManager.DELETE_ALL_USERS);
23082                }
23083            });
23084        }
23085    }
23086
23087    /**
23088     * Check and throw if the given before/after packages would be considered a
23089     * downgrade.
23090     */
23091    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23092            throws PackageManagerException {
23093        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23094            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23095                    "Update version code " + after.versionCode + " is older than current "
23096                    + before.getLongVersionCode());
23097        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23098            if (after.baseRevisionCode < before.baseRevisionCode) {
23099                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23100                        "Update base revision code " + after.baseRevisionCode
23101                        + " is older than current " + before.baseRevisionCode);
23102            }
23103
23104            if (!ArrayUtils.isEmpty(after.splitNames)) {
23105                for (int i = 0; i < after.splitNames.length; i++) {
23106                    final String splitName = after.splitNames[i];
23107                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23108                    if (j != -1) {
23109                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23110                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23111                                    "Update split " + splitName + " revision code "
23112                                    + after.splitRevisionCodes[i] + " is older than current "
23113                                    + before.splitRevisionCodes[j]);
23114                        }
23115                    }
23116                }
23117            }
23118        }
23119    }
23120
23121    private static class MoveCallbacks extends Handler {
23122        private static final int MSG_CREATED = 1;
23123        private static final int MSG_STATUS_CHANGED = 2;
23124
23125        private final RemoteCallbackList<IPackageMoveObserver>
23126                mCallbacks = new RemoteCallbackList<>();
23127
23128        private final SparseIntArray mLastStatus = new SparseIntArray();
23129
23130        public MoveCallbacks(Looper looper) {
23131            super(looper);
23132        }
23133
23134        public void register(IPackageMoveObserver callback) {
23135            mCallbacks.register(callback);
23136        }
23137
23138        public void unregister(IPackageMoveObserver callback) {
23139            mCallbacks.unregister(callback);
23140        }
23141
23142        @Override
23143        public void handleMessage(Message msg) {
23144            final SomeArgs args = (SomeArgs) msg.obj;
23145            final int n = mCallbacks.beginBroadcast();
23146            for (int i = 0; i < n; i++) {
23147                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23148                try {
23149                    invokeCallback(callback, msg.what, args);
23150                } catch (RemoteException ignored) {
23151                }
23152            }
23153            mCallbacks.finishBroadcast();
23154            args.recycle();
23155        }
23156
23157        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23158                throws RemoteException {
23159            switch (what) {
23160                case MSG_CREATED: {
23161                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23162                    break;
23163                }
23164                case MSG_STATUS_CHANGED: {
23165                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23166                    break;
23167                }
23168            }
23169        }
23170
23171        private void notifyCreated(int moveId, Bundle extras) {
23172            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23173
23174            final SomeArgs args = SomeArgs.obtain();
23175            args.argi1 = moveId;
23176            args.arg2 = extras;
23177            obtainMessage(MSG_CREATED, args).sendToTarget();
23178        }
23179
23180        private void notifyStatusChanged(int moveId, int status) {
23181            notifyStatusChanged(moveId, status, -1);
23182        }
23183
23184        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23185            Slog.v(TAG, "Move " + moveId + " status " + status);
23186
23187            final SomeArgs args = SomeArgs.obtain();
23188            args.argi1 = moveId;
23189            args.argi2 = status;
23190            args.arg3 = estMillis;
23191            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23192
23193            synchronized (mLastStatus) {
23194                mLastStatus.put(moveId, status);
23195            }
23196        }
23197    }
23198
23199    private final static class OnPermissionChangeListeners extends Handler {
23200        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23201
23202        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23203                new RemoteCallbackList<>();
23204
23205        public OnPermissionChangeListeners(Looper looper) {
23206            super(looper);
23207        }
23208
23209        @Override
23210        public void handleMessage(Message msg) {
23211            switch (msg.what) {
23212                case MSG_ON_PERMISSIONS_CHANGED: {
23213                    final int uid = msg.arg1;
23214                    handleOnPermissionsChanged(uid);
23215                } break;
23216            }
23217        }
23218
23219        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23220            mPermissionListeners.register(listener);
23221
23222        }
23223
23224        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23225            mPermissionListeners.unregister(listener);
23226        }
23227
23228        public void onPermissionsChanged(int uid) {
23229            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23230                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23231            }
23232        }
23233
23234        private void handleOnPermissionsChanged(int uid) {
23235            final int count = mPermissionListeners.beginBroadcast();
23236            try {
23237                for (int i = 0; i < count; i++) {
23238                    IOnPermissionsChangeListener callback = mPermissionListeners
23239                            .getBroadcastItem(i);
23240                    try {
23241                        callback.onPermissionsChanged(uid);
23242                    } catch (RemoteException e) {
23243                        Log.e(TAG, "Permission listener is dead", e);
23244                    }
23245                }
23246            } finally {
23247                mPermissionListeners.finishBroadcast();
23248            }
23249        }
23250    }
23251
23252    private class PackageManagerNative extends IPackageManagerNative.Stub {
23253        @Override
23254        public String[] getNamesForUids(int[] uids) throws RemoteException {
23255            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23256            // massage results so they can be parsed by the native binder
23257            for (int i = results.length - 1; i >= 0; --i) {
23258                if (results[i] == null) {
23259                    results[i] = "";
23260                }
23261            }
23262            return results;
23263        }
23264
23265        // NB: this differentiates between preloads and sideloads
23266        @Override
23267        public String getInstallerForPackage(String packageName) throws RemoteException {
23268            final String installerName = getInstallerPackageName(packageName);
23269            if (!TextUtils.isEmpty(installerName)) {
23270                return installerName;
23271            }
23272            // differentiate between preload and sideload
23273            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23274            ApplicationInfo appInfo = getApplicationInfo(packageName,
23275                                    /*flags*/ 0,
23276                                    /*userId*/ callingUser);
23277            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23278                return "preload";
23279            }
23280            return "";
23281        }
23282
23283        @Override
23284        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23285            try {
23286                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23287                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23288                if (pInfo != null) {
23289                    return pInfo.getLongVersionCode();
23290                }
23291            } catch (Exception e) {
23292            }
23293            return 0;
23294        }
23295    }
23296
23297    private class PackageManagerInternalImpl extends PackageManagerInternal {
23298        @Override
23299        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23300                int flagValues, int userId) {
23301            PackageManagerService.this.updatePermissionFlags(
23302                    permName, packageName, flagMask, flagValues, userId);
23303        }
23304
23305        @Override
23306        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23307            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23308        }
23309
23310        @Override
23311        public boolean isInstantApp(String packageName, int userId) {
23312            return PackageManagerService.this.isInstantApp(packageName, userId);
23313        }
23314
23315        @Override
23316        public String getInstantAppPackageName(int uid) {
23317            return PackageManagerService.this.getInstantAppPackageName(uid);
23318        }
23319
23320        @Override
23321        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23322            synchronized (mPackages) {
23323                return PackageManagerService.this.filterAppAccessLPr(
23324                        (PackageSetting) pkg.mExtras, callingUid, userId);
23325            }
23326        }
23327
23328        @Override
23329        public PackageParser.Package getPackage(String packageName) {
23330            synchronized (mPackages) {
23331                packageName = resolveInternalPackageNameLPr(
23332                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23333                return mPackages.get(packageName);
23334            }
23335        }
23336
23337        @Override
23338        public PackageList getPackageList(PackageListObserver observer) {
23339            synchronized (mPackages) {
23340                final int N = mPackages.size();
23341                final ArrayList<String> list = new ArrayList<>(N);
23342                for (int i = 0; i < N; i++) {
23343                    list.add(mPackages.keyAt(i));
23344                }
23345                final PackageList packageList = new PackageList(list, observer);
23346                if (observer != null) {
23347                    mPackageListObservers.add(packageList);
23348                }
23349                return packageList;
23350            }
23351        }
23352
23353        @Override
23354        public void removePackageListObserver(PackageListObserver observer) {
23355            synchronized (mPackages) {
23356                mPackageListObservers.remove(observer);
23357            }
23358        }
23359
23360        @Override
23361        public PackageParser.Package getDisabledPackage(String packageName) {
23362            synchronized (mPackages) {
23363                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23364                return (ps != null) ? ps.pkg : null;
23365            }
23366        }
23367
23368        @Override
23369        public String getKnownPackageName(int knownPackage, int userId) {
23370            switch(knownPackage) {
23371                case PackageManagerInternal.PACKAGE_BROWSER:
23372                    return getDefaultBrowserPackageName(userId);
23373                case PackageManagerInternal.PACKAGE_INSTALLER:
23374                    return mRequiredInstallerPackage;
23375                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23376                    return mSetupWizardPackage;
23377                case PackageManagerInternal.PACKAGE_SYSTEM:
23378                    return "android";
23379                case PackageManagerInternal.PACKAGE_VERIFIER:
23380                    return mRequiredVerifierPackage;
23381            }
23382            return null;
23383        }
23384
23385        @Override
23386        public boolean isResolveActivityComponent(ComponentInfo component) {
23387            return mResolveActivity.packageName.equals(component.packageName)
23388                    && mResolveActivity.name.equals(component.name);
23389        }
23390
23391        @Override
23392        public void setLocationPackagesProvider(PackagesProvider provider) {
23393            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23394        }
23395
23396        @Override
23397        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23398            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23399        }
23400
23401        @Override
23402        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23403            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23404        }
23405
23406        @Override
23407        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23408            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23409        }
23410
23411        @Override
23412        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23413            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23414        }
23415
23416        @Override
23417        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23418            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23419        }
23420
23421        @Override
23422        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23423            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23424        }
23425
23426        @Override
23427        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23428            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23429        }
23430
23431        @Override
23432        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23433            synchronized (mPackages) {
23434                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23435            }
23436            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23437        }
23438
23439        @Override
23440        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23441            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23442                    packageName, userId);
23443        }
23444
23445        @Override
23446        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23447            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23448                    packageName, userId);
23449        }
23450
23451        @Override
23452        public void setKeepUninstalledPackages(final List<String> packageList) {
23453            Preconditions.checkNotNull(packageList);
23454            List<String> removedFromList = null;
23455            synchronized (mPackages) {
23456                if (mKeepUninstalledPackages != null) {
23457                    final int packagesCount = mKeepUninstalledPackages.size();
23458                    for (int i = 0; i < packagesCount; i++) {
23459                        String oldPackage = mKeepUninstalledPackages.get(i);
23460                        if (packageList != null && packageList.contains(oldPackage)) {
23461                            continue;
23462                        }
23463                        if (removedFromList == null) {
23464                            removedFromList = new ArrayList<>();
23465                        }
23466                        removedFromList.add(oldPackage);
23467                    }
23468                }
23469                mKeepUninstalledPackages = new ArrayList<>(packageList);
23470                if (removedFromList != null) {
23471                    final int removedCount = removedFromList.size();
23472                    for (int i = 0; i < removedCount; i++) {
23473                        deletePackageIfUnusedLPr(removedFromList.get(i));
23474                    }
23475                }
23476            }
23477        }
23478
23479        @Override
23480        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23481            synchronized (mPackages) {
23482                return mPermissionManager.isPermissionsReviewRequired(
23483                        mPackages.get(packageName), userId);
23484            }
23485        }
23486
23487        @Override
23488        public PackageInfo getPackageInfo(
23489                String packageName, int flags, int filterCallingUid, int userId) {
23490            return PackageManagerService.this
23491                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23492                            flags, filterCallingUid, userId);
23493        }
23494
23495        @Override
23496        public int getPackageUid(String packageName, int flags, int userId) {
23497            return PackageManagerService.this
23498                    .getPackageUid(packageName, flags, userId);
23499        }
23500
23501        @Override
23502        public ApplicationInfo getApplicationInfo(
23503                String packageName, int flags, int filterCallingUid, int userId) {
23504            return PackageManagerService.this
23505                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23506        }
23507
23508        @Override
23509        public ActivityInfo getActivityInfo(
23510                ComponentName component, int flags, int filterCallingUid, int userId) {
23511            return PackageManagerService.this
23512                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23513        }
23514
23515        @Override
23516        public List<ResolveInfo> queryIntentActivities(
23517                Intent intent, int flags, int filterCallingUid, int userId) {
23518            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23519            return PackageManagerService.this
23520                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23521                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23522        }
23523
23524        @Override
23525        public List<ResolveInfo> queryIntentServices(
23526                Intent intent, int flags, int callingUid, int userId) {
23527            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23528            return PackageManagerService.this
23529                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23530                            false);
23531        }
23532
23533        @Override
23534        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23535                int userId) {
23536            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23537        }
23538
23539        @Override
23540        public void setDeviceAndProfileOwnerPackages(
23541                int deviceOwnerUserId, String deviceOwnerPackage,
23542                SparseArray<String> profileOwnerPackages) {
23543            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23544                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23545        }
23546
23547        @Override
23548        public boolean isPackageDataProtected(int userId, String packageName) {
23549            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23550        }
23551
23552        @Override
23553        public boolean isPackageEphemeral(int userId, String packageName) {
23554            synchronized (mPackages) {
23555                final PackageSetting ps = mSettings.mPackages.get(packageName);
23556                return ps != null ? ps.getInstantApp(userId) : false;
23557            }
23558        }
23559
23560        @Override
23561        public boolean wasPackageEverLaunched(String packageName, int userId) {
23562            synchronized (mPackages) {
23563                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23564            }
23565        }
23566
23567        @Override
23568        public void grantRuntimePermission(String packageName, String permName, int userId,
23569                boolean overridePolicy) {
23570            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23571                    permName, packageName, overridePolicy, getCallingUid(), userId,
23572                    mPermissionCallback);
23573        }
23574
23575        @Override
23576        public void revokeRuntimePermission(String packageName, String permName, int userId,
23577                boolean overridePolicy) {
23578            mPermissionManager.revokeRuntimePermission(
23579                    permName, packageName, overridePolicy, getCallingUid(), userId,
23580                    mPermissionCallback);
23581        }
23582
23583        @Override
23584        public String getNameForUid(int uid) {
23585            return PackageManagerService.this.getNameForUid(uid);
23586        }
23587
23588        @Override
23589        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23590                Intent origIntent, String resolvedType, String callingPackage,
23591                Bundle verificationBundle, int userId) {
23592            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23593                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23594                    userId);
23595        }
23596
23597        @Override
23598        public void grantEphemeralAccess(int userId, Intent intent,
23599                int targetAppId, int ephemeralAppId) {
23600            synchronized (mPackages) {
23601                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23602                        targetAppId, ephemeralAppId);
23603            }
23604        }
23605
23606        @Override
23607        public boolean isInstantAppInstallerComponent(ComponentName component) {
23608            synchronized (mPackages) {
23609                return mInstantAppInstallerActivity != null
23610                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23611            }
23612        }
23613
23614        @Override
23615        public void pruneInstantApps() {
23616            mInstantAppRegistry.pruneInstantApps();
23617        }
23618
23619        @Override
23620        public String getSetupWizardPackageName() {
23621            return mSetupWizardPackage;
23622        }
23623
23624        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23625            if (policy != null) {
23626                mExternalSourcesPolicy = policy;
23627            }
23628        }
23629
23630        @Override
23631        public boolean isPackagePersistent(String packageName) {
23632            synchronized (mPackages) {
23633                PackageParser.Package pkg = mPackages.get(packageName);
23634                return pkg != null
23635                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23636                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23637                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23638                        : false;
23639            }
23640        }
23641
23642        @Override
23643        public boolean isLegacySystemApp(Package pkg) {
23644            synchronized (mPackages) {
23645                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23646                return mPromoteSystemApps
23647                        && ps.isSystem()
23648                        && mExistingSystemPackages.contains(ps.name);
23649            }
23650        }
23651
23652        @Override
23653        public List<PackageInfo> getOverlayPackages(int userId) {
23654            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23655            synchronized (mPackages) {
23656                for (PackageParser.Package p : mPackages.values()) {
23657                    if (p.mOverlayTarget != null) {
23658                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23659                        if (pkg != null) {
23660                            overlayPackages.add(pkg);
23661                        }
23662                    }
23663                }
23664            }
23665            return overlayPackages;
23666        }
23667
23668        @Override
23669        public List<String> getTargetPackageNames(int userId) {
23670            List<String> targetPackages = new ArrayList<>();
23671            synchronized (mPackages) {
23672                for (PackageParser.Package p : mPackages.values()) {
23673                    if (p.mOverlayTarget == null) {
23674                        targetPackages.add(p.packageName);
23675                    }
23676                }
23677            }
23678            return targetPackages;
23679        }
23680
23681        @Override
23682        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23683                @Nullable List<String> overlayPackageNames) {
23684            synchronized (mPackages) {
23685                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23686                    Slog.e(TAG, "failed to find package " + targetPackageName);
23687                    return false;
23688                }
23689                ArrayList<String> overlayPaths = null;
23690                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23691                    final int N = overlayPackageNames.size();
23692                    overlayPaths = new ArrayList<>(N);
23693                    for (int i = 0; i < N; i++) {
23694                        final String packageName = overlayPackageNames.get(i);
23695                        final PackageParser.Package pkg = mPackages.get(packageName);
23696                        if (pkg == null) {
23697                            Slog.e(TAG, "failed to find package " + packageName);
23698                            return false;
23699                        }
23700                        overlayPaths.add(pkg.baseCodePath);
23701                    }
23702                }
23703
23704                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23705                ps.setOverlayPaths(overlayPaths, userId);
23706                return true;
23707            }
23708        }
23709
23710        @Override
23711        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23712                int flags, int userId, boolean resolveForStart) {
23713            return resolveIntentInternal(
23714                    intent, resolvedType, flags, userId, resolveForStart);
23715        }
23716
23717        @Override
23718        public ResolveInfo resolveService(Intent intent, String resolvedType,
23719                int flags, int userId, int callingUid) {
23720            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23721        }
23722
23723        @Override
23724        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23725            return PackageManagerService.this.resolveContentProviderInternal(
23726                    name, flags, userId);
23727        }
23728
23729        @Override
23730        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23731            synchronized (mPackages) {
23732                mIsolatedOwners.put(isolatedUid, ownerUid);
23733            }
23734        }
23735
23736        @Override
23737        public void removeIsolatedUid(int isolatedUid) {
23738            synchronized (mPackages) {
23739                mIsolatedOwners.delete(isolatedUid);
23740            }
23741        }
23742
23743        @Override
23744        public int getUidTargetSdkVersion(int uid) {
23745            synchronized (mPackages) {
23746                return getUidTargetSdkVersionLockedLPr(uid);
23747            }
23748        }
23749
23750        @Override
23751        public int getPackageTargetSdkVersion(String packageName) {
23752            synchronized (mPackages) {
23753                return getPackageTargetSdkVersionLockedLPr(packageName);
23754            }
23755        }
23756
23757        @Override
23758        public boolean canAccessInstantApps(int callingUid, int userId) {
23759            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
23760        }
23761
23762        @Override
23763        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
23764            synchronized (mPackages) {
23765                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
23766            }
23767        }
23768
23769        @Override
23770        public void notifyPackageUse(String packageName, int reason) {
23771            synchronized (mPackages) {
23772                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
23773            }
23774        }
23775    }
23776
23777    @Override
23778    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23779        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23780        synchronized (mPackages) {
23781            final long identity = Binder.clearCallingIdentity();
23782            try {
23783                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
23784                        packageNames, userId);
23785            } finally {
23786                Binder.restoreCallingIdentity(identity);
23787            }
23788        }
23789    }
23790
23791    @Override
23792    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23793        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23794        synchronized (mPackages) {
23795            final long identity = Binder.clearCallingIdentity();
23796            try {
23797                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
23798                        packageNames, userId);
23799            } finally {
23800                Binder.restoreCallingIdentity(identity);
23801            }
23802        }
23803    }
23804
23805    private static void enforceSystemOrPhoneCaller(String tag) {
23806        int callingUid = Binder.getCallingUid();
23807        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23808            throw new SecurityException(
23809                    "Cannot call " + tag + " from UID " + callingUid);
23810        }
23811    }
23812
23813    boolean isHistoricalPackageUsageAvailable() {
23814        return mPackageUsage.isHistoricalPackageUsageAvailable();
23815    }
23816
23817    /**
23818     * Return a <b>copy</b> of the collection of packages known to the package manager.
23819     * @return A copy of the values of mPackages.
23820     */
23821    Collection<PackageParser.Package> getPackages() {
23822        synchronized (mPackages) {
23823            return new ArrayList<>(mPackages.values());
23824        }
23825    }
23826
23827    /**
23828     * Logs process start information (including base APK hash) to the security log.
23829     * @hide
23830     */
23831    @Override
23832    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23833            String apkFile, int pid) {
23834        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23835            return;
23836        }
23837        if (!SecurityLog.isLoggingEnabled()) {
23838            return;
23839        }
23840        Bundle data = new Bundle();
23841        data.putLong("startTimestamp", System.currentTimeMillis());
23842        data.putString("processName", processName);
23843        data.putInt("uid", uid);
23844        data.putString("seinfo", seinfo);
23845        data.putString("apkFile", apkFile);
23846        data.putInt("pid", pid);
23847        Message msg = mProcessLoggingHandler.obtainMessage(
23848                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23849        msg.setData(data);
23850        mProcessLoggingHandler.sendMessage(msg);
23851    }
23852
23853    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23854        return mCompilerStats.getPackageStats(pkgName);
23855    }
23856
23857    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23858        return getOrCreateCompilerPackageStats(pkg.packageName);
23859    }
23860
23861    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23862        return mCompilerStats.getOrCreatePackageStats(pkgName);
23863    }
23864
23865    public void deleteCompilerPackageStats(String pkgName) {
23866        mCompilerStats.deletePackageStats(pkgName);
23867    }
23868
23869    @Override
23870    public int getInstallReason(String packageName, int userId) {
23871        final int callingUid = Binder.getCallingUid();
23872        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23873                true /* requireFullPermission */, false /* checkShell */,
23874                "get install reason");
23875        synchronized (mPackages) {
23876            final PackageSetting ps = mSettings.mPackages.get(packageName);
23877            if (filterAppAccessLPr(ps, callingUid, userId)) {
23878                return PackageManager.INSTALL_REASON_UNKNOWN;
23879            }
23880            if (ps != null) {
23881                return ps.getInstallReason(userId);
23882            }
23883        }
23884        return PackageManager.INSTALL_REASON_UNKNOWN;
23885    }
23886
23887    @Override
23888    public boolean canRequestPackageInstalls(String packageName, int userId) {
23889        return canRequestPackageInstallsInternal(packageName, 0, userId,
23890                true /* throwIfPermNotDeclared*/);
23891    }
23892
23893    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
23894            boolean throwIfPermNotDeclared) {
23895        int callingUid = Binder.getCallingUid();
23896        int uid = getPackageUid(packageName, 0, userId);
23897        if (callingUid != uid && callingUid != Process.ROOT_UID
23898                && callingUid != Process.SYSTEM_UID) {
23899            throw new SecurityException(
23900                    "Caller uid " + callingUid + " does not own package " + packageName);
23901        }
23902        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
23903        if (info == null) {
23904            return false;
23905        }
23906        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23907            return false;
23908        }
23909        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23910        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23911        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23912            if (throwIfPermNotDeclared) {
23913                throw new SecurityException("Need to declare " + appOpPermission
23914                        + " to call this api");
23915            } else {
23916                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
23917                return false;
23918            }
23919        }
23920        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23921            return false;
23922        }
23923        if (mExternalSourcesPolicy != null) {
23924            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23925            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23926                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23927            }
23928        }
23929        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23930    }
23931
23932    @Override
23933    public ComponentName getInstantAppResolverSettingsComponent() {
23934        return mInstantAppResolverSettingsComponent;
23935    }
23936
23937    @Override
23938    public ComponentName getInstantAppInstallerComponent() {
23939        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23940            return null;
23941        }
23942        return mInstantAppInstallerActivity == null
23943                ? null : mInstantAppInstallerActivity.getComponentName();
23944    }
23945
23946    @Override
23947    public String getInstantAppAndroidId(String packageName, int userId) {
23948        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23949                "getInstantAppAndroidId");
23950        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
23951                true /* requireFullPermission */, false /* checkShell */,
23952                "getInstantAppAndroidId");
23953        // Make sure the target is an Instant App.
23954        if (!isInstantApp(packageName, userId)) {
23955            return null;
23956        }
23957        synchronized (mPackages) {
23958            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
23959        }
23960    }
23961
23962    boolean canHaveOatDir(String packageName) {
23963        synchronized (mPackages) {
23964            PackageParser.Package p = mPackages.get(packageName);
23965            if (p == null) {
23966                return false;
23967            }
23968            return p.canHaveOatDir();
23969        }
23970    }
23971
23972    private String getOatDir(PackageParser.Package pkg) {
23973        if (!pkg.canHaveOatDir()) {
23974            return null;
23975        }
23976        File codePath = new File(pkg.codePath);
23977        if (codePath.isDirectory()) {
23978            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
23979        }
23980        return null;
23981    }
23982
23983    void deleteOatArtifactsOfPackage(String packageName) {
23984        final String[] instructionSets;
23985        final List<String> codePaths;
23986        final String oatDir;
23987        final PackageParser.Package pkg;
23988        synchronized (mPackages) {
23989            pkg = mPackages.get(packageName);
23990        }
23991        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
23992        codePaths = pkg.getAllCodePaths();
23993        oatDir = getOatDir(pkg);
23994
23995        for (String codePath : codePaths) {
23996            for (String isa : instructionSets) {
23997                try {
23998                    mInstaller.deleteOdex(codePath, isa, oatDir);
23999                } catch (InstallerException e) {
24000                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24001                }
24002            }
24003        }
24004    }
24005
24006    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24007        Set<String> unusedPackages = new HashSet<>();
24008        long currentTimeInMillis = System.currentTimeMillis();
24009        synchronized (mPackages) {
24010            for (PackageParser.Package pkg : mPackages.values()) {
24011                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24012                if (ps == null) {
24013                    continue;
24014                }
24015                PackageDexUsage.PackageUseInfo packageUseInfo =
24016                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24017                if (PackageManagerServiceUtils
24018                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24019                                downgradeTimeThresholdMillis, packageUseInfo,
24020                                pkg.getLatestPackageUseTimeInMills(),
24021                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24022                    unusedPackages.add(pkg.packageName);
24023                }
24024            }
24025        }
24026        return unusedPackages;
24027    }
24028
24029    @Override
24030    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24031            int userId) {
24032        final int callingUid = Binder.getCallingUid();
24033        final int callingAppId = UserHandle.getAppId(callingUid);
24034
24035        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24036                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24037
24038        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24039                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24040            throw new SecurityException("Caller must have the "
24041                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24042        }
24043
24044        synchronized(mPackages) {
24045            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24046            scheduleWritePackageRestrictionsLocked(userId);
24047        }
24048    }
24049
24050    @Nullable
24051    @Override
24052    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24053        final int callingUid = Binder.getCallingUid();
24054        final int callingAppId = UserHandle.getAppId(callingUid);
24055
24056        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24057                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24058
24059        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24060                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24061            throw new SecurityException("Caller must have the "
24062                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24063        }
24064
24065        synchronized(mPackages) {
24066            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24067        }
24068    }
24069}
24070
24071interface PackageSender {
24072    /**
24073     * @param userIds User IDs where the action occurred on a full application
24074     * @param instantUserIds User IDs where the action occurred on an instant application
24075     */
24076    void sendPackageBroadcast(final String action, final String pkg,
24077        final Bundle extras, final int flags, final String targetPkg,
24078        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24079    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24080        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24081    void notifyPackageAdded(String packageName);
24082    void notifyPackageRemoved(String packageName);
24083}
24084