PackageManagerService.java revision 2482315cd526ef49b1eb91d24f7a0149d91d0108
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.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_DEVICE_ADMINS;
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.SET_HARMFUL_APP_WARNINGS;
26import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
27import static android.content.pm.PackageManager.CERT_INPUT_RAW_X509;
28import static android.content.pm.PackageManager.CERT_INPUT_SHA256;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
31import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
32import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
33import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
34import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
39import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
40import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
41import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
42import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
43import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
44import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
45import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
50import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
51import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
52import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
53import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
54import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
57import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
58import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.isApkFile;
86import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
87import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
88import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
89import static android.system.OsConstants.O_CREAT;
90import static android.system.OsConstants.O_RDWR;
91
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
93import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
94import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
95import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
96import static com.android.internal.util.ArrayUtils.appendInt;
97import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
100import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
101import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
104import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
105import static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
106import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
107import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
108import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
109import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
110import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
111import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
115
116import android.Manifest;
117import android.annotation.IntDef;
118import android.annotation.NonNull;
119import android.annotation.Nullable;
120import android.annotation.UserIdInt;
121import android.app.ActivityManager;
122import android.app.ActivityManagerInternal;
123import android.app.AppOpsManager;
124import android.app.IActivityManager;
125import android.app.ResourcesManager;
126import android.app.admin.IDevicePolicyManager;
127import android.app.admin.SecurityLog;
128import android.app.backup.IBackupManager;
129import android.content.BroadcastReceiver;
130import android.content.ComponentName;
131import android.content.ContentResolver;
132import android.content.Context;
133import android.content.IIntentReceiver;
134import android.content.Intent;
135import android.content.IntentFilter;
136import android.content.IntentSender;
137import android.content.IntentSender.SendIntentException;
138import android.content.ServiceConnection;
139import android.content.pm.ActivityInfo;
140import android.content.pm.ApplicationInfo;
141import android.content.pm.AppsQueryHelper;
142import android.content.pm.AuxiliaryResolveInfo;
143import android.content.pm.ChangedPackages;
144import android.content.pm.ComponentInfo;
145import android.content.pm.FallbackCategoryProvider;
146import android.content.pm.FeatureInfo;
147import android.content.pm.IDexModuleRegisterCallback;
148import android.content.pm.IOnPermissionsChangeListener;
149import android.content.pm.IPackageDataObserver;
150import android.content.pm.IPackageDeleteObserver;
151import android.content.pm.IPackageDeleteObserver2;
152import android.content.pm.IPackageInstallObserver2;
153import android.content.pm.IPackageInstaller;
154import android.content.pm.IPackageManager;
155import android.content.pm.IPackageManagerNative;
156import android.content.pm.IPackageMoveObserver;
157import android.content.pm.IPackageStatsObserver;
158import android.content.pm.InstantAppInfo;
159import android.content.pm.InstantAppRequest;
160import android.content.pm.InstantAppResolveInfo;
161import android.content.pm.InstrumentationInfo;
162import android.content.pm.IntentFilterVerificationInfo;
163import android.content.pm.KeySet;
164import android.content.pm.PackageCleanItem;
165import android.content.pm.PackageInfo;
166import android.content.pm.PackageInfoLite;
167import android.content.pm.PackageInstaller;
168import android.content.pm.PackageList;
169import android.content.pm.PackageManager;
170import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
171import android.content.pm.PackageManagerInternal;
172import android.content.pm.PackageManagerInternal.PackageListObserver;
173import android.content.pm.PackageParser;
174import android.content.pm.PackageParser.ActivityIntentInfo;
175import android.content.pm.PackageParser.Package;
176import android.content.pm.PackageParser.PackageLite;
177import android.content.pm.PackageParser.PackageParserException;
178import android.content.pm.PackageParser.ParseFlags;
179import android.content.pm.PackageParser.ServiceIntentInfo;
180import android.content.pm.PackageParser.SigningDetails;
181import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion;
182import android.content.pm.PackageStats;
183import android.content.pm.PackageUserState;
184import android.content.pm.ParceledListSlice;
185import android.content.pm.PermissionGroupInfo;
186import android.content.pm.PermissionInfo;
187import android.content.pm.ProviderInfo;
188import android.content.pm.ResolveInfo;
189import android.content.pm.SELinuxUtil;
190import android.content.pm.ServiceInfo;
191import android.content.pm.SharedLibraryInfo;
192import android.content.pm.Signature;
193import android.content.pm.UserInfo;
194import android.content.pm.VerifierDeviceIdentity;
195import android.content.pm.VerifierInfo;
196import android.content.pm.VersionedPackage;
197import android.content.pm.dex.ArtManager;
198import android.content.pm.dex.DexMetadataHelper;
199import android.content.pm.dex.IArtManager;
200import android.content.res.Resources;
201import android.database.ContentObserver;
202import android.graphics.Bitmap;
203import android.hardware.display.DisplayManager;
204import android.net.Uri;
205import android.os.AsyncTask;
206import android.os.Binder;
207import android.os.Build;
208import android.os.Bundle;
209import android.os.Debug;
210import android.os.Environment;
211import android.os.Environment.UserEnvironment;
212import android.os.FileUtils;
213import android.os.Handler;
214import android.os.IBinder;
215import android.os.Looper;
216import android.os.Message;
217import android.os.Parcel;
218import android.os.ParcelFileDescriptor;
219import android.os.PatternMatcher;
220import android.os.PersistableBundle;
221import android.os.Process;
222import android.os.RemoteCallbackList;
223import android.os.RemoteException;
224import android.os.ResultReceiver;
225import android.os.SELinux;
226import android.os.ServiceManager;
227import android.os.ShellCallback;
228import android.os.SystemClock;
229import android.os.SystemProperties;
230import android.os.Trace;
231import android.os.UserHandle;
232import android.os.UserManager;
233import android.os.UserManagerInternal;
234import android.os.storage.IStorageManager;
235import android.os.storage.StorageEventListener;
236import android.os.storage.StorageManager;
237import android.os.storage.StorageManagerInternal;
238import android.os.storage.VolumeInfo;
239import android.os.storage.VolumeRecord;
240import android.provider.Settings.Global;
241import android.provider.Settings.Secure;
242import android.security.KeyStore;
243import android.security.SystemKeyStore;
244import android.service.pm.PackageServiceDumpProto;
245import android.system.ErrnoException;
246import android.system.Os;
247import android.text.TextUtils;
248import android.text.format.DateUtils;
249import android.util.ArrayMap;
250import android.util.ArraySet;
251import android.util.Base64;
252import android.util.ByteStringUtils;
253import android.util.DisplayMetrics;
254import android.util.EventLog;
255import android.util.ExceptionUtils;
256import android.util.Log;
257import android.util.LogPrinter;
258import android.util.LongSparseArray;
259import android.util.LongSparseLongArray;
260import android.util.MathUtils;
261import android.util.PackageUtils;
262import android.util.Pair;
263import android.util.PrintStreamPrinter;
264import android.util.Slog;
265import android.util.SparseArray;
266import android.util.SparseBooleanArray;
267import android.util.SparseIntArray;
268import android.util.TimingsTraceLog;
269import android.util.Xml;
270import android.util.jar.StrictJarFile;
271import android.util.proto.ProtoOutputStream;
272import android.view.Display;
273
274import com.android.internal.R;
275import com.android.internal.annotations.GuardedBy;
276import com.android.internal.app.IMediaContainerService;
277import com.android.internal.app.ResolverActivity;
278import com.android.internal.content.NativeLibraryHelper;
279import com.android.internal.content.PackageHelper;
280import com.android.internal.logging.MetricsLogger;
281import com.android.internal.os.IParcelFileDescriptorFactory;
282import com.android.internal.os.SomeArgs;
283import com.android.internal.os.Zygote;
284import com.android.internal.telephony.CarrierAppUtils;
285import com.android.internal.util.ArrayUtils;
286import com.android.internal.util.ConcurrentUtils;
287import com.android.internal.util.DumpUtils;
288import com.android.internal.util.FastXmlSerializer;
289import com.android.internal.util.IndentingPrintWriter;
290import com.android.internal.util.Preconditions;
291import com.android.internal.util.XmlUtils;
292import com.android.server.AttributeCache;
293import com.android.server.DeviceIdleController;
294import com.android.server.EventLogTags;
295import com.android.server.FgThread;
296import com.android.server.IntentResolver;
297import com.android.server.LocalServices;
298import com.android.server.LockGuard;
299import com.android.server.ServiceThread;
300import com.android.server.SystemConfig;
301import com.android.server.SystemServerInitThreadPool;
302import com.android.server.Watchdog;
303import com.android.server.net.NetworkPolicyManagerInternal;
304import com.android.server.pm.Installer.InstallerException;
305import com.android.server.pm.Settings.DatabaseVersion;
306import com.android.server.pm.Settings.VersionInfo;
307import com.android.server.pm.dex.ArtManagerService;
308import com.android.server.pm.dex.DexLogger;
309import com.android.server.pm.dex.DexManager;
310import com.android.server.pm.dex.DexoptOptions;
311import com.android.server.pm.dex.PackageDexUsage;
312import com.android.server.pm.permission.BasePermission;
313import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
314import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
315import com.android.server.pm.permission.PermissionManagerInternal;
316import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
317import com.android.server.pm.permission.PermissionManagerService;
318import com.android.server.pm.permission.PermissionsState;
319import com.android.server.pm.permission.PermissionsState.PermissionState;
320import com.android.server.security.VerityUtils;
321import com.android.server.storage.DeviceStorageMonitorInternal;
322
323import dalvik.system.CloseGuard;
324import dalvik.system.VMRuntime;
325
326import libcore.io.IoUtils;
327
328import org.xmlpull.v1.XmlPullParser;
329import org.xmlpull.v1.XmlPullParserException;
330import org.xmlpull.v1.XmlSerializer;
331
332import java.io.BufferedOutputStream;
333import java.io.ByteArrayInputStream;
334import java.io.ByteArrayOutputStream;
335import java.io.File;
336import java.io.FileDescriptor;
337import java.io.FileInputStream;
338import java.io.FileOutputStream;
339import java.io.FilenameFilter;
340import java.io.IOException;
341import java.io.PrintWriter;
342import java.lang.annotation.Retention;
343import java.lang.annotation.RetentionPolicy;
344import java.nio.charset.StandardCharsets;
345import java.security.DigestException;
346import java.security.DigestInputStream;
347import java.security.MessageDigest;
348import java.security.NoSuchAlgorithmException;
349import java.security.PublicKey;
350import java.security.SecureRandom;
351import java.security.cert.CertificateException;
352import java.util.ArrayList;
353import java.util.Arrays;
354import java.util.Collection;
355import java.util.Collections;
356import java.util.Comparator;
357import java.util.HashMap;
358import java.util.HashSet;
359import java.util.Iterator;
360import java.util.LinkedHashSet;
361import java.util.List;
362import java.util.Map;
363import java.util.Objects;
364import java.util.Set;
365import java.util.concurrent.CountDownLatch;
366import java.util.concurrent.Future;
367import java.util.concurrent.TimeUnit;
368import java.util.concurrent.atomic.AtomicBoolean;
369import java.util.concurrent.atomic.AtomicInteger;
370import java.util.function.Predicate;
371
372/**
373 * Keep track of all those APKs everywhere.
374 * <p>
375 * Internally there are two important locks:
376 * <ul>
377 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
378 * and other related state. It is a fine-grained lock that should only be held
379 * momentarily, as it's one of the most contended locks in the system.
380 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
381 * operations typically involve heavy lifting of application data on disk. Since
382 * {@code installd} is single-threaded, and it's operations can often be slow,
383 * this lock should never be acquired while already holding {@link #mPackages}.
384 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
385 * holding {@link #mInstallLock}.
386 * </ul>
387 * Many internal methods rely on the caller to hold the appropriate locks, and
388 * this contract is expressed through method name suffixes:
389 * <ul>
390 * <li>fooLI(): the caller must hold {@link #mInstallLock}
391 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
392 * being modified must be frozen
393 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
394 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
395 * </ul>
396 * <p>
397 * Because this class is very central to the platform's security; please run all
398 * CTS and unit tests whenever making modifications:
399 *
400 * <pre>
401 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
402 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
403 * </pre>
404 */
405public class PackageManagerService extends IPackageManager.Stub
406        implements PackageSender {
407    static final String TAG = "PackageManager";
408    public static final boolean DEBUG_SETTINGS = false;
409    static final boolean DEBUG_PREFERRED = false;
410    static final boolean DEBUG_UPGRADE = false;
411    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
412    private static final boolean DEBUG_BACKUP = false;
413    public static final boolean DEBUG_INSTALL = false;
414    public static final boolean DEBUG_REMOVE = false;
415    private static final boolean DEBUG_BROADCASTS = false;
416    private static final boolean DEBUG_SHOW_INFO = false;
417    private static final boolean DEBUG_PACKAGE_INFO = false;
418    private static final boolean DEBUG_INTENT_MATCHING = false;
419    public static final boolean DEBUG_PACKAGE_SCANNING = false;
420    private static final boolean DEBUG_VERIFY = false;
421    private static final boolean DEBUG_FILTERS = false;
422    public static final boolean DEBUG_PERMISSIONS = false;
423    private static final boolean DEBUG_SHARED_LIBRARIES = false;
424    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
425
426    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
427    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
428    // user, but by default initialize to this.
429    public static final boolean DEBUG_DEXOPT = false;
430
431    private static final boolean DEBUG_ABI_SELECTION = false;
432    private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
433    private static final boolean DEBUG_TRIAGED_MISSING = false;
434    private static final boolean DEBUG_APP_DATA = false;
435
436    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
437    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
438
439    private static final boolean HIDE_EPHEMERAL_APIS = false;
440
441    private static final boolean ENABLE_FREE_CACHE_V2 =
442            SystemProperties.getBoolean("fw.free_cache_v2", true);
443
444    private static final int RADIO_UID = Process.PHONE_UID;
445    private static final int LOG_UID = Process.LOG_UID;
446    private static final int NFC_UID = Process.NFC_UID;
447    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
448    private static final int SHELL_UID = Process.SHELL_UID;
449    private static final int SE_UID = Process.SE_UID;
450
451    // Suffix used during package installation when copying/moving
452    // package apks to install directory.
453    private static final String INSTALL_PACKAGE_SUFFIX = "-";
454
455    static final int SCAN_NO_DEX = 1<<0;
456    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
457    static final int SCAN_NEW_INSTALL = 1<<2;
458    static final int SCAN_UPDATE_TIME = 1<<3;
459    static final int SCAN_BOOTING = 1<<4;
460    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
461    static final int SCAN_REQUIRE_KNOWN = 1<<7;
462    static final int SCAN_MOVE = 1<<8;
463    static final int SCAN_INITIAL = 1<<9;
464    static final int SCAN_CHECK_ONLY = 1<<10;
465    static final int SCAN_DONT_KILL_APP = 1<<11;
466    static final int SCAN_IGNORE_FROZEN = 1<<12;
467    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
468    static final int SCAN_AS_INSTANT_APP = 1<<14;
469    static final int SCAN_AS_FULL_APP = 1<<15;
470    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
471    static final int SCAN_AS_SYSTEM = 1<<17;
472    static final int SCAN_AS_PRIVILEGED = 1<<18;
473    static final int SCAN_AS_OEM = 1<<19;
474    static final int SCAN_AS_VENDOR = 1<<20;
475    static final int SCAN_AS_PRODUCT = 1<<21;
476
477    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
478            SCAN_NO_DEX,
479            SCAN_UPDATE_SIGNATURE,
480            SCAN_NEW_INSTALL,
481            SCAN_UPDATE_TIME,
482            SCAN_BOOTING,
483            SCAN_DELETE_DATA_ON_FAILURES,
484            SCAN_REQUIRE_KNOWN,
485            SCAN_MOVE,
486            SCAN_INITIAL,
487            SCAN_CHECK_ONLY,
488            SCAN_DONT_KILL_APP,
489            SCAN_IGNORE_FROZEN,
490            SCAN_FIRST_BOOT_OR_UPGRADE,
491            SCAN_AS_INSTANT_APP,
492            SCAN_AS_FULL_APP,
493            SCAN_AS_VIRTUAL_PRELOAD,
494    })
495    @Retention(RetentionPolicy.SOURCE)
496    public @interface ScanFlags {}
497
498    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
499    /** Extension of the compressed packages */
500    public final static String COMPRESSED_EXTENSION = ".gz";
501    /** Suffix of stub packages on the system partition */
502    public final static String STUB_SUFFIX = "-Stub";
503
504    private static final int[] EMPTY_INT_ARRAY = new int[0];
505
506    private static final int TYPE_UNKNOWN = 0;
507    private static final int TYPE_ACTIVITY = 1;
508    private static final int TYPE_RECEIVER = 2;
509    private static final int TYPE_SERVICE = 3;
510    private static final int TYPE_PROVIDER = 4;
511    @IntDef(prefix = { "TYPE_" }, value = {
512            TYPE_UNKNOWN,
513            TYPE_ACTIVITY,
514            TYPE_RECEIVER,
515            TYPE_SERVICE,
516            TYPE_PROVIDER,
517    })
518    @Retention(RetentionPolicy.SOURCE)
519    public @interface ComponentType {}
520
521    /**
522     * Timeout (in milliseconds) after which the watchdog should declare that
523     * our handler thread is wedged.  The usual default for such things is one
524     * minute but we sometimes do very lengthy I/O operations on this thread,
525     * such as installing multi-gigabyte applications, so ours needs to be longer.
526     */
527    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
528
529    /**
530     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
531     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
532     * settings entry if available, otherwise we use the hardcoded default.  If it's been
533     * more than this long since the last fstrim, we force one during the boot sequence.
534     *
535     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
536     * one gets run at the next available charging+idle time.  This final mandatory
537     * no-fstrim check kicks in only of the other scheduling criteria is never met.
538     */
539    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
540
541    /**
542     * Whether verification is enabled by default.
543     */
544    private static final boolean DEFAULT_VERIFY_ENABLE = true;
545
546    /**
547     * The default maximum time to wait for the verification agent to return in
548     * milliseconds.
549     */
550    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
551
552    /**
553     * The default response for package verification timeout.
554     *
555     * This can be either PackageManager.VERIFICATION_ALLOW or
556     * PackageManager.VERIFICATION_REJECT.
557     */
558    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
559
560    public static final String PLATFORM_PACKAGE_NAME = "android";
561
562    public static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
563
564    public static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
565            DEFAULT_CONTAINER_PACKAGE,
566            "com.android.defcontainer.DefaultContainerService");
567
568    private static final String KILL_APP_REASON_GIDS_CHANGED =
569            "permission grant or revoke changed gids";
570
571    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
572            "permissions revoked";
573
574    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
575
576    private static final String PACKAGE_SCHEME = "package";
577
578    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
579
580    private static final String PRODUCT_OVERLAY_DIR = "/product/overlay";
581
582    /** Canonical intent used to identify what counts as a "web browser" app */
583    private static final Intent sBrowserIntent;
584    static {
585        sBrowserIntent = new Intent();
586        sBrowserIntent.setAction(Intent.ACTION_VIEW);
587        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
588        sBrowserIntent.setData(Uri.parse("http:"));
589        sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
590    }
591
592    /**
593     * The set of all protected actions [i.e. those actions for which a high priority
594     * intent filter is disallowed].
595     */
596    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
597    static {
598        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
599        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
600        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
601        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
602    }
603
604    // Compilation reasons.
605    public static final int REASON_UNKNOWN = -1;
606    public static final int REASON_FIRST_BOOT = 0;
607    public static final int REASON_BOOT = 1;
608    public static final int REASON_INSTALL = 2;
609    public static final int REASON_BACKGROUND_DEXOPT = 3;
610    public static final int REASON_AB_OTA = 4;
611    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
612    public static final int REASON_SHARED = 6;
613
614    public static final int REASON_LAST = REASON_SHARED;
615
616    /**
617     * Version number for the package parser cache. Increment this whenever the format or
618     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
619     */
620    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
621
622    /**
623     * Whether the package parser cache is enabled.
624     */
625    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
626
627    /**
628     * Permissions required in order to receive instant application lifecycle broadcasts.
629     */
630    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
631            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
632
633    final ServiceThread mHandlerThread;
634
635    final PackageHandler mHandler;
636
637    private final ProcessLoggingHandler mProcessLoggingHandler;
638
639    /**
640     * Messages for {@link #mHandler} that need to wait for system ready before
641     * being dispatched.
642     */
643    private ArrayList<Message> mPostSystemReadyMessages;
644
645    final int mSdkVersion = Build.VERSION.SDK_INT;
646
647    final Context mContext;
648    final boolean mFactoryTest;
649    final boolean mOnlyCore;
650    final DisplayMetrics mMetrics;
651    final int mDefParseFlags;
652    final String[] mSeparateProcesses;
653    final boolean mIsUpgrade;
654    final boolean mIsPreNUpgrade;
655    final boolean mIsPreNMR1Upgrade;
656
657    // Have we told the Activity Manager to whitelist the default container service by uid yet?
658    @GuardedBy("mPackages")
659    boolean mDefaultContainerWhitelisted = false;
660
661    @GuardedBy("mPackages")
662    private boolean mDexOptDialogShown;
663
664    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
665    // LOCK HELD.  Can be called with mInstallLock held.
666    @GuardedBy("mInstallLock")
667    final Installer mInstaller;
668
669    /** Directory where installed applications are stored */
670    private static final File sAppInstallDir =
671            new File(Environment.getDataDirectory(), "app");
672    /** Directory where installed application's 32-bit native libraries are copied. */
673    private static final File sAppLib32InstallDir =
674            new File(Environment.getDataDirectory(), "app-lib");
675    /** Directory where code and non-resource assets of forward-locked applications are stored */
676    private static final File sDrmAppPrivateInstallDir =
677            new File(Environment.getDataDirectory(), "app-private");
678
679    // ----------------------------------------------------------------
680
681    // Lock for state used when installing and doing other long running
682    // operations.  Methods that must be called with this lock held have
683    // the suffix "LI".
684    final Object mInstallLock = new Object();
685
686    // ----------------------------------------------------------------
687
688    // Keys are String (package name), values are Package.  This also serves
689    // as the lock for the global state.  Methods that must be called with
690    // this lock held have the prefix "LP".
691    @GuardedBy("mPackages")
692    final ArrayMap<String, PackageParser.Package> mPackages =
693            new ArrayMap<String, PackageParser.Package>();
694
695    final ArrayMap<String, Set<String>> mKnownCodebase =
696            new ArrayMap<String, Set<String>>();
697
698    // Keys are isolated uids and values are the uid of the application
699    // that created the isolated proccess.
700    @GuardedBy("mPackages")
701    final SparseIntArray mIsolatedOwners = new SparseIntArray();
702
703    /**
704     * Tracks new system packages [received in an OTA] that we expect to
705     * find updated user-installed versions. Keys are package name, values
706     * are package location.
707     */
708    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
709    /**
710     * Tracks high priority intent filters for protected actions. During boot, certain
711     * filter actions are protected and should never be allowed to have a high priority
712     * intent filter for them. However, there is one, and only one exception -- the
713     * setup wizard. It must be able to define a high priority intent filter for these
714     * actions to ensure there are no escapes from the wizard. We need to delay processing
715     * of these during boot as we need to look at all of the system packages in order
716     * to know which component is the setup wizard.
717     */
718    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
719    /**
720     * Whether or not processing protected filters should be deferred.
721     */
722    private boolean mDeferProtectedFilters = true;
723
724    /**
725     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
726     */
727    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
728    /**
729     * Whether or not system app permissions should be promoted from install to runtime.
730     */
731    boolean mPromoteSystemApps;
732
733    @GuardedBy("mPackages")
734    final Settings mSettings;
735
736    /**
737     * Set of package names that are currently "frozen", which means active
738     * surgery is being done on the code/data for that package. The platform
739     * will refuse to launch frozen packages to avoid race conditions.
740     *
741     * @see PackageFreezer
742     */
743    @GuardedBy("mPackages")
744    final ArraySet<String> mFrozenPackages = new ArraySet<>();
745
746    final ProtectedPackages mProtectedPackages;
747
748    @GuardedBy("mLoadedVolumes")
749    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
750
751    boolean mFirstBoot;
752
753    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
754
755    @GuardedBy("mAvailableFeatures")
756    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
757
758    private final InstantAppRegistry mInstantAppRegistry;
759
760    @GuardedBy("mPackages")
761    int mChangedPackagesSequenceNumber;
762    /**
763     * List of changed [installed, removed or updated] packages.
764     * mapping from user id -> sequence number -> package name
765     */
766    @GuardedBy("mPackages")
767    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
768    /**
769     * The sequence number of the last change to a package.
770     * mapping from user id -> package name -> sequence number
771     */
772    @GuardedBy("mPackages")
773    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
774
775    @GuardedBy("mPackages")
776    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
777
778    class PackageParserCallback implements PackageParser.Callback {
779        @Override public final boolean hasFeature(String feature) {
780            return PackageManagerService.this.hasSystemFeature(feature, 0);
781        }
782
783        final List<PackageParser.Package> getStaticOverlayPackages(
784                Collection<PackageParser.Package> allPackages, String targetPackageName) {
785            if ("android".equals(targetPackageName)) {
786                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
787                // native AssetManager.
788                return null;
789            }
790
791            List<PackageParser.Package> overlayPackages = null;
792            for (PackageParser.Package p : allPackages) {
793                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
794                    if (overlayPackages == null) {
795                        overlayPackages = new ArrayList<PackageParser.Package>();
796                    }
797                    overlayPackages.add(p);
798                }
799            }
800            if (overlayPackages != null) {
801                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
802                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
803                        return p1.mOverlayPriority - p2.mOverlayPriority;
804                    }
805                };
806                Collections.sort(overlayPackages, cmp);
807            }
808            return overlayPackages;
809        }
810
811        final String[] getStaticOverlayPaths(List<PackageParser.Package> overlayPackages,
812                String targetPath) {
813            if (overlayPackages == null || overlayPackages.isEmpty()) {
814                return null;
815            }
816            List<String> overlayPathList = null;
817            for (PackageParser.Package overlayPackage : overlayPackages) {
818                if (targetPath == null) {
819                    if (overlayPathList == null) {
820                        overlayPathList = new ArrayList<String>();
821                    }
822                    overlayPathList.add(overlayPackage.baseCodePath);
823                    continue;
824                }
825
826                try {
827                    // Creates idmaps for system to parse correctly the Android manifest of the
828                    // target package.
829                    //
830                    // OverlayManagerService will update each of them with a correct gid from its
831                    // target package app id.
832                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
833                            UserHandle.getSharedAppGid(
834                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
835                    if (overlayPathList == null) {
836                        overlayPathList = new ArrayList<String>();
837                    }
838                    overlayPathList.add(overlayPackage.baseCodePath);
839                } catch (InstallerException e) {
840                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
841                            overlayPackage.baseCodePath);
842                }
843            }
844            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
845        }
846
847        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
848            List<PackageParser.Package> overlayPackages;
849            synchronized (mInstallLock) {
850                synchronized (mPackages) {
851                    overlayPackages = getStaticOverlayPackages(
852                            mPackages.values(), targetPackageName);
853                }
854                // It is safe to keep overlayPackages without holding mPackages because static overlay
855                // packages can't be uninstalled or disabled.
856                return getStaticOverlayPaths(overlayPackages, targetPath);
857            }
858        }
859
860        @Override public final String[] getOverlayApks(String targetPackageName) {
861            return getStaticOverlayPaths(targetPackageName, null);
862        }
863
864        @Override public final String[] getOverlayPaths(String targetPackageName,
865                String targetPath) {
866            return getStaticOverlayPaths(targetPackageName, targetPath);
867        }
868    }
869
870    class ParallelPackageParserCallback extends PackageParserCallback {
871        List<PackageParser.Package> mOverlayPackages = null;
872
873        void findStaticOverlayPackages() {
874            synchronized (mPackages) {
875                for (PackageParser.Package p : mPackages.values()) {
876                    if (p.mOverlayIsStatic) {
877                        if (mOverlayPackages == null) {
878                            mOverlayPackages = new ArrayList<PackageParser.Package>();
879                        }
880                        mOverlayPackages.add(p);
881                    }
882                }
883            }
884        }
885
886        @Override
887        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
888            // We can trust mOverlayPackages without holding mPackages because package uninstall
889            // can't happen while running parallel parsing.
890            // And we can call mInstaller inside getStaticOverlayPaths without holding mInstallLock
891            // because mInstallLock is held before running parallel parsing.
892            // Moreover holding mPackages or mInstallLock on each parsing thread causes dead-lock.
893            return mOverlayPackages == null ? null :
894                    getStaticOverlayPaths(
895                            getStaticOverlayPackages(mOverlayPackages, targetPackageName),
896                            targetPath);
897        }
898    }
899
900    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
901    final ParallelPackageParserCallback mParallelPackageParserCallback =
902            new ParallelPackageParserCallback();
903
904    public static final class SharedLibraryEntry {
905        public final @Nullable String path;
906        public final @Nullable String apk;
907        public final @NonNull SharedLibraryInfo info;
908
909        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
910                String declaringPackageName, long declaringPackageVersionCode) {
911            path = _path;
912            apk = _apk;
913            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
914                    declaringPackageName, declaringPackageVersionCode), null);
915        }
916    }
917
918    // Currently known shared libraries.
919    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
920    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
921            new ArrayMap<>();
922
923    // All available activities, for your resolving pleasure.
924    final ActivityIntentResolver mActivities =
925            new ActivityIntentResolver();
926
927    // All available receivers, for your resolving pleasure.
928    final ActivityIntentResolver mReceivers =
929            new ActivityIntentResolver();
930
931    // All available services, for your resolving pleasure.
932    final ServiceIntentResolver mServices = new ServiceIntentResolver();
933
934    // All available providers, for your resolving pleasure.
935    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
936
937    // Mapping from provider base names (first directory in content URI codePath)
938    // to the provider information.
939    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
940            new ArrayMap<String, PackageParser.Provider>();
941
942    // Mapping from instrumentation class names to info about them.
943    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
944            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
945
946    // Packages whose data we have transfered into another package, thus
947    // should no longer exist.
948    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
949
950    // Broadcast actions that are only available to the system.
951    @GuardedBy("mProtectedBroadcasts")
952    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
953
954    /** List of packages waiting for verification. */
955    final SparseArray<PackageVerificationState> mPendingVerification
956            = new SparseArray<PackageVerificationState>();
957
958    final PackageInstallerService mInstallerService;
959
960    final ArtManagerService mArtManagerService;
961
962    private final PackageDexOptimizer mPackageDexOptimizer;
963    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
964    // is used by other apps).
965    private final DexManager mDexManager;
966
967    private AtomicInteger mNextMoveId = new AtomicInteger();
968    private final MoveCallbacks mMoveCallbacks;
969
970    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
971
972    // Cache of users who need badging.
973    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
974
975    /** Token for keys in mPendingVerification. */
976    private int mPendingVerificationToken = 0;
977
978    volatile boolean mSystemReady;
979    volatile boolean mSafeMode;
980    volatile boolean mHasSystemUidErrors;
981    private volatile boolean mWebInstantAppsDisabled;
982
983    ApplicationInfo mAndroidApplication;
984    final ActivityInfo mResolveActivity = new ActivityInfo();
985    final ResolveInfo mResolveInfo = new ResolveInfo();
986    ComponentName mResolveComponentName;
987    PackageParser.Package mPlatformPackage;
988    ComponentName mCustomResolverComponentName;
989
990    boolean mResolverReplaced = false;
991
992    private final @Nullable ComponentName mIntentFilterVerifierComponent;
993    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
994
995    private int mIntentFilterVerificationToken = 0;
996
997    /** The service connection to the ephemeral resolver */
998    final InstantAppResolverConnection mInstantAppResolverConnection;
999    /** Component used to show resolver settings for Instant Apps */
1000    final ComponentName mInstantAppResolverSettingsComponent;
1001
1002    /** Activity used to install instant applications */
1003    ActivityInfo mInstantAppInstallerActivity;
1004    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1005
1006    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1007            = new SparseArray<IntentFilterVerificationState>();
1008
1009    // TODO remove this and go through mPermissonManager directly
1010    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1011    private final PermissionManagerInternal mPermissionManager;
1012
1013    // List of packages names to keep cached, even if they are uninstalled for all users
1014    private List<String> mKeepUninstalledPackages;
1015
1016    private UserManagerInternal mUserManagerInternal;
1017    private ActivityManagerInternal mActivityManagerInternal;
1018
1019    private DeviceIdleController.LocalService mDeviceIdleController;
1020
1021    private File mCacheDir;
1022
1023    private Future<?> mPrepareAppDataFuture;
1024
1025    private static class IFVerificationParams {
1026        PackageParser.Package pkg;
1027        boolean replacing;
1028        int userId;
1029        int verifierUid;
1030
1031        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1032                int _userId, int _verifierUid) {
1033            pkg = _pkg;
1034            replacing = _replacing;
1035            userId = _userId;
1036            replacing = _replacing;
1037            verifierUid = _verifierUid;
1038        }
1039    }
1040
1041    private interface IntentFilterVerifier<T extends IntentFilter> {
1042        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1043                                               T filter, String packageName);
1044        void startVerifications(int userId);
1045        void receiveVerificationResponse(int verificationId);
1046    }
1047
1048    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1049        private Context mContext;
1050        private ComponentName mIntentFilterVerifierComponent;
1051        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1052
1053        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1054            mContext = context;
1055            mIntentFilterVerifierComponent = verifierComponent;
1056        }
1057
1058        private String getDefaultScheme() {
1059            return IntentFilter.SCHEME_HTTPS;
1060        }
1061
1062        @Override
1063        public void startVerifications(int userId) {
1064            // Launch verifications requests
1065            int count = mCurrentIntentFilterVerifications.size();
1066            for (int n=0; n<count; n++) {
1067                int verificationId = mCurrentIntentFilterVerifications.get(n);
1068                final IntentFilterVerificationState ivs =
1069                        mIntentFilterVerificationStates.get(verificationId);
1070
1071                String packageName = ivs.getPackageName();
1072
1073                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1074                final int filterCount = filters.size();
1075                ArraySet<String> domainsSet = new ArraySet<>();
1076                for (int m=0; m<filterCount; m++) {
1077                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1078                    domainsSet.addAll(filter.getHostsList());
1079                }
1080                synchronized (mPackages) {
1081                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1082                            packageName, domainsSet) != null) {
1083                        scheduleWriteSettingsLocked();
1084                    }
1085                }
1086                sendVerificationRequest(verificationId, ivs);
1087            }
1088            mCurrentIntentFilterVerifications.clear();
1089        }
1090
1091        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1092            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1093            verificationIntent.putExtra(
1094                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1095                    verificationId);
1096            verificationIntent.putExtra(
1097                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1098                    getDefaultScheme());
1099            verificationIntent.putExtra(
1100                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1101                    ivs.getHostsString());
1102            verificationIntent.putExtra(
1103                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1104                    ivs.getPackageName());
1105            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1106            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1107
1108            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1109            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1110                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1111                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1112
1113            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1114            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1115                    "Sending IntentFilter verification broadcast");
1116        }
1117
1118        public void receiveVerificationResponse(int verificationId) {
1119            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1120
1121            final boolean verified = ivs.isVerified();
1122
1123            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1124            final int count = filters.size();
1125            if (DEBUG_DOMAIN_VERIFICATION) {
1126                Slog.i(TAG, "Received verification response " + verificationId
1127                        + " for " + count + " filters, verified=" + verified);
1128            }
1129            for (int n=0; n<count; n++) {
1130                PackageParser.ActivityIntentInfo filter = filters.get(n);
1131                filter.setVerified(verified);
1132
1133                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1134                        + " verified with result:" + verified + " and hosts:"
1135                        + ivs.getHostsString());
1136            }
1137
1138            mIntentFilterVerificationStates.remove(verificationId);
1139
1140            final String packageName = ivs.getPackageName();
1141            IntentFilterVerificationInfo ivi = null;
1142
1143            synchronized (mPackages) {
1144                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1145            }
1146            if (ivi == null) {
1147                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1148                        + verificationId + " packageName:" + packageName);
1149                return;
1150            }
1151            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1152                    "Updating IntentFilterVerificationInfo for package " + packageName
1153                            +" verificationId:" + verificationId);
1154
1155            synchronized (mPackages) {
1156                if (verified) {
1157                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1158                } else {
1159                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1160                }
1161                scheduleWriteSettingsLocked();
1162
1163                final int userId = ivs.getUserId();
1164                if (userId != UserHandle.USER_ALL) {
1165                    final int userStatus =
1166                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1167
1168                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1169                    boolean needUpdate = false;
1170
1171                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1172                    // already been set by the User thru the Disambiguation dialog
1173                    switch (userStatus) {
1174                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1175                            if (verified) {
1176                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1177                            } else {
1178                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1179                            }
1180                            needUpdate = true;
1181                            break;
1182
1183                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1184                            if (verified) {
1185                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1186                                needUpdate = true;
1187                            }
1188                            break;
1189
1190                        default:
1191                            // Nothing to do
1192                    }
1193
1194                    if (needUpdate) {
1195                        mSettings.updateIntentFilterVerificationStatusLPw(
1196                                packageName, updatedStatus, userId);
1197                        scheduleWritePackageRestrictionsLocked(userId);
1198                    }
1199                }
1200            }
1201        }
1202
1203        @Override
1204        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1205                    ActivityIntentInfo filter, String packageName) {
1206            if (!hasValidDomains(filter)) {
1207                return false;
1208            }
1209            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1210            if (ivs == null) {
1211                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1212                        packageName);
1213            }
1214            if (DEBUG_DOMAIN_VERIFICATION) {
1215                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1216            }
1217            ivs.addFilter(filter);
1218            return true;
1219        }
1220
1221        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1222                int userId, int verificationId, String packageName) {
1223            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1224                    verifierUid, userId, packageName);
1225            ivs.setPendingState();
1226            synchronized (mPackages) {
1227                mIntentFilterVerificationStates.append(verificationId, ivs);
1228                mCurrentIntentFilterVerifications.add(verificationId);
1229            }
1230            return ivs;
1231        }
1232    }
1233
1234    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1235        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1236                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1237                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1238    }
1239
1240    // Set of pending broadcasts for aggregating enable/disable of components.
1241    static class PendingPackageBroadcasts {
1242        // for each user id, a map of <package name -> components within that package>
1243        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1244
1245        public PendingPackageBroadcasts() {
1246            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1247        }
1248
1249        public ArrayList<String> get(int userId, String packageName) {
1250            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1251            return packages.get(packageName);
1252        }
1253
1254        public void put(int userId, String packageName, ArrayList<String> components) {
1255            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1256            packages.put(packageName, components);
1257        }
1258
1259        public void remove(int userId, String packageName) {
1260            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1261            if (packages != null) {
1262                packages.remove(packageName);
1263            }
1264        }
1265
1266        public void remove(int userId) {
1267            mUidMap.remove(userId);
1268        }
1269
1270        public int userIdCount() {
1271            return mUidMap.size();
1272        }
1273
1274        public int userIdAt(int n) {
1275            return mUidMap.keyAt(n);
1276        }
1277
1278        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1279            return mUidMap.get(userId);
1280        }
1281
1282        public int size() {
1283            // total number of pending broadcast entries across all userIds
1284            int num = 0;
1285            for (int i = 0; i< mUidMap.size(); i++) {
1286                num += mUidMap.valueAt(i).size();
1287            }
1288            return num;
1289        }
1290
1291        public void clear() {
1292            mUidMap.clear();
1293        }
1294
1295        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1296            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1297            if (map == null) {
1298                map = new ArrayMap<String, ArrayList<String>>();
1299                mUidMap.put(userId, map);
1300            }
1301            return map;
1302        }
1303    }
1304    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1305
1306    // Service Connection to remote media container service to copy
1307    // package uri's from external media onto secure containers
1308    // or internal storage.
1309    private IMediaContainerService mContainerService = null;
1310
1311    static final int SEND_PENDING_BROADCAST = 1;
1312    static final int MCS_BOUND = 3;
1313    static final int END_COPY = 4;
1314    static final int INIT_COPY = 5;
1315    static final int MCS_UNBIND = 6;
1316    static final int START_CLEANING_PACKAGE = 7;
1317    static final int FIND_INSTALL_LOC = 8;
1318    static final int POST_INSTALL = 9;
1319    static final int MCS_RECONNECT = 10;
1320    static final int MCS_GIVE_UP = 11;
1321    static final int WRITE_SETTINGS = 13;
1322    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1323    static final int PACKAGE_VERIFIED = 15;
1324    static final int CHECK_PENDING_VERIFICATION = 16;
1325    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1326    static final int INTENT_FILTER_VERIFIED = 18;
1327    static final int WRITE_PACKAGE_LIST = 19;
1328    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1329    static final int DEF_CONTAINER_BIND = 21;
1330
1331    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1332
1333    // Delay time in millisecs
1334    static final int BROADCAST_DELAY = 10 * 1000;
1335
1336    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1337            2 * 60 * 60 * 1000L; /* two hours */
1338
1339    static UserManagerService sUserManager;
1340
1341    // Stores a list of users whose package restrictions file needs to be updated
1342    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1343
1344    final private DefaultContainerConnection mDefContainerConn =
1345            new DefaultContainerConnection();
1346    class DefaultContainerConnection implements ServiceConnection {
1347        public void onServiceConnected(ComponentName name, IBinder service) {
1348            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1349            final IMediaContainerService imcs = IMediaContainerService.Stub
1350                    .asInterface(Binder.allowBlocking(service));
1351            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1352        }
1353
1354        public void onServiceDisconnected(ComponentName name) {
1355            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1356        }
1357    }
1358
1359    // Recordkeeping of restore-after-install operations that are currently in flight
1360    // between the Package Manager and the Backup Manager
1361    static class PostInstallData {
1362        public InstallArgs args;
1363        public PackageInstalledInfo res;
1364
1365        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1366            args = _a;
1367            res = _r;
1368        }
1369    }
1370
1371    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1372    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1373
1374    // XML tags for backup/restore of various bits of state
1375    private static final String TAG_PREFERRED_BACKUP = "pa";
1376    private static final String TAG_DEFAULT_APPS = "da";
1377    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1378
1379    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1380    private static final String TAG_ALL_GRANTS = "rt-grants";
1381    private static final String TAG_GRANT = "grant";
1382    private static final String ATTR_PACKAGE_NAME = "pkg";
1383
1384    private static final String TAG_PERMISSION = "perm";
1385    private static final String ATTR_PERMISSION_NAME = "name";
1386    private static final String ATTR_IS_GRANTED = "g";
1387    private static final String ATTR_USER_SET = "set";
1388    private static final String ATTR_USER_FIXED = "fixed";
1389    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1390
1391    // System/policy permission grants are not backed up
1392    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1393            FLAG_PERMISSION_POLICY_FIXED
1394            | FLAG_PERMISSION_SYSTEM_FIXED
1395            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1396
1397    // And we back up these user-adjusted states
1398    private static final int USER_RUNTIME_GRANT_MASK =
1399            FLAG_PERMISSION_USER_SET
1400            | FLAG_PERMISSION_USER_FIXED
1401            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1402
1403    final @Nullable String mRequiredVerifierPackage;
1404    final @NonNull String mRequiredInstallerPackage;
1405    final @NonNull String mRequiredUninstallerPackage;
1406    final @Nullable String mSetupWizardPackage;
1407    final @Nullable String mStorageManagerPackage;
1408    final @Nullable String mSystemTextClassifierPackage;
1409    final @NonNull String mServicesSystemSharedLibraryPackageName;
1410    final @NonNull String mSharedSystemSharedLibraryPackageName;
1411
1412    private final PackageUsage mPackageUsage = new PackageUsage();
1413    private final CompilerStats mCompilerStats = new CompilerStats();
1414
1415    class PackageHandler extends Handler {
1416        private boolean mBound = false;
1417        final ArrayList<HandlerParams> mPendingInstalls =
1418            new ArrayList<HandlerParams>();
1419
1420        private boolean connectToService() {
1421            if (DEBUG_INSTALL) Log.i(TAG, "Trying to bind to DefaultContainerService");
1422            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1423            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1424            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1425                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1426                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1427                mBound = true;
1428                return true;
1429            }
1430            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1431            return false;
1432        }
1433
1434        private void disconnectService() {
1435            mContainerService = null;
1436            mBound = false;
1437            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1438            mContext.unbindService(mDefContainerConn);
1439            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1440        }
1441
1442        PackageHandler(Looper looper) {
1443            super(looper);
1444        }
1445
1446        public void handleMessage(Message msg) {
1447            try {
1448                doHandleMessage(msg);
1449            } finally {
1450                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1451            }
1452        }
1453
1454        void doHandleMessage(Message msg) {
1455            switch (msg.what) {
1456                case DEF_CONTAINER_BIND:
1457                    if (!mBound) {
1458                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "earlyBindingMCS",
1459                                System.identityHashCode(mHandler));
1460                        if (!connectToService()) {
1461                            Slog.e(TAG, "Failed to bind to media container service");
1462                        }
1463                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "earlyBindingMCS",
1464                                System.identityHashCode(mHandler));
1465                    }
1466                    break;
1467                case INIT_COPY: {
1468                    HandlerParams params = (HandlerParams) msg.obj;
1469                    int idx = mPendingInstalls.size();
1470                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1471                    // If a bind was already initiated we dont really
1472                    // need to do anything. The pending install
1473                    // will be processed later on.
1474                    if (!mBound) {
1475                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1476                                System.identityHashCode(mHandler));
1477                        // If this is the only one pending we might
1478                        // have to bind to the service again.
1479                        if (!connectToService()) {
1480                            Slog.e(TAG, "Failed to bind to media container service");
1481                            params.serviceError();
1482                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1483                                    System.identityHashCode(mHandler));
1484                            if (params.traceMethod != null) {
1485                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1486                                        params.traceCookie);
1487                            }
1488                            return;
1489                        } else {
1490                            // Once we bind to the service, the first
1491                            // pending request will be processed.
1492                            mPendingInstalls.add(idx, params);
1493                        }
1494                    } else {
1495                        mPendingInstalls.add(idx, params);
1496                        // Already bound to the service. Just make
1497                        // sure we trigger off processing the first request.
1498                        if (idx == 0) {
1499                            mHandler.sendEmptyMessage(MCS_BOUND);
1500                        }
1501                    }
1502                    break;
1503                }
1504                case MCS_BOUND: {
1505                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1506                    if (msg.obj != null) {
1507                        mContainerService = (IMediaContainerService) msg.obj;
1508                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1509                                System.identityHashCode(mHandler));
1510                    }
1511                    if (mContainerService == null) {
1512                        if (!mBound) {
1513                            // Something seriously wrong since we are not bound and we are not
1514                            // waiting for connection. Bail out.
1515                            Slog.e(TAG, "Cannot bind to media container service");
1516                            for (HandlerParams params : mPendingInstalls) {
1517                                // Indicate service bind error
1518                                params.serviceError();
1519                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1520                                        System.identityHashCode(params));
1521                                if (params.traceMethod != null) {
1522                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1523                                            params.traceMethod, params.traceCookie);
1524                                }
1525                            }
1526                            mPendingInstalls.clear();
1527                        } else {
1528                            Slog.w(TAG, "Waiting to connect to media container service");
1529                        }
1530                    } else if (mPendingInstalls.size() > 0) {
1531                        HandlerParams params = mPendingInstalls.get(0);
1532                        if (params != null) {
1533                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1534                                    System.identityHashCode(params));
1535                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1536                            if (params.startCopy()) {
1537                                // We are done...  look for more work or to
1538                                // go idle.
1539                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1540                                        "Checking for more work or unbind...");
1541                                // Delete pending install
1542                                if (mPendingInstalls.size() > 0) {
1543                                    mPendingInstalls.remove(0);
1544                                }
1545                                if (mPendingInstalls.size() == 0) {
1546                                    if (mBound) {
1547                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1548                                                "Posting delayed MCS_UNBIND");
1549                                        removeMessages(MCS_UNBIND);
1550                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1551                                        // Unbind after a little delay, to avoid
1552                                        // continual thrashing.
1553                                        sendMessageDelayed(ubmsg, 10000);
1554                                    }
1555                                } else {
1556                                    // There are more pending requests in queue.
1557                                    // Just post MCS_BOUND message to trigger processing
1558                                    // of next pending install.
1559                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1560                                            "Posting MCS_BOUND for next work");
1561                                    mHandler.sendEmptyMessage(MCS_BOUND);
1562                                }
1563                            }
1564                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1565                        }
1566                    } else {
1567                        // Should never happen ideally.
1568                        Slog.w(TAG, "Empty queue");
1569                    }
1570                    break;
1571                }
1572                case MCS_RECONNECT: {
1573                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1574                    if (mPendingInstalls.size() > 0) {
1575                        if (mBound) {
1576                            disconnectService();
1577                        }
1578                        if (!connectToService()) {
1579                            Slog.e(TAG, "Failed to bind to media container service");
1580                            for (HandlerParams params : mPendingInstalls) {
1581                                // Indicate service bind error
1582                                params.serviceError();
1583                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1584                                        System.identityHashCode(params));
1585                            }
1586                            mPendingInstalls.clear();
1587                        }
1588                    }
1589                    break;
1590                }
1591                case MCS_UNBIND: {
1592                    // If there is no actual work left, then time to unbind.
1593                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1594
1595                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1596                        if (mBound) {
1597                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1598
1599                            disconnectService();
1600                        }
1601                    } else if (mPendingInstalls.size() > 0) {
1602                        // There are more pending requests in queue.
1603                        // Just post MCS_BOUND message to trigger processing
1604                        // of next pending install.
1605                        mHandler.sendEmptyMessage(MCS_BOUND);
1606                    }
1607
1608                    break;
1609                }
1610                case MCS_GIVE_UP: {
1611                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1612                    HandlerParams params = mPendingInstalls.remove(0);
1613                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1614                            System.identityHashCode(params));
1615                    break;
1616                }
1617                case SEND_PENDING_BROADCAST: {
1618                    String packages[];
1619                    ArrayList<String> components[];
1620                    int size = 0;
1621                    int uids[];
1622                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1623                    synchronized (mPackages) {
1624                        if (mPendingBroadcasts == null) {
1625                            return;
1626                        }
1627                        size = mPendingBroadcasts.size();
1628                        if (size <= 0) {
1629                            // Nothing to be done. Just return
1630                            return;
1631                        }
1632                        packages = new String[size];
1633                        components = new ArrayList[size];
1634                        uids = new int[size];
1635                        int i = 0;  // filling out the above arrays
1636
1637                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1638                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1639                            Iterator<Map.Entry<String, ArrayList<String>>> it
1640                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1641                                            .entrySet().iterator();
1642                            while (it.hasNext() && i < size) {
1643                                Map.Entry<String, ArrayList<String>> ent = it.next();
1644                                packages[i] = ent.getKey();
1645                                components[i] = ent.getValue();
1646                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1647                                uids[i] = (ps != null)
1648                                        ? UserHandle.getUid(packageUserId, ps.appId)
1649                                        : -1;
1650                                i++;
1651                            }
1652                        }
1653                        size = i;
1654                        mPendingBroadcasts.clear();
1655                    }
1656                    // Send broadcasts
1657                    for (int i = 0; i < size; i++) {
1658                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1659                    }
1660                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1661                    break;
1662                }
1663                case START_CLEANING_PACKAGE: {
1664                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1665                    final String packageName = (String)msg.obj;
1666                    final int userId = msg.arg1;
1667                    final boolean andCode = msg.arg2 != 0;
1668                    synchronized (mPackages) {
1669                        if (userId == UserHandle.USER_ALL) {
1670                            int[] users = sUserManager.getUserIds();
1671                            for (int user : users) {
1672                                mSettings.addPackageToCleanLPw(
1673                                        new PackageCleanItem(user, packageName, andCode));
1674                            }
1675                        } else {
1676                            mSettings.addPackageToCleanLPw(
1677                                    new PackageCleanItem(userId, packageName, andCode));
1678                        }
1679                    }
1680                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1681                    startCleaningPackages();
1682                } break;
1683                case POST_INSTALL: {
1684                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1685
1686                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1687                    final boolean didRestore = (msg.arg2 != 0);
1688                    mRunningInstalls.delete(msg.arg1);
1689
1690                    if (data != null) {
1691                        InstallArgs args = data.args;
1692                        PackageInstalledInfo parentRes = data.res;
1693
1694                        final boolean grantPermissions = (args.installFlags
1695                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1696                        final boolean killApp = (args.installFlags
1697                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1698                        final boolean virtualPreload = ((args.installFlags
1699                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1700                        final String[] grantedPermissions = args.installGrantPermissions;
1701
1702                        // Handle the parent package
1703                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1704                                virtualPreload, grantedPermissions, didRestore,
1705                                args.installerPackageName, args.observer);
1706
1707                        // Handle the child packages
1708                        final int childCount = (parentRes.addedChildPackages != null)
1709                                ? parentRes.addedChildPackages.size() : 0;
1710                        for (int i = 0; i < childCount; i++) {
1711                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1712                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1713                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1714                                    args.installerPackageName, args.observer);
1715                        }
1716
1717                        // Log tracing if needed
1718                        if (args.traceMethod != null) {
1719                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1720                                    args.traceCookie);
1721                        }
1722                    } else {
1723                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1724                    }
1725
1726                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1727                } break;
1728                case WRITE_SETTINGS: {
1729                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1730                    synchronized (mPackages) {
1731                        removeMessages(WRITE_SETTINGS);
1732                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1733                        mSettings.writeLPr();
1734                        mDirtyUsers.clear();
1735                    }
1736                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1737                } break;
1738                case WRITE_PACKAGE_RESTRICTIONS: {
1739                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1740                    synchronized (mPackages) {
1741                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1742                        for (int userId : mDirtyUsers) {
1743                            mSettings.writePackageRestrictionsLPr(userId);
1744                        }
1745                        mDirtyUsers.clear();
1746                    }
1747                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1748                } break;
1749                case WRITE_PACKAGE_LIST: {
1750                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1751                    synchronized (mPackages) {
1752                        removeMessages(WRITE_PACKAGE_LIST);
1753                        mSettings.writePackageListLPr(msg.arg1);
1754                    }
1755                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1756                } break;
1757                case CHECK_PENDING_VERIFICATION: {
1758                    final int verificationId = msg.arg1;
1759                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1760
1761                    if ((state != null) && !state.timeoutExtended()) {
1762                        final InstallArgs args = state.getInstallArgs();
1763                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1764
1765                        Slog.i(TAG, "Verification timed out for " + originUri);
1766                        mPendingVerification.remove(verificationId);
1767
1768                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1769
1770                        final UserHandle user = args.getUser();
1771                        if (getDefaultVerificationResponse(user)
1772                                == PackageManager.VERIFICATION_ALLOW) {
1773                            Slog.i(TAG, "Continuing with installation of " + originUri);
1774                            state.setVerifierResponse(Binder.getCallingUid(),
1775                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1776                            broadcastPackageVerified(verificationId, originUri,
1777                                    PackageManager.VERIFICATION_ALLOW, user);
1778                            try {
1779                                ret = args.copyApk(mContainerService, true);
1780                            } catch (RemoteException e) {
1781                                Slog.e(TAG, "Could not contact the ContainerService");
1782                            }
1783                        } else {
1784                            broadcastPackageVerified(verificationId, originUri,
1785                                    PackageManager.VERIFICATION_REJECT, user);
1786                        }
1787
1788                        Trace.asyncTraceEnd(
1789                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1790
1791                        processPendingInstall(args, ret);
1792                        mHandler.sendEmptyMessage(MCS_UNBIND);
1793                    }
1794                    break;
1795                }
1796                case PACKAGE_VERIFIED: {
1797                    final int verificationId = msg.arg1;
1798
1799                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1800                    if (state == null) {
1801                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1802                        break;
1803                    }
1804
1805                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1806
1807                    state.setVerifierResponse(response.callerUid, response.code);
1808
1809                    if (state.isVerificationComplete()) {
1810                        mPendingVerification.remove(verificationId);
1811
1812                        final InstallArgs args = state.getInstallArgs();
1813                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1814
1815                        int ret;
1816                        if (state.isInstallAllowed()) {
1817                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1818                            broadcastPackageVerified(verificationId, originUri,
1819                                    response.code, state.getInstallArgs().getUser());
1820                            try {
1821                                ret = args.copyApk(mContainerService, true);
1822                            } catch (RemoteException e) {
1823                                Slog.e(TAG, "Could not contact the ContainerService");
1824                            }
1825                        } else {
1826                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1827                        }
1828
1829                        Trace.asyncTraceEnd(
1830                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1831
1832                        processPendingInstall(args, ret);
1833                        mHandler.sendEmptyMessage(MCS_UNBIND);
1834                    }
1835
1836                    break;
1837                }
1838                case START_INTENT_FILTER_VERIFICATIONS: {
1839                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1840                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1841                            params.replacing, params.pkg);
1842                    break;
1843                }
1844                case INTENT_FILTER_VERIFIED: {
1845                    final int verificationId = msg.arg1;
1846
1847                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1848                            verificationId);
1849                    if (state == null) {
1850                        Slog.w(TAG, "Invalid IntentFilter verification token "
1851                                + verificationId + " received");
1852                        break;
1853                    }
1854
1855                    final int userId = state.getUserId();
1856
1857                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1858                            "Processing IntentFilter verification with token:"
1859                            + verificationId + " and userId:" + userId);
1860
1861                    final IntentFilterVerificationResponse response =
1862                            (IntentFilterVerificationResponse) msg.obj;
1863
1864                    state.setVerifierResponse(response.callerUid, response.code);
1865
1866                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1867                            "IntentFilter verification with token:" + verificationId
1868                            + " and userId:" + userId
1869                            + " is settings verifier response with response code:"
1870                            + response.code);
1871
1872                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1873                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1874                                + response.getFailedDomainsString());
1875                    }
1876
1877                    if (state.isVerificationComplete()) {
1878                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1879                    } else {
1880                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1881                                "IntentFilter verification with token:" + verificationId
1882                                + " was not said to be complete");
1883                    }
1884
1885                    break;
1886                }
1887                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1888                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1889                            mInstantAppResolverConnection,
1890                            (InstantAppRequest) msg.obj,
1891                            mInstantAppInstallerActivity,
1892                            mHandler);
1893                }
1894            }
1895        }
1896    }
1897
1898    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1899        @Override
1900        public void onGidsChanged(int appId, int userId) {
1901            mHandler.post(new Runnable() {
1902                @Override
1903                public void run() {
1904                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1905                }
1906            });
1907        }
1908        @Override
1909        public void onPermissionGranted(int uid, int userId) {
1910            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1911
1912            // Not critical; if this is lost, the application has to request again.
1913            synchronized (mPackages) {
1914                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1915            }
1916        }
1917        @Override
1918        public void onInstallPermissionGranted() {
1919            synchronized (mPackages) {
1920                scheduleWriteSettingsLocked();
1921            }
1922        }
1923        @Override
1924        public void onPermissionRevoked(int uid, int userId) {
1925            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1926
1927            synchronized (mPackages) {
1928                // Critical; after this call the application should never have the permission
1929                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1930            }
1931
1932            final int appId = UserHandle.getAppId(uid);
1933            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1934        }
1935        @Override
1936        public void onInstallPermissionRevoked() {
1937            synchronized (mPackages) {
1938                scheduleWriteSettingsLocked();
1939            }
1940        }
1941        @Override
1942        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1943            synchronized (mPackages) {
1944                for (int userId : updatedUserIds) {
1945                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1946                }
1947            }
1948        }
1949        @Override
1950        public void onInstallPermissionUpdated() {
1951            synchronized (mPackages) {
1952                scheduleWriteSettingsLocked();
1953            }
1954        }
1955        @Override
1956        public void onPermissionRemoved() {
1957            synchronized (mPackages) {
1958                mSettings.writeLPr();
1959            }
1960        }
1961    };
1962
1963    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1964            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1965            boolean launchedForRestore, String installerPackage,
1966            IPackageInstallObserver2 installObserver) {
1967        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1968            // Send the removed broadcasts
1969            if (res.removedInfo != null) {
1970                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1971            }
1972
1973            // Now that we successfully installed the package, grant runtime
1974            // permissions if requested before broadcasting the install. Also
1975            // for legacy apps in permission review mode we clear the permission
1976            // review flag which is used to emulate runtime permissions for
1977            // legacy apps.
1978            if (grantPermissions) {
1979                final int callingUid = Binder.getCallingUid();
1980                mPermissionManager.grantRequestedRuntimePermissions(
1981                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1982                        mPermissionCallback);
1983            }
1984
1985            final boolean update = res.removedInfo != null
1986                    && res.removedInfo.removedPackage != null;
1987            final String installerPackageName =
1988                    res.installerPackageName != null
1989                            ? res.installerPackageName
1990                            : res.removedInfo != null
1991                                    ? res.removedInfo.installerPackageName
1992                                    : null;
1993
1994            // If this is the first time we have child packages for a disabled privileged
1995            // app that had no children, we grant requested runtime permissions to the new
1996            // children if the parent on the system image had them already granted.
1997            if (res.pkg.parentPackage != null) {
1998                final int callingUid = Binder.getCallingUid();
1999                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
2000                        res.pkg, callingUid, mPermissionCallback);
2001            }
2002
2003            synchronized (mPackages) {
2004                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
2005            }
2006
2007            final String packageName = res.pkg.applicationInfo.packageName;
2008
2009            // Determine the set of users who are adding this package for
2010            // the first time vs. those who are seeing an update.
2011            int[] firstUserIds = EMPTY_INT_ARRAY;
2012            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
2013            int[] updateUserIds = EMPTY_INT_ARRAY;
2014            int[] instantUserIds = EMPTY_INT_ARRAY;
2015            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
2016            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
2017            for (int newUser : res.newUsers) {
2018                final boolean isInstantApp = ps.getInstantApp(newUser);
2019                if (allNewUsers) {
2020                    if (isInstantApp) {
2021                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2022                    } else {
2023                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2024                    }
2025                    continue;
2026                }
2027                boolean isNew = true;
2028                for (int origUser : res.origUsers) {
2029                    if (origUser == newUser) {
2030                        isNew = false;
2031                        break;
2032                    }
2033                }
2034                if (isNew) {
2035                    if (isInstantApp) {
2036                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2037                    } else {
2038                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2039                    }
2040                } else {
2041                    if (isInstantApp) {
2042                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2043                    } else {
2044                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2045                    }
2046                }
2047            }
2048
2049            // Send installed broadcasts if the package is not a static shared lib.
2050            if (res.pkg.staticSharedLibName == null) {
2051                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2052
2053                // Send added for users that see the package for the first time
2054                // sendPackageAddedForNewUsers also deals with system apps
2055                int appId = UserHandle.getAppId(res.uid);
2056                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2057                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2058                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2059
2060                // Send added for users that don't see the package for the first time
2061                Bundle extras = new Bundle(1);
2062                extras.putInt(Intent.EXTRA_UID, res.uid);
2063                if (update) {
2064                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2065                }
2066                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2067                        extras, 0 /*flags*/,
2068                        null /*targetPackage*/, null /*finishedReceiver*/,
2069                        updateUserIds, instantUserIds);
2070                if (installerPackageName != null) {
2071                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2072                            extras, 0 /*flags*/,
2073                            installerPackageName, null /*finishedReceiver*/,
2074                            updateUserIds, instantUserIds);
2075                }
2076                // if the required verifier is defined, but, is not the installer of record
2077                // for the package, it gets notified
2078                final boolean notifyVerifier = mRequiredVerifierPackage != null
2079                        && !mRequiredVerifierPackage.equals(installerPackageName);
2080                if (notifyVerifier) {
2081                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2082                            extras, 0 /*flags*/,
2083                            mRequiredVerifierPackage, null /*finishedReceiver*/,
2084                            updateUserIds, instantUserIds);
2085                }
2086
2087                // Send replaced for users that don't see the package for the first time
2088                if (update) {
2089                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2090                            packageName, extras, 0 /*flags*/,
2091                            null /*targetPackage*/, null /*finishedReceiver*/,
2092                            updateUserIds, instantUserIds);
2093                    if (installerPackageName != null) {
2094                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2095                                extras, 0 /*flags*/,
2096                                installerPackageName, null /*finishedReceiver*/,
2097                                updateUserIds, instantUserIds);
2098                    }
2099                    if (notifyVerifier) {
2100                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2101                                extras, 0 /*flags*/,
2102                                mRequiredVerifierPackage, null /*finishedReceiver*/,
2103                                updateUserIds, instantUserIds);
2104                    }
2105                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2106                            null /*package*/, null /*extras*/, 0 /*flags*/,
2107                            packageName /*targetPackage*/,
2108                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2109                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2110                    // First-install and we did a restore, so we're responsible for the
2111                    // first-launch broadcast.
2112                    if (DEBUG_BACKUP) {
2113                        Slog.i(TAG, "Post-restore of " + packageName
2114                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2115                    }
2116                    sendFirstLaunchBroadcast(packageName, installerPackage,
2117                            firstUserIds, firstInstantUserIds);
2118                }
2119
2120                // Send broadcast package appeared if forward locked/external for all users
2121                // treat asec-hosted packages like removable media on upgrade
2122                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2123                    if (DEBUG_INSTALL) {
2124                        Slog.i(TAG, "upgrading pkg " + res.pkg
2125                                + " is ASEC-hosted -> AVAILABLE");
2126                    }
2127                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2128                    ArrayList<String> pkgList = new ArrayList<>(1);
2129                    pkgList.add(packageName);
2130                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2131                }
2132            }
2133
2134            // Work that needs to happen on first install within each user
2135            if (firstUserIds != null && firstUserIds.length > 0) {
2136                synchronized (mPackages) {
2137                    for (int userId : firstUserIds) {
2138                        // If this app is a browser and it's newly-installed for some
2139                        // users, clear any default-browser state in those users. The
2140                        // app's nature doesn't depend on the user, so we can just check
2141                        // its browser nature in any user and generalize.
2142                        if (packageIsBrowser(packageName, userId)) {
2143                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2144                        }
2145
2146                        // We may also need to apply pending (restored) runtime
2147                        // permission grants within these users.
2148                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2149                    }
2150                }
2151            }
2152
2153            if (allNewUsers && !update) {
2154                notifyPackageAdded(packageName);
2155            }
2156
2157            // Log current value of "unknown sources" setting
2158            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2159                    getUnknownSourcesSettings());
2160
2161            // Remove the replaced package's older resources safely now
2162            // We delete after a gc for applications  on sdcard.
2163            if (res.removedInfo != null && res.removedInfo.args != null) {
2164                Runtime.getRuntime().gc();
2165                synchronized (mInstallLock) {
2166                    res.removedInfo.args.doPostDeleteLI(true);
2167                }
2168            } else {
2169                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2170                // and not block here.
2171                VMRuntime.getRuntime().requestConcurrentGC();
2172            }
2173
2174            // Notify DexManager that the package was installed for new users.
2175            // The updated users should already be indexed and the package code paths
2176            // should not change.
2177            // Don't notify the manager for ephemeral apps as they are not expected to
2178            // survive long enough to benefit of background optimizations.
2179            for (int userId : firstUserIds) {
2180                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2181                // There's a race currently where some install events may interleave with an uninstall.
2182                // This can lead to package info being null (b/36642664).
2183                if (info != null) {
2184                    mDexManager.notifyPackageInstalled(info, userId);
2185                }
2186            }
2187        }
2188
2189        // If someone is watching installs - notify them
2190        if (installObserver != null) {
2191            try {
2192                Bundle extras = extrasForInstallResult(res);
2193                installObserver.onPackageInstalled(res.name, res.returnCode,
2194                        res.returnMsg, extras);
2195            } catch (RemoteException e) {
2196                Slog.i(TAG, "Observer no longer exists.");
2197            }
2198        }
2199    }
2200
2201    private StorageEventListener mStorageListener = new StorageEventListener() {
2202        @Override
2203        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2204            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2205                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2206                    final String volumeUuid = vol.getFsUuid();
2207
2208                    // Clean up any users or apps that were removed or recreated
2209                    // while this volume was missing
2210                    sUserManager.reconcileUsers(volumeUuid);
2211                    reconcileApps(volumeUuid);
2212
2213                    // Clean up any install sessions that expired or were
2214                    // cancelled while this volume was missing
2215                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2216
2217                    loadPrivatePackages(vol);
2218
2219                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2220                    unloadPrivatePackages(vol);
2221                }
2222            }
2223        }
2224
2225        @Override
2226        public void onVolumeForgotten(String fsUuid) {
2227            if (TextUtils.isEmpty(fsUuid)) {
2228                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2229                return;
2230            }
2231
2232            // Remove any apps installed on the forgotten volume
2233            synchronized (mPackages) {
2234                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2235                for (PackageSetting ps : packages) {
2236                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2237                    deletePackageVersioned(new VersionedPackage(ps.name,
2238                            PackageManager.VERSION_CODE_HIGHEST),
2239                            new LegacyPackageDeleteObserver(null).getBinder(),
2240                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2241                    // Try very hard to release any references to this package
2242                    // so we don't risk the system server being killed due to
2243                    // open FDs
2244                    AttributeCache.instance().removePackage(ps.name);
2245                }
2246
2247                mSettings.onVolumeForgotten(fsUuid);
2248                mSettings.writeLPr();
2249            }
2250        }
2251    };
2252
2253    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2254        Bundle extras = null;
2255        switch (res.returnCode) {
2256            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2257                extras = new Bundle();
2258                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2259                        res.origPermission);
2260                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2261                        res.origPackage);
2262                break;
2263            }
2264            case PackageManager.INSTALL_SUCCEEDED: {
2265                extras = new Bundle();
2266                extras.putBoolean(Intent.EXTRA_REPLACING,
2267                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2268                break;
2269            }
2270        }
2271        return extras;
2272    }
2273
2274    void scheduleWriteSettingsLocked() {
2275        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2276            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2277        }
2278    }
2279
2280    void scheduleWritePackageListLocked(int userId) {
2281        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2282            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2283            msg.arg1 = userId;
2284            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2285        }
2286    }
2287
2288    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2289        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2290        scheduleWritePackageRestrictionsLocked(userId);
2291    }
2292
2293    void scheduleWritePackageRestrictionsLocked(int userId) {
2294        final int[] userIds = (userId == UserHandle.USER_ALL)
2295                ? sUserManager.getUserIds() : new int[]{userId};
2296        for (int nextUserId : userIds) {
2297            if (!sUserManager.exists(nextUserId)) return;
2298            mDirtyUsers.add(nextUserId);
2299            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2300                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2301            }
2302        }
2303    }
2304
2305    public static PackageManagerService main(Context context, Installer installer,
2306            boolean factoryTest, boolean onlyCore) {
2307        // Self-check for initial settings.
2308        PackageManagerServiceCompilerMapping.checkProperties();
2309
2310        PackageManagerService m = new PackageManagerService(context, installer,
2311                factoryTest, onlyCore);
2312        m.enableSystemUserPackages();
2313        ServiceManager.addService("package", m);
2314        final PackageManagerNative pmn = m.new PackageManagerNative();
2315        ServiceManager.addService("package_native", pmn);
2316        return m;
2317    }
2318
2319    private void enableSystemUserPackages() {
2320        if (!UserManager.isSplitSystemUser()) {
2321            return;
2322        }
2323        // For system user, enable apps based on the following conditions:
2324        // - app is whitelisted or belong to one of these groups:
2325        //   -- system app which has no launcher icons
2326        //   -- system app which has INTERACT_ACROSS_USERS permission
2327        //   -- system IME app
2328        // - app is not in the blacklist
2329        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2330        Set<String> enableApps = new ArraySet<>();
2331        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2332                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2333                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2334        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2335        enableApps.addAll(wlApps);
2336        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2337                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2338        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2339        enableApps.removeAll(blApps);
2340        Log.i(TAG, "Applications installed for system user: " + enableApps);
2341        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2342                UserHandle.SYSTEM);
2343        final int allAppsSize = allAps.size();
2344        synchronized (mPackages) {
2345            for (int i = 0; i < allAppsSize; i++) {
2346                String pName = allAps.get(i);
2347                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2348                // Should not happen, but we shouldn't be failing if it does
2349                if (pkgSetting == null) {
2350                    continue;
2351                }
2352                boolean install = enableApps.contains(pName);
2353                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2354                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2355                            + " for system user");
2356                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2357                }
2358            }
2359            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2360        }
2361    }
2362
2363    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2364        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2365                Context.DISPLAY_SERVICE);
2366        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2367    }
2368
2369    /**
2370     * Requests that files preopted on a secondary system partition be copied to the data partition
2371     * if possible.  Note that the actual copying of the files is accomplished by init for security
2372     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2373     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2374     */
2375    private static void requestCopyPreoptedFiles() {
2376        final int WAIT_TIME_MS = 100;
2377        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2378        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2379            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2380            // We will wait for up to 100 seconds.
2381            final long timeStart = SystemClock.uptimeMillis();
2382            final long timeEnd = timeStart + 100 * 1000;
2383            long timeNow = timeStart;
2384            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2385                try {
2386                    Thread.sleep(WAIT_TIME_MS);
2387                } catch (InterruptedException e) {
2388                    // Do nothing
2389                }
2390                timeNow = SystemClock.uptimeMillis();
2391                if (timeNow > timeEnd) {
2392                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2393                    Slog.wtf(TAG, "cppreopt did not finish!");
2394                    break;
2395                }
2396            }
2397
2398            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2399        }
2400    }
2401
2402    public PackageManagerService(Context context, Installer installer,
2403            boolean factoryTest, boolean onlyCore) {
2404        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2405        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2406        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2407                SystemClock.uptimeMillis());
2408
2409        if (mSdkVersion <= 0) {
2410            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2411        }
2412
2413        mContext = context;
2414
2415        mFactoryTest = factoryTest;
2416        mOnlyCore = onlyCore;
2417        mMetrics = new DisplayMetrics();
2418        mInstaller = installer;
2419
2420        // Create sub-components that provide services / data. Order here is important.
2421        synchronized (mInstallLock) {
2422        synchronized (mPackages) {
2423            // Expose private service for system components to use.
2424            LocalServices.addService(
2425                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2426            sUserManager = new UserManagerService(context, this,
2427                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2428            mPermissionManager = PermissionManagerService.create(context,
2429                    new DefaultPermissionGrantedCallback() {
2430                        @Override
2431                        public void onDefaultRuntimePermissionsGranted(int userId) {
2432                            synchronized(mPackages) {
2433                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2434                            }
2435                        }
2436                    }, mPackages /*externalLock*/);
2437            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2438            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2439        }
2440        }
2441        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2442                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2443        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2444                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2445        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2446                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2447        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2448                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2449        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2450                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2451        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2452                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2453        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2454                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2455
2456        String separateProcesses = SystemProperties.get("debug.separate_processes");
2457        if (separateProcesses != null && separateProcesses.length() > 0) {
2458            if ("*".equals(separateProcesses)) {
2459                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2460                mSeparateProcesses = null;
2461                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2462            } else {
2463                mDefParseFlags = 0;
2464                mSeparateProcesses = separateProcesses.split(",");
2465                Slog.w(TAG, "Running with debug.separate_processes: "
2466                        + separateProcesses);
2467            }
2468        } else {
2469            mDefParseFlags = 0;
2470            mSeparateProcesses = null;
2471        }
2472
2473        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2474                "*dexopt*");
2475        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2476                installer, mInstallLock);
2477        mDexManager = new DexManager(mContext, this, mPackageDexOptimizer, installer, mInstallLock,
2478                dexManagerListener);
2479        mArtManagerService = new ArtManagerService(mContext, this, installer, mInstallLock);
2480        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2481
2482        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2483                FgThread.get().getLooper());
2484
2485        getDefaultDisplayMetrics(context, mMetrics);
2486
2487        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2488        SystemConfig systemConfig = SystemConfig.getInstance();
2489        mAvailableFeatures = systemConfig.getAvailableFeatures();
2490        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2491
2492        mProtectedPackages = new ProtectedPackages(mContext);
2493
2494        synchronized (mInstallLock) {
2495        // writer
2496        synchronized (mPackages) {
2497            mHandlerThread = new ServiceThread(TAG,
2498                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2499            mHandlerThread.start();
2500            mHandler = new PackageHandler(mHandlerThread.getLooper());
2501            mProcessLoggingHandler = new ProcessLoggingHandler();
2502            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2503            mInstantAppRegistry = new InstantAppRegistry(this);
2504
2505            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2506            final int builtInLibCount = libConfig.size();
2507            for (int i = 0; i < builtInLibCount; i++) {
2508                String name = libConfig.keyAt(i);
2509                String path = libConfig.valueAt(i);
2510                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2511                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2512            }
2513
2514            SELinuxMMAC.readInstallPolicy();
2515
2516            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2517            FallbackCategoryProvider.loadFallbacks();
2518            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2519
2520            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2521            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2522            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2523
2524            // Clean up orphaned packages for which the code path doesn't exist
2525            // and they are an update to a system app - caused by bug/32321269
2526            final int packageSettingCount = mSettings.mPackages.size();
2527            for (int i = packageSettingCount - 1; i >= 0; i--) {
2528                PackageSetting ps = mSettings.mPackages.valueAt(i);
2529                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2530                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2531                    mSettings.mPackages.removeAt(i);
2532                    mSettings.enableSystemPackageLPw(ps.name);
2533                }
2534            }
2535
2536            if (mFirstBoot) {
2537                requestCopyPreoptedFiles();
2538            }
2539
2540            String customResolverActivity = Resources.getSystem().getString(
2541                    R.string.config_customResolverActivity);
2542            if (TextUtils.isEmpty(customResolverActivity)) {
2543                customResolverActivity = null;
2544            } else {
2545                mCustomResolverComponentName = ComponentName.unflattenFromString(
2546                        customResolverActivity);
2547            }
2548
2549            long startTime = SystemClock.uptimeMillis();
2550
2551            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2552                    startTime);
2553
2554            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2555            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2556
2557            if (bootClassPath == null) {
2558                Slog.w(TAG, "No BOOTCLASSPATH found!");
2559            }
2560
2561            if (systemServerClassPath == null) {
2562                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2563            }
2564
2565            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2566
2567            final VersionInfo ver = mSettings.getInternalVersion();
2568            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2569            if (mIsUpgrade) {
2570                logCriticalInfo(Log.INFO,
2571                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2572            }
2573
2574            // when upgrading from pre-M, promote system app permissions from install to runtime
2575            mPromoteSystemApps =
2576                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2577
2578            // When upgrading from pre-N, we need to handle package extraction like first boot,
2579            // as there is no profiling data available.
2580            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2581
2582            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2583
2584            // save off the names of pre-existing system packages prior to scanning; we don't
2585            // want to automatically grant runtime permissions for new system apps
2586            if (mPromoteSystemApps) {
2587                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2588                while (pkgSettingIter.hasNext()) {
2589                    PackageSetting ps = pkgSettingIter.next();
2590                    if (isSystemApp(ps)) {
2591                        mExistingSystemPackages.add(ps.name);
2592                    }
2593                }
2594            }
2595
2596            mCacheDir = preparePackageParserCache(mIsUpgrade);
2597
2598            // Set flag to monitor and not change apk file paths when
2599            // scanning install directories.
2600            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2601
2602            if (mIsUpgrade || mFirstBoot) {
2603                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2604            }
2605
2606            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2607            // For security and version matching reason, only consider
2608            // overlay packages if they reside in the right directory.
2609            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2610                    mDefParseFlags
2611                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2612                    scanFlags
2613                    | SCAN_AS_SYSTEM
2614                    | SCAN_AS_VENDOR,
2615                    0);
2616            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2617                    mDefParseFlags
2618                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2619                    scanFlags
2620                    | SCAN_AS_SYSTEM
2621                    | SCAN_AS_PRODUCT,
2622                    0);
2623
2624            mParallelPackageParserCallback.findStaticOverlayPackages();
2625
2626            // Find base frameworks (resource packages without code).
2627            scanDirTracedLI(frameworkDir,
2628                    mDefParseFlags
2629                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2630                    scanFlags
2631                    | SCAN_NO_DEX
2632                    | SCAN_AS_SYSTEM
2633                    | SCAN_AS_PRIVILEGED,
2634                    0);
2635
2636            // Collect privileged system packages.
2637            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2638            scanDirTracedLI(privilegedAppDir,
2639                    mDefParseFlags
2640                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2641                    scanFlags
2642                    | SCAN_AS_SYSTEM
2643                    | SCAN_AS_PRIVILEGED,
2644                    0);
2645
2646            // Collect ordinary system packages.
2647            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2648            scanDirTracedLI(systemAppDir,
2649                    mDefParseFlags
2650                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2651                    scanFlags
2652                    | SCAN_AS_SYSTEM,
2653                    0);
2654
2655            // Collect privileged vendor packages.
2656            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2657            try {
2658                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2659            } catch (IOException e) {
2660                // failed to look up canonical path, continue with original one
2661            }
2662            scanDirTracedLI(privilegedVendorAppDir,
2663                    mDefParseFlags
2664                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2665                    scanFlags
2666                    | SCAN_AS_SYSTEM
2667                    | SCAN_AS_VENDOR
2668                    | SCAN_AS_PRIVILEGED,
2669                    0);
2670
2671            // Collect ordinary vendor packages.
2672            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2673            try {
2674                vendorAppDir = vendorAppDir.getCanonicalFile();
2675            } catch (IOException e) {
2676                // failed to look up canonical path, continue with original one
2677            }
2678            scanDirTracedLI(vendorAppDir,
2679                    mDefParseFlags
2680                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2681                    scanFlags
2682                    | SCAN_AS_SYSTEM
2683                    | SCAN_AS_VENDOR,
2684                    0);
2685
2686            // Collect privileged odm packages. /odm is another vendor partition
2687            // other than /vendor.
2688            File privilegedOdmAppDir = new File(Environment.getOdmDirectory(),
2689                        "priv-app");
2690            try {
2691                privilegedOdmAppDir = privilegedOdmAppDir.getCanonicalFile();
2692            } catch (IOException e) {
2693                // failed to look up canonical path, continue with original one
2694            }
2695            scanDirTracedLI(privilegedOdmAppDir,
2696                    mDefParseFlags
2697                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2698                    scanFlags
2699                    | SCAN_AS_SYSTEM
2700                    | SCAN_AS_VENDOR
2701                    | SCAN_AS_PRIVILEGED,
2702                    0);
2703
2704            // Collect ordinary odm packages. /odm is another vendor partition
2705            // other than /vendor.
2706            File odmAppDir = new File(Environment.getOdmDirectory(), "app");
2707            try {
2708                odmAppDir = odmAppDir.getCanonicalFile();
2709            } catch (IOException e) {
2710                // failed to look up canonical path, continue with original one
2711            }
2712            scanDirTracedLI(odmAppDir,
2713                    mDefParseFlags
2714                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2715                    scanFlags
2716                    | SCAN_AS_SYSTEM
2717                    | SCAN_AS_VENDOR,
2718                    0);
2719
2720            // Collect all OEM packages.
2721            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2722            scanDirTracedLI(oemAppDir,
2723                    mDefParseFlags
2724                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2725                    scanFlags
2726                    | SCAN_AS_SYSTEM
2727                    | SCAN_AS_OEM,
2728                    0);
2729
2730            // Collected privileged product packages.
2731            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2732            try {
2733                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2734            } catch (IOException e) {
2735                // failed to look up canonical path, continue with original one
2736            }
2737            scanDirTracedLI(privilegedProductAppDir,
2738                    mDefParseFlags
2739                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2740                    scanFlags
2741                    | SCAN_AS_SYSTEM
2742                    | SCAN_AS_PRODUCT
2743                    | SCAN_AS_PRIVILEGED,
2744                    0);
2745
2746            // Collect ordinary product packages.
2747            File productAppDir = new File(Environment.getProductDirectory(), "app");
2748            try {
2749                productAppDir = productAppDir.getCanonicalFile();
2750            } catch (IOException e) {
2751                // failed to look up canonical path, continue with original one
2752            }
2753            scanDirTracedLI(productAppDir,
2754                    mDefParseFlags
2755                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2756                    scanFlags
2757                    | SCAN_AS_SYSTEM
2758                    | SCAN_AS_PRODUCT,
2759                    0);
2760
2761            // Prune any system packages that no longer exist.
2762            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2763            // Stub packages must either be replaced with full versions in the /data
2764            // partition or be disabled.
2765            final List<String> stubSystemApps = new ArrayList<>();
2766            if (!mOnlyCore) {
2767                // do this first before mucking with mPackages for the "expecting better" case
2768                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2769                while (pkgIterator.hasNext()) {
2770                    final PackageParser.Package pkg = pkgIterator.next();
2771                    if (pkg.isStub) {
2772                        stubSystemApps.add(pkg.packageName);
2773                    }
2774                }
2775
2776                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2777                while (psit.hasNext()) {
2778                    PackageSetting ps = psit.next();
2779
2780                    /*
2781                     * If this is not a system app, it can't be a
2782                     * disable system app.
2783                     */
2784                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2785                        continue;
2786                    }
2787
2788                    /*
2789                     * If the package is scanned, it's not erased.
2790                     */
2791                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2792                    if (scannedPkg != null) {
2793                        /*
2794                         * If the system app is both scanned and in the
2795                         * disabled packages list, then it must have been
2796                         * added via OTA. Remove it from the currently
2797                         * scanned package so the previously user-installed
2798                         * application can be scanned.
2799                         */
2800                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2801                            logCriticalInfo(Log.WARN,
2802                                    "Expecting better updated system app for " + ps.name
2803                                    + "; removing system app.  Last known"
2804                                    + " codePath=" + ps.codePathString
2805                                    + ", versionCode=" + ps.versionCode
2806                                    + "; scanned versionCode=" + scannedPkg.getLongVersionCode());
2807                            removePackageLI(scannedPkg, true);
2808                            mExpectingBetter.put(ps.name, ps.codePath);
2809                        }
2810
2811                        continue;
2812                    }
2813
2814                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2815                        psit.remove();
2816                        logCriticalInfo(Log.WARN, "System package " + ps.name
2817                                + " no longer exists; it's data will be wiped");
2818                        // Actual deletion of code and data will be handled by later
2819                        // reconciliation step
2820                    } else {
2821                        // we still have a disabled system package, but, it still might have
2822                        // been removed. check the code path still exists and check there's
2823                        // still a package. the latter can happen if an OTA keeps the same
2824                        // code path, but, changes the package name.
2825                        final PackageSetting disabledPs =
2826                                mSettings.getDisabledSystemPkgLPr(ps.name);
2827                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2828                                || disabledPs.pkg == null) {
2829                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2830                        }
2831                    }
2832                }
2833            }
2834
2835            //delete tmp files
2836            deleteTempPackageFiles();
2837
2838            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2839
2840            // Remove any shared userIDs that have no associated packages
2841            mSettings.pruneSharedUsersLPw();
2842            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2843            final int systemPackagesCount = mPackages.size();
2844            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2845                    + " ms, packageCount: " + systemPackagesCount
2846                    + " , timePerPackage: "
2847                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2848                    + " , cached: " + cachedSystemApps);
2849            if (mIsUpgrade && systemPackagesCount > 0) {
2850                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2851                        ((int) systemScanTime) / systemPackagesCount);
2852            }
2853            if (!mOnlyCore) {
2854                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2855                        SystemClock.uptimeMillis());
2856                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2857
2858                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2859                        | PackageParser.PARSE_FORWARD_LOCK,
2860                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2861
2862                // Remove disable package settings for updated system apps that were
2863                // removed via an OTA. If the update is no longer present, remove the
2864                // app completely. Otherwise, revoke their system privileges.
2865                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2866                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2867                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2868                    final String msg;
2869                    if (deletedPkg == null) {
2870                        // should have found an update, but, we didn't; remove everything
2871                        msg = "Updated system package " + deletedAppName
2872                                + " no longer exists; removing its data";
2873                        // Actual deletion of code and data will be handled by later
2874                        // reconciliation step
2875                    } else {
2876                        // found an update; revoke system privileges
2877                        msg = "Updated system package + " + deletedAppName
2878                                + " no longer exists; revoking system privileges";
2879
2880                        // Don't do anything if a stub is removed from the system image. If
2881                        // we were to remove the uncompressed version from the /data partition,
2882                        // this is where it'd be done.
2883
2884                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2885                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2886                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2887                    }
2888                    logCriticalInfo(Log.WARN, msg);
2889                }
2890
2891                /*
2892                 * Make sure all system apps that we expected to appear on
2893                 * the userdata partition actually showed up. If they never
2894                 * appeared, crawl back and revive the system version.
2895                 */
2896                for (int i = 0; i < mExpectingBetter.size(); i++) {
2897                    final String packageName = mExpectingBetter.keyAt(i);
2898                    if (!mPackages.containsKey(packageName)) {
2899                        final File scanFile = mExpectingBetter.valueAt(i);
2900
2901                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2902                                + " but never showed up; reverting to system");
2903
2904                        final @ParseFlags int reparseFlags;
2905                        final @ScanFlags int rescanFlags;
2906                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2907                            reparseFlags =
2908                                    mDefParseFlags |
2909                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2910                            rescanFlags =
2911                                    scanFlags
2912                                    | SCAN_AS_SYSTEM
2913                                    | SCAN_AS_PRIVILEGED;
2914                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2915                            reparseFlags =
2916                                    mDefParseFlags |
2917                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2918                            rescanFlags =
2919                                    scanFlags
2920                                    | SCAN_AS_SYSTEM;
2921                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)
2922                                || FileUtils.contains(privilegedOdmAppDir, scanFile)) {
2923                            reparseFlags =
2924                                    mDefParseFlags |
2925                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2926                            rescanFlags =
2927                                    scanFlags
2928                                    | SCAN_AS_SYSTEM
2929                                    | SCAN_AS_VENDOR
2930                                    | SCAN_AS_PRIVILEGED;
2931                        } else if (FileUtils.contains(vendorAppDir, scanFile)
2932                                || FileUtils.contains(odmAppDir, scanFile)) {
2933                            reparseFlags =
2934                                    mDefParseFlags |
2935                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2936                            rescanFlags =
2937                                    scanFlags
2938                                    | SCAN_AS_SYSTEM
2939                                    | SCAN_AS_VENDOR;
2940                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2941                            reparseFlags =
2942                                    mDefParseFlags |
2943                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2944                            rescanFlags =
2945                                    scanFlags
2946                                    | SCAN_AS_SYSTEM
2947                                    | SCAN_AS_OEM;
2948                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2949                            reparseFlags =
2950                                    mDefParseFlags |
2951                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2952                            rescanFlags =
2953                                    scanFlags
2954                                    | SCAN_AS_SYSTEM
2955                                    | SCAN_AS_PRODUCT
2956                                    | SCAN_AS_PRIVILEGED;
2957                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2958                            reparseFlags =
2959                                    mDefParseFlags |
2960                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2961                            rescanFlags =
2962                                    scanFlags
2963                                    | SCAN_AS_SYSTEM
2964                                    | SCAN_AS_PRODUCT;
2965                        } else {
2966                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2967                            continue;
2968                        }
2969
2970                        mSettings.enableSystemPackageLPw(packageName);
2971
2972                        try {
2973                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2974                        } catch (PackageManagerException e) {
2975                            Slog.e(TAG, "Failed to parse original system package: "
2976                                    + e.getMessage());
2977                        }
2978                    }
2979                }
2980
2981                // Uncompress and install any stubbed system applications.
2982                // This must be done last to ensure all stubs are replaced or disabled.
2983                decompressSystemApplications(stubSystemApps, scanFlags);
2984
2985                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2986                                - cachedSystemApps;
2987
2988                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2989                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2990                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2991                        + " ms, packageCount: " + dataPackagesCount
2992                        + " , timePerPackage: "
2993                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2994                        + " , cached: " + cachedNonSystemApps);
2995                if (mIsUpgrade && dataPackagesCount > 0) {
2996                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2997                            ((int) dataScanTime) / dataPackagesCount);
2998                }
2999            }
3000            mExpectingBetter.clear();
3001
3002            // Resolve the storage manager.
3003            mStorageManagerPackage = getStorageManagerPackageName();
3004
3005            // Resolve protected action filters. Only the setup wizard is allowed to
3006            // have a high priority filter for these actions.
3007            mSetupWizardPackage = getSetupWizardPackageName();
3008            if (mProtectedFilters.size() > 0) {
3009                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
3010                    Slog.i(TAG, "No setup wizard;"
3011                        + " All protected intents capped to priority 0");
3012                }
3013                for (ActivityIntentInfo filter : mProtectedFilters) {
3014                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
3015                        if (DEBUG_FILTERS) {
3016                            Slog.i(TAG, "Found setup wizard;"
3017                                + " allow priority " + filter.getPriority() + ";"
3018                                + " package: " + filter.activity.info.packageName
3019                                + " activity: " + filter.activity.className
3020                                + " priority: " + filter.getPriority());
3021                        }
3022                        // skip setup wizard; allow it to keep the high priority filter
3023                        continue;
3024                    }
3025                    if (DEBUG_FILTERS) {
3026                        Slog.i(TAG, "Protected action; cap priority to 0;"
3027                                + " package: " + filter.activity.info.packageName
3028                                + " activity: " + filter.activity.className
3029                                + " origPrio: " + filter.getPriority());
3030                    }
3031                    filter.setPriority(0);
3032                }
3033            }
3034
3035            mSystemTextClassifierPackage = getSystemTextClassifierPackageName();
3036
3037            mDeferProtectedFilters = false;
3038            mProtectedFilters.clear();
3039
3040            // Now that we know all of the shared libraries, update all clients to have
3041            // the correct library paths.
3042            updateAllSharedLibrariesLPw(null);
3043
3044            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
3045                // NOTE: We ignore potential failures here during a system scan (like
3046                // the rest of the commands above) because there's precious little we
3047                // can do about it. A settings error is reported, though.
3048                final List<String> changedAbiCodePath =
3049                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
3050                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
3051                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
3052                        final String codePathString = changedAbiCodePath.get(i);
3053                        try {
3054                            mInstaller.rmdex(codePathString,
3055                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
3056                        } catch (InstallerException ignored) {
3057                        }
3058                    }
3059                }
3060                // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same
3061                // SELinux domain.
3062                setting.fixSeInfoLocked();
3063            }
3064
3065            // Now that we know all the packages we are keeping,
3066            // read and update their last usage times.
3067            mPackageUsage.read(mPackages);
3068            mCompilerStats.read();
3069
3070            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
3071                    SystemClock.uptimeMillis());
3072            Slog.i(TAG, "Time to scan packages: "
3073                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
3074                    + " seconds");
3075
3076            // If the platform SDK has changed since the last time we booted,
3077            // we need to re-grant app permission to catch any new ones that
3078            // appear.  This is really a hack, and means that apps can in some
3079            // cases get permissions that the user didn't initially explicitly
3080            // allow...  it would be nice to have some better way to handle
3081            // this situation.
3082            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3083            if (sdkUpdated) {
3084                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3085                        + mSdkVersion + "; regranting permissions for internal storage");
3086            }
3087            mPermissionManager.updateAllPermissions(
3088                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3089                    mPermissionCallback);
3090            ver.sdkVersion = mSdkVersion;
3091
3092            // If this is the first boot or an update from pre-M, and it is a normal
3093            // boot, then we need to initialize the default preferred apps across
3094            // all defined users.
3095            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3096                for (UserInfo user : sUserManager.getUsers(true)) {
3097                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3098                    applyFactoryDefaultBrowserLPw(user.id);
3099                    primeDomainVerificationsLPw(user.id);
3100                }
3101            }
3102
3103            // Prepare storage for system user really early during boot,
3104            // since core system apps like SettingsProvider and SystemUI
3105            // can't wait for user to start
3106            final int storageFlags;
3107            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3108                storageFlags = StorageManager.FLAG_STORAGE_DE;
3109            } else {
3110                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3111            }
3112            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3113                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3114                    true /* onlyCoreApps */);
3115            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3116                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3117                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3118                traceLog.traceBegin("AppDataFixup");
3119                try {
3120                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3121                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3122                } catch (InstallerException e) {
3123                    Slog.w(TAG, "Trouble fixing GIDs", e);
3124                }
3125                traceLog.traceEnd();
3126
3127                traceLog.traceBegin("AppDataPrepare");
3128                if (deferPackages == null || deferPackages.isEmpty()) {
3129                    return;
3130                }
3131                int count = 0;
3132                for (String pkgName : deferPackages) {
3133                    PackageParser.Package pkg = null;
3134                    synchronized (mPackages) {
3135                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3136                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3137                            pkg = ps.pkg;
3138                        }
3139                    }
3140                    if (pkg != null) {
3141                        synchronized (mInstallLock) {
3142                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3143                                    true /* maybeMigrateAppData */);
3144                        }
3145                        count++;
3146                    }
3147                }
3148                traceLog.traceEnd();
3149                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3150            }, "prepareAppData");
3151
3152            // If this is first boot after an OTA, and a normal boot, then
3153            // we need to clear code cache directories.
3154            // Note that we do *not* clear the application profiles. These remain valid
3155            // across OTAs and are used to drive profile verification (post OTA) and
3156            // profile compilation (without waiting to collect a fresh set of profiles).
3157            if (mIsUpgrade && !onlyCore) {
3158                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3159                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3160                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3161                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3162                        // No apps are running this early, so no need to freeze
3163                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3164                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3165                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3166                    }
3167                }
3168                ver.fingerprint = Build.FINGERPRINT;
3169            }
3170
3171            checkDefaultBrowser();
3172
3173            // clear only after permissions and other defaults have been updated
3174            mExistingSystemPackages.clear();
3175            mPromoteSystemApps = false;
3176
3177            // All the changes are done during package scanning.
3178            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3179
3180            // can downgrade to reader
3181            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3182            mSettings.writeLPr();
3183            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3184            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3185                    SystemClock.uptimeMillis());
3186
3187            if (!mOnlyCore) {
3188                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3189                mRequiredInstallerPackage = getRequiredInstallerLPr();
3190                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3191                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3192                if (mIntentFilterVerifierComponent != null) {
3193                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3194                            mIntentFilterVerifierComponent);
3195                } else {
3196                    mIntentFilterVerifier = null;
3197                }
3198                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3199                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3200                        SharedLibraryInfo.VERSION_UNDEFINED);
3201                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3202                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3203                        SharedLibraryInfo.VERSION_UNDEFINED);
3204            } else {
3205                mRequiredVerifierPackage = null;
3206                mRequiredInstallerPackage = null;
3207                mRequiredUninstallerPackage = null;
3208                mIntentFilterVerifierComponent = null;
3209                mIntentFilterVerifier = null;
3210                mServicesSystemSharedLibraryPackageName = null;
3211                mSharedSystemSharedLibraryPackageName = null;
3212            }
3213
3214            mInstallerService = new PackageInstallerService(context, this);
3215            final Pair<ComponentName, String> instantAppResolverComponent =
3216                    getInstantAppResolverLPr();
3217            if (instantAppResolverComponent != null) {
3218                if (DEBUG_INSTANT) {
3219                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3220                }
3221                mInstantAppResolverConnection = new InstantAppResolverConnection(
3222                        mContext, instantAppResolverComponent.first,
3223                        instantAppResolverComponent.second);
3224                mInstantAppResolverSettingsComponent =
3225                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3226            } else {
3227                mInstantAppResolverConnection = null;
3228                mInstantAppResolverSettingsComponent = null;
3229            }
3230            updateInstantAppInstallerLocked(null);
3231
3232            // Read and update the usage of dex files.
3233            // Do this at the end of PM init so that all the packages have their
3234            // data directory reconciled.
3235            // At this point we know the code paths of the packages, so we can validate
3236            // the disk file and build the internal cache.
3237            // The usage file is expected to be small so loading and verifying it
3238            // should take a fairly small time compare to the other activities (e.g. package
3239            // scanning).
3240            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3241            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3242            for (int userId : currentUserIds) {
3243                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3244            }
3245            mDexManager.load(userPackages);
3246            if (mIsUpgrade) {
3247                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3248                        (int) (SystemClock.uptimeMillis() - startTime));
3249            }
3250        } // synchronized (mPackages)
3251        } // synchronized (mInstallLock)
3252
3253        // Now after opening every single application zip, make sure they
3254        // are all flushed.  Not really needed, but keeps things nice and
3255        // tidy.
3256        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3257        Runtime.getRuntime().gc();
3258        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3259
3260        // The initial scanning above does many calls into installd while
3261        // holding the mPackages lock, but we're mostly interested in yelling
3262        // once we have a booted system.
3263        mInstaller.setWarnIfHeld(mPackages);
3264
3265        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3266    }
3267
3268    /**
3269     * Uncompress and install stub applications.
3270     * <p>In order to save space on the system partition, some applications are shipped in a
3271     * compressed form. In addition the compressed bits for the full application, the
3272     * system image contains a tiny stub comprised of only the Android manifest.
3273     * <p>During the first boot, attempt to uncompress and install the full application. If
3274     * the application can't be installed for any reason, disable the stub and prevent
3275     * uncompressing the full application during future boots.
3276     * <p>In order to forcefully attempt an installation of a full application, go to app
3277     * settings and enable the application.
3278     */
3279    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3280        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3281            final String pkgName = stubSystemApps.get(i);
3282            // skip if the system package is already disabled
3283            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3284                stubSystemApps.remove(i);
3285                continue;
3286            }
3287            // skip if the package isn't installed (?!); this should never happen
3288            final PackageParser.Package pkg = mPackages.get(pkgName);
3289            if (pkg == null) {
3290                stubSystemApps.remove(i);
3291                continue;
3292            }
3293            // skip if the package has been disabled by the user
3294            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3295            if (ps != null) {
3296                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3297                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3298                    stubSystemApps.remove(i);
3299                    continue;
3300                }
3301            }
3302
3303            if (DEBUG_COMPRESSION) {
3304                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3305            }
3306
3307            // uncompress the binary to its eventual destination on /data
3308            final File scanFile = decompressPackage(pkg);
3309            if (scanFile == null) {
3310                continue;
3311            }
3312
3313            // install the package to replace the stub on /system
3314            try {
3315                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3316                removePackageLI(pkg, true /*chatty*/);
3317                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3318                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3319                        UserHandle.USER_SYSTEM, "android");
3320                stubSystemApps.remove(i);
3321                continue;
3322            } catch (PackageManagerException e) {
3323                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3324            }
3325
3326            // any failed attempt to install the package will be cleaned up later
3327        }
3328
3329        // disable any stub still left; these failed to install the full application
3330        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3331            final String pkgName = stubSystemApps.get(i);
3332            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3333            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3334                    UserHandle.USER_SYSTEM, "android");
3335            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3336        }
3337    }
3338
3339    /**
3340     * Decompresses the given package on the system image onto
3341     * the /data partition.
3342     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3343     */
3344    private File decompressPackage(PackageParser.Package pkg) {
3345        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3346        if (compressedFiles == null || compressedFiles.length == 0) {
3347            if (DEBUG_COMPRESSION) {
3348                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3349            }
3350            return null;
3351        }
3352        final File dstCodePath =
3353                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3354        int ret = PackageManager.INSTALL_SUCCEEDED;
3355        try {
3356            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3357            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3358            for (File srcFile : compressedFiles) {
3359                final String srcFileName = srcFile.getName();
3360                final String dstFileName = srcFileName.substring(
3361                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3362                final File dstFile = new File(dstCodePath, dstFileName);
3363                ret = decompressFile(srcFile, dstFile);
3364                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3365                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3366                            + "; pkg: " + pkg.packageName
3367                            + ", file: " + dstFileName);
3368                    break;
3369                }
3370            }
3371        } catch (ErrnoException e) {
3372            logCriticalInfo(Log.ERROR, "Failed to decompress"
3373                    + "; pkg: " + pkg.packageName
3374                    + ", err: " + e.errno);
3375        }
3376        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3377            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3378            NativeLibraryHelper.Handle handle = null;
3379            try {
3380                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3381                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3382                        null /*abiOverride*/);
3383            } catch (IOException e) {
3384                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3385                        + "; pkg: " + pkg.packageName);
3386                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3387            } finally {
3388                IoUtils.closeQuietly(handle);
3389            }
3390        }
3391        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3392            if (dstCodePath == null || !dstCodePath.exists()) {
3393                return null;
3394            }
3395            removeCodePathLI(dstCodePath);
3396            return null;
3397        }
3398
3399        return dstCodePath;
3400    }
3401
3402    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3403        // we're only interested in updating the installer appliction when 1) it's not
3404        // already set or 2) the modified package is the installer
3405        if (mInstantAppInstallerActivity != null
3406                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3407                        .equals(modifiedPackage)) {
3408            return;
3409        }
3410        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3411    }
3412
3413    private static File preparePackageParserCache(boolean isUpgrade) {
3414        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3415            return null;
3416        }
3417
3418        // Disable package parsing on eng builds to allow for faster incremental development.
3419        if (Build.IS_ENG) {
3420            return null;
3421        }
3422
3423        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3424            Slog.i(TAG, "Disabling package parser cache due to system property.");
3425            return null;
3426        }
3427
3428        // The base directory for the package parser cache lives under /data/system/.
3429        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3430                "package_cache");
3431        if (cacheBaseDir == null) {
3432            return null;
3433        }
3434
3435        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3436        // This also serves to "GC" unused entries when the package cache version changes (which
3437        // can only happen during upgrades).
3438        if (isUpgrade) {
3439            FileUtils.deleteContents(cacheBaseDir);
3440        }
3441
3442
3443        // Return the versioned package cache directory. This is something like
3444        // "/data/system/package_cache/1"
3445        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3446
3447        if (cacheDir == null) {
3448            // Something went wrong. Attempt to delete everything and return.
3449            Slog.wtf(TAG, "Cache directory cannot be created - wiping base dir " + cacheBaseDir);
3450            FileUtils.deleteContentsAndDir(cacheBaseDir);
3451            return null;
3452        }
3453
3454        // The following is a workaround to aid development on non-numbered userdebug
3455        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3456        // the system partition is newer.
3457        //
3458        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3459        // that starts with "eng." to signify that this is an engineering build and not
3460        // destined for release.
3461        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3462            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3463
3464            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3465            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3466            // in general and should not be used for production changes. In this specific case,
3467            // we know that they will work.
3468            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3469            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3470                FileUtils.deleteContents(cacheBaseDir);
3471                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3472            }
3473        }
3474
3475        return cacheDir;
3476    }
3477
3478    @Override
3479    public boolean isFirstBoot() {
3480        // allow instant applications
3481        return mFirstBoot;
3482    }
3483
3484    @Override
3485    public boolean isOnlyCoreApps() {
3486        // allow instant applications
3487        return mOnlyCore;
3488    }
3489
3490    @Override
3491    public boolean isUpgrade() {
3492        // allow instant applications
3493        // The system property allows testing ota flow when upgraded to the same image.
3494        return mIsUpgrade || SystemProperties.getBoolean(
3495                "persist.pm.mock-upgrade", false /* default */);
3496    }
3497
3498    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3499        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3500
3501        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3502                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3503                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3504        if (matches.size() == 1) {
3505            return matches.get(0).getComponentInfo().packageName;
3506        } else if (matches.size() == 0) {
3507            Log.e(TAG, "There should probably be a verifier, but, none were found");
3508            return null;
3509        }
3510        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3511    }
3512
3513    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3514        synchronized (mPackages) {
3515            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3516            if (libraryEntry == null) {
3517                throw new IllegalStateException("Missing required shared library:" + name);
3518            }
3519            return libraryEntry.apk;
3520        }
3521    }
3522
3523    private @NonNull String getRequiredInstallerLPr() {
3524        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3525        intent.addCategory(Intent.CATEGORY_DEFAULT);
3526        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3527
3528        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3529                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3530                UserHandle.USER_SYSTEM);
3531        if (matches.size() == 1) {
3532            ResolveInfo resolveInfo = matches.get(0);
3533            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3534                throw new RuntimeException("The installer must be a privileged app");
3535            }
3536            return matches.get(0).getComponentInfo().packageName;
3537        } else {
3538            throw new RuntimeException("There must be exactly one installer; found " + matches);
3539        }
3540    }
3541
3542    private @NonNull String getRequiredUninstallerLPr() {
3543        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3544        intent.addCategory(Intent.CATEGORY_DEFAULT);
3545        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3546
3547        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3548                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3549                UserHandle.USER_SYSTEM);
3550        if (resolveInfo == null ||
3551                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3552            throw new RuntimeException("There must be exactly one uninstaller; found "
3553                    + resolveInfo);
3554        }
3555        return resolveInfo.getComponentInfo().packageName;
3556    }
3557
3558    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3559        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3560
3561        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3562                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3563                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3564        ResolveInfo best = null;
3565        final int N = matches.size();
3566        for (int i = 0; i < N; i++) {
3567            final ResolveInfo cur = matches.get(i);
3568            final String packageName = cur.getComponentInfo().packageName;
3569            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3570                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3571                continue;
3572            }
3573
3574            if (best == null || cur.priority > best.priority) {
3575                best = cur;
3576            }
3577        }
3578
3579        if (best != null) {
3580            return best.getComponentInfo().getComponentName();
3581        }
3582        Slog.w(TAG, "Intent filter verifier not found");
3583        return null;
3584    }
3585
3586    @Override
3587    public @Nullable ComponentName getInstantAppResolverComponent() {
3588        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3589            return null;
3590        }
3591        synchronized (mPackages) {
3592            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3593            if (instantAppResolver == null) {
3594                return null;
3595            }
3596            return instantAppResolver.first;
3597        }
3598    }
3599
3600    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3601        final String[] packageArray =
3602                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3603        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3604            if (DEBUG_INSTANT) {
3605                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3606            }
3607            return null;
3608        }
3609
3610        final int callingUid = Binder.getCallingUid();
3611        final int resolveFlags =
3612                MATCH_DIRECT_BOOT_AWARE
3613                | MATCH_DIRECT_BOOT_UNAWARE
3614                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3615        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3616        final Intent resolverIntent = new Intent(actionName);
3617        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3618                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3619        final int N = resolvers.size();
3620        if (N == 0) {
3621            if (DEBUG_INSTANT) {
3622                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3623            }
3624            return null;
3625        }
3626
3627        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3628        for (int i = 0; i < N; i++) {
3629            final ResolveInfo info = resolvers.get(i);
3630
3631            if (info.serviceInfo == null) {
3632                continue;
3633            }
3634
3635            final String packageName = info.serviceInfo.packageName;
3636            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3637                if (DEBUG_INSTANT) {
3638                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3639                            + " pkg: " + packageName + ", info:" + info);
3640                }
3641                continue;
3642            }
3643
3644            if (DEBUG_INSTANT) {
3645                Slog.v(TAG, "Ephemeral resolver found;"
3646                        + " pkg: " + packageName + ", info:" + info);
3647            }
3648            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3649        }
3650        if (DEBUG_INSTANT) {
3651            Slog.v(TAG, "Ephemeral resolver NOT found");
3652        }
3653        return null;
3654    }
3655
3656    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3657        String[] orderedActions = Build.IS_ENG
3658                ? new String[]{
3659                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3660                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3661                : new String[]{
3662                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3663
3664        final int resolveFlags =
3665                MATCH_DIRECT_BOOT_AWARE
3666                        | MATCH_DIRECT_BOOT_UNAWARE
3667                        | Intent.FLAG_IGNORE_EPHEMERAL
3668                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3669        final Intent intent = new Intent();
3670        intent.addCategory(Intent.CATEGORY_DEFAULT);
3671        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3672        List<ResolveInfo> matches = null;
3673        for (String action : orderedActions) {
3674            intent.setAction(action);
3675            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3676                    resolveFlags, UserHandle.USER_SYSTEM);
3677            if (matches.isEmpty()) {
3678                if (DEBUG_INSTANT) {
3679                    Slog.d(TAG, "Instant App installer not found with " + action);
3680                }
3681            } else {
3682                break;
3683            }
3684        }
3685        Iterator<ResolveInfo> iter = matches.iterator();
3686        while (iter.hasNext()) {
3687            final ResolveInfo rInfo = iter.next();
3688            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3689            if (ps != null) {
3690                final PermissionsState permissionsState = ps.getPermissionsState();
3691                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3692                        || Build.IS_ENG) {
3693                    continue;
3694                }
3695            }
3696            iter.remove();
3697        }
3698        if (matches.size() == 0) {
3699            return null;
3700        } else if (matches.size() == 1) {
3701            return (ActivityInfo) matches.get(0).getComponentInfo();
3702        } else {
3703            throw new RuntimeException(
3704                    "There must be at most one ephemeral installer; found " + matches);
3705        }
3706    }
3707
3708    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3709            @NonNull ComponentName resolver) {
3710        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3711                .addCategory(Intent.CATEGORY_DEFAULT)
3712                .setPackage(resolver.getPackageName());
3713        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3714        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3715                UserHandle.USER_SYSTEM);
3716        if (matches.isEmpty()) {
3717            return null;
3718        }
3719        return matches.get(0).getComponentInfo().getComponentName();
3720    }
3721
3722    private void primeDomainVerificationsLPw(int userId) {
3723        if (DEBUG_DOMAIN_VERIFICATION) {
3724            Slog.d(TAG, "Priming domain verifications in user " + userId);
3725        }
3726
3727        SystemConfig systemConfig = SystemConfig.getInstance();
3728        ArraySet<String> packages = systemConfig.getLinkedApps();
3729
3730        for (String packageName : packages) {
3731            PackageParser.Package pkg = mPackages.get(packageName);
3732            if (pkg != null) {
3733                if (!pkg.isSystem()) {
3734                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3735                    continue;
3736                }
3737
3738                ArraySet<String> domains = null;
3739                for (PackageParser.Activity a : pkg.activities) {
3740                    for (ActivityIntentInfo filter : a.intents) {
3741                        if (hasValidDomains(filter)) {
3742                            if (domains == null) {
3743                                domains = new ArraySet<String>();
3744                            }
3745                            domains.addAll(filter.getHostsList());
3746                        }
3747                    }
3748                }
3749
3750                if (domains != null && domains.size() > 0) {
3751                    if (DEBUG_DOMAIN_VERIFICATION) {
3752                        Slog.v(TAG, "      + " + packageName);
3753                    }
3754                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3755                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3756                    // and then 'always' in the per-user state actually used for intent resolution.
3757                    final IntentFilterVerificationInfo ivi;
3758                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3759                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3760                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3761                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3762                } else {
3763                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3764                            + "' does not handle web links");
3765                }
3766            } else {
3767                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3768            }
3769        }
3770
3771        scheduleWritePackageRestrictionsLocked(userId);
3772        scheduleWriteSettingsLocked();
3773    }
3774
3775    private void applyFactoryDefaultBrowserLPw(int userId) {
3776        // The default browser app's package name is stored in a string resource,
3777        // with a product-specific overlay used for vendor customization.
3778        String browserPkg = mContext.getResources().getString(
3779                com.android.internal.R.string.default_browser);
3780        if (!TextUtils.isEmpty(browserPkg)) {
3781            // non-empty string => required to be a known package
3782            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3783            if (ps == null) {
3784                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3785                browserPkg = null;
3786            } else {
3787                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3788            }
3789        }
3790
3791        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3792        // default.  If there's more than one, just leave everything alone.
3793        if (browserPkg == null) {
3794            calculateDefaultBrowserLPw(userId);
3795        }
3796    }
3797
3798    private void calculateDefaultBrowserLPw(int userId) {
3799        List<String> allBrowsers = resolveAllBrowserApps(userId);
3800        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3801        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3802    }
3803
3804    private List<String> resolveAllBrowserApps(int userId) {
3805        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3806        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3807                PackageManager.MATCH_ALL, userId);
3808
3809        final int count = list.size();
3810        List<String> result = new ArrayList<String>(count);
3811        for (int i=0; i<count; i++) {
3812            ResolveInfo info = list.get(i);
3813            if (info.activityInfo == null
3814                    || !info.handleAllWebDataURI
3815                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3816                    || result.contains(info.activityInfo.packageName)) {
3817                continue;
3818            }
3819            result.add(info.activityInfo.packageName);
3820        }
3821
3822        return result;
3823    }
3824
3825    private boolean packageIsBrowser(String packageName, int userId) {
3826        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3827                PackageManager.MATCH_ALL, userId);
3828        final int N = list.size();
3829        for (int i = 0; i < N; i++) {
3830            ResolveInfo info = list.get(i);
3831            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3832                return true;
3833            }
3834        }
3835        return false;
3836    }
3837
3838    private void checkDefaultBrowser() {
3839        final int myUserId = UserHandle.myUserId();
3840        final String packageName = getDefaultBrowserPackageName(myUserId);
3841        if (packageName != null) {
3842            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3843            if (info == null) {
3844                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3845                synchronized (mPackages) {
3846                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3847                }
3848            }
3849        }
3850    }
3851
3852    @Override
3853    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3854            throws RemoteException {
3855        try {
3856            return super.onTransact(code, data, reply, flags);
3857        } catch (RuntimeException e) {
3858            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3859                Slog.wtf(TAG, "Package Manager Crash", e);
3860            }
3861            throw e;
3862        }
3863    }
3864
3865    static int[] appendInts(int[] cur, int[] add) {
3866        if (add == null) return cur;
3867        if (cur == null) return add;
3868        final int N = add.length;
3869        for (int i=0; i<N; i++) {
3870            cur = appendInt(cur, add[i]);
3871        }
3872        return cur;
3873    }
3874
3875    /**
3876     * Returns whether or not a full application can see an instant application.
3877     * <p>
3878     * Currently, there are three cases in which this can occur:
3879     * <ol>
3880     * <li>The calling application is a "special" process. Special processes
3881     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3882     * <li>The calling application has the permission
3883     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3884     * <li>The calling application is the default launcher on the
3885     *     system partition.</li>
3886     * </ol>
3887     */
3888    private boolean canViewInstantApps(int callingUid, int userId) {
3889        if (callingUid < Process.FIRST_APPLICATION_UID) {
3890            return true;
3891        }
3892        if (mContext.checkCallingOrSelfPermission(
3893                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3894            return true;
3895        }
3896        if (mContext.checkCallingOrSelfPermission(
3897                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3898            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3899            if (homeComponent != null
3900                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3901                return true;
3902            }
3903        }
3904        return false;
3905    }
3906
3907    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3908        if (!sUserManager.exists(userId)) return null;
3909        if (ps == null) {
3910            return null;
3911        }
3912        final int callingUid = Binder.getCallingUid();
3913        // Filter out ephemeral app metadata:
3914        //   * The system/shell/root can see metadata for any app
3915        //   * An installed app can see metadata for 1) other installed apps
3916        //     and 2) ephemeral apps that have explicitly interacted with it
3917        //   * Ephemeral apps can only see their own data and exposed installed apps
3918        //   * Holding a signature permission allows seeing instant apps
3919        if (filterAppAccessLPr(ps, callingUid, userId)) {
3920            return null;
3921        }
3922
3923        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3924                && ps.isSystem()) {
3925            flags |= MATCH_ANY_USER;
3926        }
3927
3928        final PackageUserState state = ps.readUserState(userId);
3929        PackageParser.Package p = ps.pkg;
3930        if (p != null) {
3931            final PermissionsState permissionsState = ps.getPermissionsState();
3932
3933            // Compute GIDs only if requested
3934            final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3935                    ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3936            // Compute granted permissions only if package has requested permissions
3937            final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3938                    ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3939
3940            PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3941                    ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3942
3943            if (packageInfo == null) {
3944                return null;
3945            }
3946
3947            packageInfo.packageName = packageInfo.applicationInfo.packageName =
3948                    resolveExternalPackageNameLPr(p);
3949
3950            return packageInfo;
3951        } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
3952            PackageInfo pi = new PackageInfo();
3953            pi.packageName = ps.name;
3954            pi.setLongVersionCode(ps.versionCode);
3955            pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
3956            pi.firstInstallTime = ps.firstInstallTime;
3957            pi.lastUpdateTime = ps.lastUpdateTime;
3958
3959            ApplicationInfo ai = new ApplicationInfo();
3960            ai.packageName = ps.name;
3961            ai.uid = UserHandle.getUid(userId, ps.appId);
3962            ai.primaryCpuAbi = ps.primaryCpuAbiString;
3963            ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
3964            ai.setVersionCode(ps.versionCode);
3965            ai.flags = ps.pkgFlags;
3966            ai.privateFlags = ps.pkgPrivateFlags;
3967            pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
3968
3969            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
3970                    + ps.name + "]. Provides a minimum info.");
3971            return pi;
3972        } else {
3973            return null;
3974        }
3975    }
3976
3977    @Override
3978    public void checkPackageStartable(String packageName, int userId) {
3979        final int callingUid = Binder.getCallingUid();
3980        if (getInstantAppPackageName(callingUid) != null) {
3981            throw new SecurityException("Instant applications don't have access to this method");
3982        }
3983        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3984        synchronized (mPackages) {
3985            final PackageSetting ps = mSettings.mPackages.get(packageName);
3986            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3987                throw new SecurityException("Package " + packageName + " was not found!");
3988            }
3989
3990            if (!ps.getInstalled(userId)) {
3991                throw new SecurityException(
3992                        "Package " + packageName + " was not installed for user " + userId + "!");
3993            }
3994
3995            if (mSafeMode && !ps.isSystem()) {
3996                throw new SecurityException("Package " + packageName + " not a system app!");
3997            }
3998
3999            if (mFrozenPackages.contains(packageName)) {
4000                throw new SecurityException("Package " + packageName + " is currently frozen!");
4001            }
4002
4003            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
4004                throw new SecurityException("Package " + packageName + " is not encryption aware!");
4005            }
4006        }
4007    }
4008
4009    @Override
4010    public boolean isPackageAvailable(String packageName, int userId) {
4011        if (!sUserManager.exists(userId)) return false;
4012        final int callingUid = Binder.getCallingUid();
4013        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4014                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
4015        synchronized (mPackages) {
4016            PackageParser.Package p = mPackages.get(packageName);
4017            if (p != null) {
4018                final PackageSetting ps = (PackageSetting) p.mExtras;
4019                if (filterAppAccessLPr(ps, callingUid, userId)) {
4020                    return false;
4021                }
4022                if (ps != null) {
4023                    final PackageUserState state = ps.readUserState(userId);
4024                    if (state != null) {
4025                        return PackageParser.isAvailable(state);
4026                    }
4027                }
4028            }
4029        }
4030        return false;
4031    }
4032
4033    @Override
4034    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
4035        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
4036                flags, Binder.getCallingUid(), userId);
4037    }
4038
4039    @Override
4040    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
4041            int flags, int userId) {
4042        return getPackageInfoInternal(versionedPackage.getPackageName(),
4043                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
4044    }
4045
4046    /**
4047     * Important: The provided filterCallingUid is used exclusively to filter out packages
4048     * that can be seen based on user state. It's typically the original caller uid prior
4049     * to clearing. Because it can only be provided by trusted code, it's value can be
4050     * trusted and will be used as-is; unlike userId which will be validated by this method.
4051     */
4052    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
4053            int flags, int filterCallingUid, int userId) {
4054        if (!sUserManager.exists(userId)) return null;
4055        flags = updateFlagsForPackage(flags, userId, packageName);
4056        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4057                false /* requireFullPermission */, false /* checkShell */, "get package info");
4058
4059        // reader
4060        synchronized (mPackages) {
4061            // Normalize package name to handle renamed packages and static libs
4062            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
4063
4064            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
4065            if (matchFactoryOnly) {
4066                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
4067                if (ps != null) {
4068                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4069                        return null;
4070                    }
4071                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4072                        return null;
4073                    }
4074                    return generatePackageInfo(ps, flags, userId);
4075                }
4076            }
4077
4078            PackageParser.Package p = mPackages.get(packageName);
4079            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
4080                return null;
4081            }
4082            if (DEBUG_PACKAGE_INFO)
4083                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4084            if (p != null) {
4085                final PackageSetting ps = (PackageSetting) p.mExtras;
4086                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4087                    return null;
4088                }
4089                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4090                    return null;
4091                }
4092                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4093            }
4094            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4095                final PackageSetting ps = mSettings.mPackages.get(packageName);
4096                if (ps == null) return null;
4097                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4098                    return null;
4099                }
4100                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4101                    return null;
4102                }
4103                return generatePackageInfo(ps, flags, userId);
4104            }
4105        }
4106        return null;
4107    }
4108
4109    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4110        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4111            return true;
4112        }
4113        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4114            return true;
4115        }
4116        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4117            return true;
4118        }
4119        return false;
4120    }
4121
4122    private boolean isComponentVisibleToInstantApp(
4123            @Nullable ComponentName component, @ComponentType int type) {
4124        if (type == TYPE_ACTIVITY) {
4125            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4126            if (activity == null) {
4127                return false;
4128            }
4129            final boolean visibleToInstantApp =
4130                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4131            final boolean explicitlyVisibleToInstantApp =
4132                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4133            return visibleToInstantApp && explicitlyVisibleToInstantApp;
4134        } else if (type == TYPE_RECEIVER) {
4135            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4136            if (activity == null) {
4137                return false;
4138            }
4139            final boolean visibleToInstantApp =
4140                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4141            final boolean explicitlyVisibleToInstantApp =
4142                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4143            return visibleToInstantApp && !explicitlyVisibleToInstantApp;
4144        } else if (type == TYPE_SERVICE) {
4145            final PackageParser.Service service = mServices.mServices.get(component);
4146            return service != null
4147                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4148                    : false;
4149        } else if (type == TYPE_PROVIDER) {
4150            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4151            return provider != null
4152                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4153                    : false;
4154        } else if (type == TYPE_UNKNOWN) {
4155            return isComponentVisibleToInstantApp(component);
4156        }
4157        return false;
4158    }
4159
4160    /**
4161     * Returns whether or not access to the application should be filtered.
4162     * <p>
4163     * Access may be limited based upon whether the calling or target applications
4164     * are instant applications.
4165     *
4166     * @see #canAccessInstantApps(int)
4167     */
4168    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4169            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4170        // if we're in an isolated process, get the real calling UID
4171        if (Process.isIsolated(callingUid)) {
4172            callingUid = mIsolatedOwners.get(callingUid);
4173        }
4174        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4175        final boolean callerIsInstantApp = instantAppPkgName != null;
4176        if (ps == null) {
4177            if (callerIsInstantApp) {
4178                // pretend the application exists, but, needs to be filtered
4179                return true;
4180            }
4181            return false;
4182        }
4183        // if the target and caller are the same application, don't filter
4184        if (isCallerSameApp(ps.name, callingUid)) {
4185            return false;
4186        }
4187        if (callerIsInstantApp) {
4188            // both caller and target are both instant, but, different applications, filter
4189            if (ps.getInstantApp(userId)) {
4190                return true;
4191            }
4192            // request for a specific component; if it hasn't been explicitly exposed through
4193            // property or instrumentation target, filter
4194            if (component != null) {
4195                final PackageParser.Instrumentation instrumentation =
4196                        mInstrumentation.get(component);
4197                if (instrumentation != null
4198                        && isCallerSameApp(instrumentation.info.targetPackage, callingUid)) {
4199                    return false;
4200                }
4201                return !isComponentVisibleToInstantApp(component, componentType);
4202            }
4203            // request for application; if no components have been explicitly exposed, filter
4204            return !ps.pkg.visibleToInstantApps;
4205        }
4206        if (ps.getInstantApp(userId)) {
4207            // caller can see all components of all instant applications, don't filter
4208            if (canViewInstantApps(callingUid, userId)) {
4209                return false;
4210            }
4211            // request for a specific instant application component, filter
4212            if (component != null) {
4213                return true;
4214            }
4215            // request for an instant application; if the caller hasn't been granted access, filter
4216            return !mInstantAppRegistry.isInstantAccessGranted(
4217                    userId, UserHandle.getAppId(callingUid), ps.appId);
4218        }
4219        return false;
4220    }
4221
4222    /**
4223     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4224     */
4225    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4226        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4227    }
4228
4229    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4230            int flags) {
4231        // Callers can access only the libs they depend on, otherwise they need to explicitly
4232        // ask for the shared libraries given the caller is allowed to access all static libs.
4233        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4234            // System/shell/root get to see all static libs
4235            final int appId = UserHandle.getAppId(uid);
4236            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4237                    || appId == Process.ROOT_UID) {
4238                return false;
4239            }
4240            // Installer gets to see all static libs.
4241            if (PackageManager.PERMISSION_GRANTED
4242                    == checkUidPermission(Manifest.permission.INSTALL_PACKAGES, uid)) {
4243                return false;
4244            }
4245        }
4246
4247        // No package means no static lib as it is always on internal storage
4248        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4249            return false;
4250        }
4251
4252        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4253                ps.pkg.staticSharedLibVersion);
4254        if (libEntry == null) {
4255            return false;
4256        }
4257
4258        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4259        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4260        if (uidPackageNames == null) {
4261            return true;
4262        }
4263
4264        for (String uidPackageName : uidPackageNames) {
4265            if (ps.name.equals(uidPackageName)) {
4266                return false;
4267            }
4268            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4269            if (uidPs != null) {
4270                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4271                        libEntry.info.getName());
4272                if (index < 0) {
4273                    continue;
4274                }
4275                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4276                    return false;
4277                }
4278            }
4279        }
4280        return true;
4281    }
4282
4283    @Override
4284    public String[] currentToCanonicalPackageNames(String[] names) {
4285        final int callingUid = Binder.getCallingUid();
4286        if (getInstantAppPackageName(callingUid) != null) {
4287            return names;
4288        }
4289        final String[] out = new String[names.length];
4290        // reader
4291        synchronized (mPackages) {
4292            final int callingUserId = UserHandle.getUserId(callingUid);
4293            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4294            for (int i=names.length-1; i>=0; i--) {
4295                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4296                boolean translateName = false;
4297                if (ps != null && ps.realName != null) {
4298                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4299                    translateName = !targetIsInstantApp
4300                            || canViewInstantApps
4301                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4302                                    UserHandle.getAppId(callingUid), ps.appId);
4303                }
4304                out[i] = translateName ? ps.realName : names[i];
4305            }
4306        }
4307        return out;
4308    }
4309
4310    @Override
4311    public String[] canonicalToCurrentPackageNames(String[] names) {
4312        final int callingUid = Binder.getCallingUid();
4313        if (getInstantAppPackageName(callingUid) != null) {
4314            return names;
4315        }
4316        final String[] out = new String[names.length];
4317        // reader
4318        synchronized (mPackages) {
4319            final int callingUserId = UserHandle.getUserId(callingUid);
4320            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4321            for (int i=names.length-1; i>=0; i--) {
4322                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4323                boolean translateName = false;
4324                if (cur != null) {
4325                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4326                    final boolean targetIsInstantApp =
4327                            ps != null && ps.getInstantApp(callingUserId);
4328                    translateName = !targetIsInstantApp
4329                            || canViewInstantApps
4330                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4331                                    UserHandle.getAppId(callingUid), ps.appId);
4332                }
4333                out[i] = translateName ? cur : names[i];
4334            }
4335        }
4336        return out;
4337    }
4338
4339    @Override
4340    public int getPackageUid(String packageName, int flags, int userId) {
4341        if (!sUserManager.exists(userId)) return -1;
4342        final int callingUid = Binder.getCallingUid();
4343        flags = updateFlagsForPackage(flags, userId, packageName);
4344        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4345                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4346
4347        // reader
4348        synchronized (mPackages) {
4349            final PackageParser.Package p = mPackages.get(packageName);
4350            if (p != null && p.isMatch(flags)) {
4351                PackageSetting ps = (PackageSetting) p.mExtras;
4352                if (filterAppAccessLPr(ps, callingUid, userId)) {
4353                    return -1;
4354                }
4355                return UserHandle.getUid(userId, p.applicationInfo.uid);
4356            }
4357            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4358                final PackageSetting ps = mSettings.mPackages.get(packageName);
4359                if (ps != null && ps.isMatch(flags)
4360                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4361                    return UserHandle.getUid(userId, ps.appId);
4362                }
4363            }
4364        }
4365
4366        return -1;
4367    }
4368
4369    @Override
4370    public int[] getPackageGids(String packageName, int flags, int userId) {
4371        if (!sUserManager.exists(userId)) return null;
4372        final int callingUid = Binder.getCallingUid();
4373        flags = updateFlagsForPackage(flags, userId, packageName);
4374        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4375                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4376
4377        // reader
4378        synchronized (mPackages) {
4379            final PackageParser.Package p = mPackages.get(packageName);
4380            if (p != null && p.isMatch(flags)) {
4381                PackageSetting ps = (PackageSetting) p.mExtras;
4382                if (filterAppAccessLPr(ps, callingUid, userId)) {
4383                    return null;
4384                }
4385                // TODO: Shouldn't this be checking for package installed state for userId and
4386                // return null?
4387                return ps.getPermissionsState().computeGids(userId);
4388            }
4389            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4390                final PackageSetting ps = mSettings.mPackages.get(packageName);
4391                if (ps != null && ps.isMatch(flags)
4392                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4393                    return ps.getPermissionsState().computeGids(userId);
4394                }
4395            }
4396        }
4397
4398        return null;
4399    }
4400
4401    @Override
4402    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4403        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4404    }
4405
4406    @Override
4407    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4408            int flags) {
4409        final List<PermissionInfo> permissionList =
4410                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4411        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4412    }
4413
4414    @Override
4415    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4416        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4417    }
4418
4419    @Override
4420    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4421        final List<PermissionGroupInfo> permissionList =
4422                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4423        return (permissionList == null)
4424                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4425    }
4426
4427    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4428            int filterCallingUid, int userId) {
4429        if (!sUserManager.exists(userId)) return null;
4430        PackageSetting ps = mSettings.mPackages.get(packageName);
4431        if (ps != null) {
4432            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4433                return null;
4434            }
4435            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4436                return null;
4437            }
4438            if (ps.pkg == null) {
4439                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4440                if (pInfo != null) {
4441                    return pInfo.applicationInfo;
4442                }
4443                return null;
4444            }
4445            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4446                    ps.readUserState(userId), userId);
4447            if (ai != null) {
4448                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4449            }
4450            return ai;
4451        }
4452        return null;
4453    }
4454
4455    @Override
4456    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4457        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4458    }
4459
4460    /**
4461     * Important: The provided filterCallingUid is used exclusively to filter out applications
4462     * that can be seen based on user state. It's typically the original caller uid prior
4463     * to clearing. Because it can only be provided by trusted code, it's value can be
4464     * trusted and will be used as-is; unlike userId which will be validated by this method.
4465     */
4466    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4467            int filterCallingUid, int userId) {
4468        if (!sUserManager.exists(userId)) return null;
4469        flags = updateFlagsForApplication(flags, userId, packageName);
4470        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4471                false /* requireFullPermission */, false /* checkShell */, "get application info");
4472
4473        // writer
4474        synchronized (mPackages) {
4475            // Normalize package name to handle renamed packages and static libs
4476            packageName = resolveInternalPackageNameLPr(packageName,
4477                    PackageManager.VERSION_CODE_HIGHEST);
4478
4479            PackageParser.Package p = mPackages.get(packageName);
4480            if (DEBUG_PACKAGE_INFO) Log.v(
4481                    TAG, "getApplicationInfo " + packageName
4482                    + ": " + p);
4483            if (p != null) {
4484                PackageSetting ps = mSettings.mPackages.get(packageName);
4485                if (ps == null) return null;
4486                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4487                    return null;
4488                }
4489                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4490                    return null;
4491                }
4492                // Note: isEnabledLP() does not apply here - always return info
4493                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4494                        p, flags, ps.readUserState(userId), userId);
4495                if (ai != null) {
4496                    ai.packageName = resolveExternalPackageNameLPr(p);
4497                }
4498                return ai;
4499            }
4500            if ("android".equals(packageName)||"system".equals(packageName)) {
4501                return mAndroidApplication;
4502            }
4503            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4504                // Already generates the external package name
4505                return generateApplicationInfoFromSettingsLPw(packageName,
4506                        flags, filterCallingUid, userId);
4507            }
4508        }
4509        return null;
4510    }
4511
4512    private String normalizePackageNameLPr(String packageName) {
4513        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4514        return normalizedPackageName != null ? normalizedPackageName : packageName;
4515    }
4516
4517    @Override
4518    public void deletePreloadsFileCache() {
4519        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4520            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4521        }
4522        File dir = Environment.getDataPreloadsFileCacheDirectory();
4523        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4524        FileUtils.deleteContents(dir);
4525    }
4526
4527    @Override
4528    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4529            final int storageFlags, final IPackageDataObserver observer) {
4530        mContext.enforceCallingOrSelfPermission(
4531                android.Manifest.permission.CLEAR_APP_CACHE, null);
4532        mHandler.post(() -> {
4533            boolean success = false;
4534            try {
4535                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4536                success = true;
4537            } catch (IOException e) {
4538                Slog.w(TAG, e);
4539            }
4540            if (observer != null) {
4541                try {
4542                    observer.onRemoveCompleted(null, success);
4543                } catch (RemoteException e) {
4544                    Slog.w(TAG, e);
4545                }
4546            }
4547        });
4548    }
4549
4550    @Override
4551    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4552            final int storageFlags, final IntentSender pi) {
4553        mContext.enforceCallingOrSelfPermission(
4554                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4555        mHandler.post(() -> {
4556            boolean success = false;
4557            try {
4558                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4559                success = true;
4560            } catch (IOException e) {
4561                Slog.w(TAG, e);
4562            }
4563            if (pi != null) {
4564                try {
4565                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4566                } catch (SendIntentException e) {
4567                    Slog.w(TAG, e);
4568                }
4569            }
4570        });
4571    }
4572
4573    /**
4574     * Blocking call to clear various types of cached data across the system
4575     * until the requested bytes are available.
4576     */
4577    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4578        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4579        final File file = storage.findPathForUuid(volumeUuid);
4580        if (file.getUsableSpace() >= bytes) return;
4581
4582        if (ENABLE_FREE_CACHE_V2) {
4583            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4584                    volumeUuid);
4585            final boolean aggressive = (storageFlags
4586                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4587            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4588
4589            // 1. Pre-flight to determine if we have any chance to succeed
4590            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4591            if (internalVolume && (aggressive || SystemProperties
4592                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4593                deletePreloadsFileCache();
4594                if (file.getUsableSpace() >= bytes) return;
4595            }
4596
4597            // 3. Consider parsed APK data (aggressive only)
4598            if (internalVolume && aggressive) {
4599                FileUtils.deleteContents(mCacheDir);
4600                if (file.getUsableSpace() >= bytes) return;
4601            }
4602
4603            // 4. Consider cached app data (above quotas)
4604            try {
4605                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4606                        Installer.FLAG_FREE_CACHE_V2);
4607            } catch (InstallerException ignored) {
4608            }
4609            if (file.getUsableSpace() >= bytes) return;
4610
4611            // 5. Consider shared libraries with refcount=0 and age>min cache period
4612            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4613                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4614                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4615                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4616                return;
4617            }
4618
4619            // 6. Consider dexopt output (aggressive only)
4620            // TODO: Implement
4621
4622            // 7. Consider installed instant apps unused longer than min cache period
4623            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4624                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4625                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4626                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4627                return;
4628            }
4629
4630            // 8. Consider cached app data (below quotas)
4631            try {
4632                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4633                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4634            } catch (InstallerException ignored) {
4635            }
4636            if (file.getUsableSpace() >= bytes) return;
4637
4638            // 9. Consider DropBox entries
4639            // TODO: Implement
4640
4641            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4642            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4643                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4644                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4645                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4646                return;
4647            }
4648        } else {
4649            try {
4650                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4651            } catch (InstallerException ignored) {
4652            }
4653            if (file.getUsableSpace() >= bytes) return;
4654        }
4655
4656        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4657    }
4658
4659    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4660            throws IOException {
4661        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4662        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4663
4664        List<VersionedPackage> packagesToDelete = null;
4665        final long now = System.currentTimeMillis();
4666
4667        synchronized (mPackages) {
4668            final int[] allUsers = sUserManager.getUserIds();
4669            final int libCount = mSharedLibraries.size();
4670            for (int i = 0; i < libCount; i++) {
4671                final LongSparseArray<SharedLibraryEntry> versionedLib
4672                        = mSharedLibraries.valueAt(i);
4673                if (versionedLib == null) {
4674                    continue;
4675                }
4676                final int versionCount = versionedLib.size();
4677                for (int j = 0; j < versionCount; j++) {
4678                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4679                    // Skip packages that are not static shared libs.
4680                    if (!libInfo.isStatic()) {
4681                        break;
4682                    }
4683                    // Important: We skip static shared libs used for some user since
4684                    // in such a case we need to keep the APK on the device. The check for
4685                    // a lib being used for any user is performed by the uninstall call.
4686                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4687                    // Resolve the package name - we use synthetic package names internally
4688                    final String internalPackageName = resolveInternalPackageNameLPr(
4689                            declaringPackage.getPackageName(),
4690                            declaringPackage.getLongVersionCode());
4691                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4692                    // Skip unused static shared libs cached less than the min period
4693                    // to prevent pruning a lib needed by a subsequently installed package.
4694                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4695                        continue;
4696                    }
4697                    if (packagesToDelete == null) {
4698                        packagesToDelete = new ArrayList<>();
4699                    }
4700                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4701                            declaringPackage.getLongVersionCode()));
4702                }
4703            }
4704        }
4705
4706        if (packagesToDelete != null) {
4707            final int packageCount = packagesToDelete.size();
4708            for (int i = 0; i < packageCount; i++) {
4709                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4710                // Delete the package synchronously (will fail of the lib used for any user).
4711                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4712                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4713                                == PackageManager.DELETE_SUCCEEDED) {
4714                    if (volume.getUsableSpace() >= neededSpace) {
4715                        return true;
4716                    }
4717                }
4718            }
4719        }
4720
4721        return false;
4722    }
4723
4724    /**
4725     * Update given flags based on encryption status of current user.
4726     */
4727    private int updateFlags(int flags, int userId) {
4728        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4729                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4730            // Caller expressed an explicit opinion about what encryption
4731            // aware/unaware components they want to see, so fall through and
4732            // give them what they want
4733        } else {
4734            // Caller expressed no opinion, so match based on user state
4735            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4736                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4737            } else {
4738                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4739            }
4740        }
4741        return flags;
4742    }
4743
4744    private UserManagerInternal getUserManagerInternal() {
4745        if (mUserManagerInternal == null) {
4746            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4747        }
4748        return mUserManagerInternal;
4749    }
4750
4751    private ActivityManagerInternal getActivityManagerInternal() {
4752        if (mActivityManagerInternal == null) {
4753            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4754        }
4755        return mActivityManagerInternal;
4756    }
4757
4758
4759    private DeviceIdleController.LocalService getDeviceIdleController() {
4760        if (mDeviceIdleController == null) {
4761            mDeviceIdleController =
4762                    LocalServices.getService(DeviceIdleController.LocalService.class);
4763        }
4764        return mDeviceIdleController;
4765    }
4766
4767    /**
4768     * Update given flags when being used to request {@link PackageInfo}.
4769     */
4770    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4771        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4772        boolean triaged = true;
4773        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4774                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4775            // Caller is asking for component details, so they'd better be
4776            // asking for specific encryption matching behavior, or be triaged
4777            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4778                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4779                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4780                triaged = false;
4781            }
4782        }
4783        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4784                | PackageManager.MATCH_SYSTEM_ONLY
4785                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4786            triaged = false;
4787        }
4788        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4789            mPermissionManager.enforceCrossUserPermission(
4790                    Binder.getCallingUid(), userId, false, false,
4791                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4792                    + Debug.getCallers(5));
4793        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4794                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4795            // If the caller wants all packages and has a restricted profile associated with it,
4796            // then match all users. This is to make sure that launchers that need to access work
4797            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4798            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4799            flags |= PackageManager.MATCH_ANY_USER;
4800        }
4801        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4802            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4803                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4804        }
4805        return updateFlags(flags, userId);
4806    }
4807
4808    /**
4809     * Update given flags when being used to request {@link ApplicationInfo}.
4810     */
4811    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4812        return updateFlagsForPackage(flags, userId, cookie);
4813    }
4814
4815    /**
4816     * Update given flags when being used to request {@link ComponentInfo}.
4817     */
4818    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4819        if (cookie instanceof Intent) {
4820            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4821                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4822            }
4823        }
4824
4825        boolean triaged = true;
4826        // Caller is asking for component details, so they'd better be
4827        // asking for specific encryption matching behavior, or be triaged
4828        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4829                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4830                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4831            triaged = false;
4832        }
4833        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4834            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4835                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4836        }
4837
4838        return updateFlags(flags, userId);
4839    }
4840
4841    /**
4842     * Update given intent when being used to request {@link ResolveInfo}.
4843     */
4844    private Intent updateIntentForResolve(Intent intent) {
4845        if (intent.getSelector() != null) {
4846            intent = intent.getSelector();
4847        }
4848        if (DEBUG_PREFERRED) {
4849            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4850        }
4851        return intent;
4852    }
4853
4854    /**
4855     * Update given flags when being used to request {@link ResolveInfo}.
4856     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4857     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4858     * flag set. However, this flag is only honoured in three circumstances:
4859     * <ul>
4860     * <li>when called from a system process</li>
4861     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4862     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4863     * action and a {@code android.intent.category.BROWSABLE} category</li>
4864     * </ul>
4865     */
4866    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4867        return updateFlagsForResolve(flags, userId, intent, callingUid,
4868                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4869    }
4870    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4871            boolean wantInstantApps) {
4872        return updateFlagsForResolve(flags, userId, intent, callingUid,
4873                wantInstantApps, false /*onlyExposedExplicitly*/);
4874    }
4875    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4876            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4877        // Safe mode means we shouldn't match any third-party components
4878        if (mSafeMode) {
4879            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4880        }
4881        if (getInstantAppPackageName(callingUid) != null) {
4882            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4883            if (onlyExposedExplicitly) {
4884                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4885            }
4886            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4887            flags |= PackageManager.MATCH_INSTANT;
4888        } else {
4889            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4890            final boolean allowMatchInstant = wantInstantApps
4891                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4892            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4893                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4894            if (!allowMatchInstant) {
4895                flags &= ~PackageManager.MATCH_INSTANT;
4896            }
4897        }
4898        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4899    }
4900
4901    @Override
4902    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4903        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4904    }
4905
4906    /**
4907     * Important: The provided filterCallingUid is used exclusively to filter out activities
4908     * that can be seen based on user state. It's typically the original caller uid prior
4909     * to clearing. Because it can only be provided by trusted code, it's value can be
4910     * trusted and will be used as-is; unlike userId which will be validated by this method.
4911     */
4912    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4913            int filterCallingUid, int userId) {
4914        if (!sUserManager.exists(userId)) return null;
4915        flags = updateFlagsForComponent(flags, userId, component);
4916
4917        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4918            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4919                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4920        }
4921
4922        synchronized (mPackages) {
4923            PackageParser.Activity a = mActivities.mActivities.get(component);
4924
4925            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4926            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4927                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4928                if (ps == null) return null;
4929                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4930                    return null;
4931                }
4932                return PackageParser.generateActivityInfo(
4933                        a, flags, ps.readUserState(userId), userId);
4934            }
4935            if (mResolveComponentName.equals(component)) {
4936                return PackageParser.generateActivityInfo(
4937                        mResolveActivity, flags, new PackageUserState(), userId);
4938            }
4939        }
4940        return null;
4941    }
4942
4943    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4944        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4945            return false;
4946        }
4947        final long token = Binder.clearCallingIdentity();
4948        try {
4949            final int callingUserId = UserHandle.getUserId(callingUid);
4950            if (ActivityManager.getCurrentUser() != callingUserId) {
4951                return false;
4952            }
4953            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4954        } finally {
4955            Binder.restoreCallingIdentity(token);
4956        }
4957    }
4958
4959    @Override
4960    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4961            String resolvedType) {
4962        synchronized (mPackages) {
4963            if (component.equals(mResolveComponentName)) {
4964                // The resolver supports EVERYTHING!
4965                return true;
4966            }
4967            final int callingUid = Binder.getCallingUid();
4968            final int callingUserId = UserHandle.getUserId(callingUid);
4969            PackageParser.Activity a = mActivities.mActivities.get(component);
4970            if (a == null) {
4971                return false;
4972            }
4973            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4974            if (ps == null) {
4975                return false;
4976            }
4977            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4978                return false;
4979            }
4980            for (int i=0; i<a.intents.size(); i++) {
4981                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4982                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4983                    return true;
4984                }
4985            }
4986            return false;
4987        }
4988    }
4989
4990    @Override
4991    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4992        if (!sUserManager.exists(userId)) return null;
4993        final int callingUid = Binder.getCallingUid();
4994        flags = updateFlagsForComponent(flags, userId, component);
4995        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4996                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4997        synchronized (mPackages) {
4998            PackageParser.Activity a = mReceivers.mActivities.get(component);
4999            if (DEBUG_PACKAGE_INFO) Log.v(
5000                TAG, "getReceiverInfo " + component + ": " + a);
5001            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
5002                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5003                if (ps == null) return null;
5004                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
5005                    return null;
5006                }
5007                return PackageParser.generateActivityInfo(
5008                        a, flags, ps.readUserState(userId), userId);
5009            }
5010        }
5011        return null;
5012    }
5013
5014    @Override
5015    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
5016            int flags, int userId) {
5017        if (!sUserManager.exists(userId)) return null;
5018        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
5019        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5020            return null;
5021        }
5022
5023        flags = updateFlagsForPackage(flags, userId, null);
5024
5025        final boolean canSeeStaticLibraries =
5026                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
5027                        == PERMISSION_GRANTED
5028                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
5029                        == PERMISSION_GRANTED
5030                || canRequestPackageInstallsInternal(packageName,
5031                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
5032                        false  /* throwIfPermNotDeclared*/)
5033                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
5034                        == PERMISSION_GRANTED;
5035
5036        synchronized (mPackages) {
5037            List<SharedLibraryInfo> result = null;
5038
5039            final int libCount = mSharedLibraries.size();
5040            for (int i = 0; i < libCount; i++) {
5041                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5042                if (versionedLib == null) {
5043                    continue;
5044                }
5045
5046                final int versionCount = versionedLib.size();
5047                for (int j = 0; j < versionCount; j++) {
5048                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5049                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5050                        break;
5051                    }
5052                    final long identity = Binder.clearCallingIdentity();
5053                    try {
5054                        PackageInfo packageInfo = getPackageInfoVersioned(
5055                                libInfo.getDeclaringPackage(), flags
5056                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5057                        if (packageInfo == null) {
5058                            continue;
5059                        }
5060                    } finally {
5061                        Binder.restoreCallingIdentity(identity);
5062                    }
5063
5064                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5065                            libInfo.getLongVersion(), libInfo.getType(),
5066                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5067                            flags, userId));
5068
5069                    if (result == null) {
5070                        result = new ArrayList<>();
5071                    }
5072                    result.add(resLibInfo);
5073                }
5074            }
5075
5076            return result != null ? new ParceledListSlice<>(result) : null;
5077        }
5078    }
5079
5080    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5081            SharedLibraryInfo libInfo, int flags, int userId) {
5082        List<VersionedPackage> versionedPackages = null;
5083        final int packageCount = mSettings.mPackages.size();
5084        for (int i = 0; i < packageCount; i++) {
5085            PackageSetting ps = mSettings.mPackages.valueAt(i);
5086
5087            if (ps == null) {
5088                continue;
5089            }
5090
5091            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5092                continue;
5093            }
5094
5095            final String libName = libInfo.getName();
5096            if (libInfo.isStatic()) {
5097                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5098                if (libIdx < 0) {
5099                    continue;
5100                }
5101                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
5102                    continue;
5103                }
5104                if (versionedPackages == null) {
5105                    versionedPackages = new ArrayList<>();
5106                }
5107                // If the dependent is a static shared lib, use the public package name
5108                String dependentPackageName = ps.name;
5109                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5110                    dependentPackageName = ps.pkg.manifestPackageName;
5111                }
5112                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5113            } else if (ps.pkg != null) {
5114                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5115                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5116                    if (versionedPackages == null) {
5117                        versionedPackages = new ArrayList<>();
5118                    }
5119                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5120                }
5121            }
5122        }
5123
5124        return versionedPackages;
5125    }
5126
5127    @Override
5128    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5129        if (!sUserManager.exists(userId)) return null;
5130        final int callingUid = Binder.getCallingUid();
5131        flags = updateFlagsForComponent(flags, userId, component);
5132        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5133                false /* requireFullPermission */, false /* checkShell */, "get service info");
5134        synchronized (mPackages) {
5135            PackageParser.Service s = mServices.mServices.get(component);
5136            if (DEBUG_PACKAGE_INFO) Log.v(
5137                TAG, "getServiceInfo " + component + ": " + s);
5138            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5139                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5140                if (ps == null) return null;
5141                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5142                    return null;
5143                }
5144                return PackageParser.generateServiceInfo(
5145                        s, flags, ps.readUserState(userId), userId);
5146            }
5147        }
5148        return null;
5149    }
5150
5151    @Override
5152    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5153        if (!sUserManager.exists(userId)) return null;
5154        final int callingUid = Binder.getCallingUid();
5155        flags = updateFlagsForComponent(flags, userId, component);
5156        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5157                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5158        synchronized (mPackages) {
5159            PackageParser.Provider p = mProviders.mProviders.get(component);
5160            if (DEBUG_PACKAGE_INFO) Log.v(
5161                TAG, "getProviderInfo " + component + ": " + p);
5162            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5163                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5164                if (ps == null) return null;
5165                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5166                    return null;
5167                }
5168                return PackageParser.generateProviderInfo(
5169                        p, flags, ps.readUserState(userId), userId);
5170            }
5171        }
5172        return null;
5173    }
5174
5175    @Override
5176    public String[] getSystemSharedLibraryNames() {
5177        // allow instant applications
5178        synchronized (mPackages) {
5179            Set<String> libs = null;
5180            final int libCount = mSharedLibraries.size();
5181            for (int i = 0; i < libCount; i++) {
5182                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5183                if (versionedLib == null) {
5184                    continue;
5185                }
5186                final int versionCount = versionedLib.size();
5187                for (int j = 0; j < versionCount; j++) {
5188                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5189                    if (!libEntry.info.isStatic()) {
5190                        if (libs == null) {
5191                            libs = new ArraySet<>();
5192                        }
5193                        libs.add(libEntry.info.getName());
5194                        break;
5195                    }
5196                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5197                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5198                            UserHandle.getUserId(Binder.getCallingUid()),
5199                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5200                        if (libs == null) {
5201                            libs = new ArraySet<>();
5202                        }
5203                        libs.add(libEntry.info.getName());
5204                        break;
5205                    }
5206                }
5207            }
5208
5209            if (libs != null) {
5210                String[] libsArray = new String[libs.size()];
5211                libs.toArray(libsArray);
5212                return libsArray;
5213            }
5214
5215            return null;
5216        }
5217    }
5218
5219    @Override
5220    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5221        // allow instant applications
5222        synchronized (mPackages) {
5223            return mServicesSystemSharedLibraryPackageName;
5224        }
5225    }
5226
5227    @Override
5228    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5229        // allow instant applications
5230        synchronized (mPackages) {
5231            return mSharedSystemSharedLibraryPackageName;
5232        }
5233    }
5234
5235    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5236        for (int i = userList.length - 1; i >= 0; --i) {
5237            final int userId = userList[i];
5238            // don't add instant app to the list of updates
5239            if (pkgSetting.getInstantApp(userId)) {
5240                continue;
5241            }
5242            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5243            if (changedPackages == null) {
5244                changedPackages = new SparseArray<>();
5245                mChangedPackages.put(userId, changedPackages);
5246            }
5247            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5248            if (sequenceNumbers == null) {
5249                sequenceNumbers = new HashMap<>();
5250                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5251            }
5252            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5253            if (sequenceNumber != null) {
5254                changedPackages.remove(sequenceNumber);
5255            }
5256            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5257            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5258        }
5259        mChangedPackagesSequenceNumber++;
5260    }
5261
5262    @Override
5263    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5264        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5265            return null;
5266        }
5267        synchronized (mPackages) {
5268            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5269                return null;
5270            }
5271            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5272            if (changedPackages == null) {
5273                return null;
5274            }
5275            final List<String> packageNames =
5276                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5277            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5278                final String packageName = changedPackages.get(i);
5279                if (packageName != null) {
5280                    packageNames.add(packageName);
5281                }
5282            }
5283            return packageNames.isEmpty()
5284                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5285        }
5286    }
5287
5288    @Override
5289    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5290        // allow instant applications
5291        ArrayList<FeatureInfo> res;
5292        synchronized (mAvailableFeatures) {
5293            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5294            res.addAll(mAvailableFeatures.values());
5295        }
5296        final FeatureInfo fi = new FeatureInfo();
5297        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5298                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5299        res.add(fi);
5300
5301        return new ParceledListSlice<>(res);
5302    }
5303
5304    @Override
5305    public boolean hasSystemFeature(String name, int version) {
5306        // allow instant applications
5307        synchronized (mAvailableFeatures) {
5308            final FeatureInfo feat = mAvailableFeatures.get(name);
5309            if (feat == null) {
5310                return false;
5311            } else {
5312                return feat.version >= version;
5313            }
5314        }
5315    }
5316
5317    @Override
5318    public int checkPermission(String permName, String pkgName, int userId) {
5319        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5320    }
5321
5322    @Override
5323    public int checkUidPermission(String permName, int uid) {
5324        synchronized (mPackages) {
5325            final String[] packageNames = getPackagesForUid(uid);
5326            final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0)
5327                    ? mPackages.get(packageNames[0])
5328                    : null;
5329            return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid());
5330        }
5331    }
5332
5333    @Override
5334    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5335        if (UserHandle.getCallingUserId() != userId) {
5336            mContext.enforceCallingPermission(
5337                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5338                    "isPermissionRevokedByPolicy for user " + userId);
5339        }
5340
5341        if (checkPermission(permission, packageName, userId)
5342                == PackageManager.PERMISSION_GRANTED) {
5343            return false;
5344        }
5345
5346        final int callingUid = Binder.getCallingUid();
5347        if (getInstantAppPackageName(callingUid) != null) {
5348            if (!isCallerSameApp(packageName, callingUid)) {
5349                return false;
5350            }
5351        } else {
5352            if (isInstantApp(packageName, userId)) {
5353                return false;
5354            }
5355        }
5356
5357        final long identity = Binder.clearCallingIdentity();
5358        try {
5359            final int flags = getPermissionFlags(permission, packageName, userId);
5360            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5361        } finally {
5362            Binder.restoreCallingIdentity(identity);
5363        }
5364    }
5365
5366    @Override
5367    public String getPermissionControllerPackageName() {
5368        synchronized (mPackages) {
5369            return mRequiredInstallerPackage;
5370        }
5371    }
5372
5373    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5374        return mPermissionManager.addDynamicPermission(
5375                info, async, getCallingUid(), new PermissionCallback() {
5376                    @Override
5377                    public void onPermissionChanged() {
5378                        if (!async) {
5379                            mSettings.writeLPr();
5380                        } else {
5381                            scheduleWriteSettingsLocked();
5382                        }
5383                    }
5384                });
5385    }
5386
5387    @Override
5388    public boolean addPermission(PermissionInfo info) {
5389        synchronized (mPackages) {
5390            return addDynamicPermission(info, false);
5391        }
5392    }
5393
5394    @Override
5395    public boolean addPermissionAsync(PermissionInfo info) {
5396        synchronized (mPackages) {
5397            return addDynamicPermission(info, true);
5398        }
5399    }
5400
5401    @Override
5402    public void removePermission(String permName) {
5403        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5404    }
5405
5406    @Override
5407    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5408        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5409                getCallingUid(), userId, mPermissionCallback);
5410    }
5411
5412    @Override
5413    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5414        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5415                getCallingUid(), userId, mPermissionCallback);
5416    }
5417
5418    @Override
5419    public void resetRuntimePermissions() {
5420        mContext.enforceCallingOrSelfPermission(
5421                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5422                "revokeRuntimePermission");
5423
5424        int callingUid = Binder.getCallingUid();
5425        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5426            mContext.enforceCallingOrSelfPermission(
5427                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5428                    "resetRuntimePermissions");
5429        }
5430
5431        synchronized (mPackages) {
5432            mPermissionManager.updateAllPermissions(
5433                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5434                    mPermissionCallback);
5435            for (int userId : UserManagerService.getInstance().getUserIds()) {
5436                final int packageCount = mPackages.size();
5437                for (int i = 0; i < packageCount; i++) {
5438                    PackageParser.Package pkg = mPackages.valueAt(i);
5439                    if (!(pkg.mExtras instanceof PackageSetting)) {
5440                        continue;
5441                    }
5442                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5443                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5444                }
5445            }
5446        }
5447    }
5448
5449    @Override
5450    public int getPermissionFlags(String permName, String packageName, int userId) {
5451        return mPermissionManager.getPermissionFlags(
5452                permName, packageName, getCallingUid(), userId);
5453    }
5454
5455    @Override
5456    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5457            int flagValues, int userId) {
5458        mPermissionManager.updatePermissionFlags(
5459                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5460                mPermissionCallback);
5461    }
5462
5463    /**
5464     * Update the permission flags for all packages and runtime permissions of a user in order
5465     * to allow device or profile owner to remove POLICY_FIXED.
5466     */
5467    @Override
5468    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5469        synchronized (mPackages) {
5470            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5471                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5472                    mPermissionCallback);
5473            if (changed) {
5474                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5475            }
5476        }
5477    }
5478
5479    @Override
5480    public boolean shouldShowRequestPermissionRationale(String permissionName,
5481            String packageName, int userId) {
5482        if (UserHandle.getCallingUserId() != userId) {
5483            mContext.enforceCallingPermission(
5484                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5485                    "canShowRequestPermissionRationale for user " + userId);
5486        }
5487
5488        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5489        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5490            return false;
5491        }
5492
5493        if (checkPermission(permissionName, packageName, userId)
5494                == PackageManager.PERMISSION_GRANTED) {
5495            return false;
5496        }
5497
5498        final int flags;
5499
5500        final long identity = Binder.clearCallingIdentity();
5501        try {
5502            flags = getPermissionFlags(permissionName,
5503                    packageName, userId);
5504        } finally {
5505            Binder.restoreCallingIdentity(identity);
5506        }
5507
5508        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5509                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5510                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5511
5512        if ((flags & fixedFlags) != 0) {
5513            return false;
5514        }
5515
5516        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5517    }
5518
5519    @Override
5520    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5521        mContext.enforceCallingOrSelfPermission(
5522                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5523                "addOnPermissionsChangeListener");
5524
5525        synchronized (mPackages) {
5526            mOnPermissionChangeListeners.addListenerLocked(listener);
5527        }
5528    }
5529
5530    @Override
5531    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5532        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5533            throw new SecurityException("Instant applications don't have access to this method");
5534        }
5535        synchronized (mPackages) {
5536            mOnPermissionChangeListeners.removeListenerLocked(listener);
5537        }
5538    }
5539
5540    @Override
5541    public boolean isProtectedBroadcast(String actionName) {
5542        // allow instant applications
5543        synchronized (mProtectedBroadcasts) {
5544            if (mProtectedBroadcasts.contains(actionName)) {
5545                return true;
5546            } else if (actionName != null) {
5547                // TODO: remove these terrible hacks
5548                if (actionName.startsWith("android.net.netmon.lingerExpired")
5549                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5550                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5551                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5552                    return true;
5553                }
5554            }
5555        }
5556        return false;
5557    }
5558
5559    @Override
5560    public int checkSignatures(String pkg1, String pkg2) {
5561        synchronized (mPackages) {
5562            final PackageParser.Package p1 = mPackages.get(pkg1);
5563            final PackageParser.Package p2 = mPackages.get(pkg2);
5564            if (p1 == null || p1.mExtras == null
5565                    || p2 == null || p2.mExtras == null) {
5566                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5567            }
5568            final int callingUid = Binder.getCallingUid();
5569            final int callingUserId = UserHandle.getUserId(callingUid);
5570            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5571            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5572            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5573                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5574                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5575            }
5576            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5577        }
5578    }
5579
5580    @Override
5581    public int checkUidSignatures(int uid1, int uid2) {
5582        final int callingUid = Binder.getCallingUid();
5583        final int callingUserId = UserHandle.getUserId(callingUid);
5584        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5585        // Map to base uids.
5586        uid1 = UserHandle.getAppId(uid1);
5587        uid2 = UserHandle.getAppId(uid2);
5588        // reader
5589        synchronized (mPackages) {
5590            Signature[] s1;
5591            Signature[] s2;
5592            Object obj = mSettings.getUserIdLPr(uid1);
5593            if (obj != null) {
5594                if (obj instanceof SharedUserSetting) {
5595                    if (isCallerInstantApp) {
5596                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5597                    }
5598                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5599                } else if (obj instanceof PackageSetting) {
5600                    final PackageSetting ps = (PackageSetting) obj;
5601                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5602                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5603                    }
5604                    s1 = ps.signatures.mSigningDetails.signatures;
5605                } else {
5606                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5607                }
5608            } else {
5609                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5610            }
5611            obj = mSettings.getUserIdLPr(uid2);
5612            if (obj != null) {
5613                if (obj instanceof SharedUserSetting) {
5614                    if (isCallerInstantApp) {
5615                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5616                    }
5617                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5618                } else if (obj instanceof PackageSetting) {
5619                    final PackageSetting ps = (PackageSetting) obj;
5620                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5621                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5622                    }
5623                    s2 = ps.signatures.mSigningDetails.signatures;
5624                } else {
5625                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5626                }
5627            } else {
5628                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5629            }
5630            return compareSignatures(s1, s2);
5631        }
5632    }
5633
5634    @Override
5635    public boolean hasSigningCertificate(
5636            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5637
5638        synchronized (mPackages) {
5639            final PackageParser.Package p = mPackages.get(packageName);
5640            if (p == null || p.mExtras == null) {
5641                return false;
5642            }
5643            final int callingUid = Binder.getCallingUid();
5644            final int callingUserId = UserHandle.getUserId(callingUid);
5645            final PackageSetting ps = (PackageSetting) p.mExtras;
5646            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5647                return false;
5648            }
5649            switch (type) {
5650                case CERT_INPUT_RAW_X509:
5651                    return p.mSigningDetails.hasCertificate(certificate);
5652                case CERT_INPUT_SHA256:
5653                    return p.mSigningDetails.hasSha256Certificate(certificate);
5654                default:
5655                    return false;
5656            }
5657        }
5658    }
5659
5660    @Override
5661    public boolean hasUidSigningCertificate(
5662            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5663        final int callingUid = Binder.getCallingUid();
5664        final int callingUserId = UserHandle.getUserId(callingUid);
5665        // Map to base uids.
5666        uid = UserHandle.getAppId(uid);
5667        // reader
5668        synchronized (mPackages) {
5669            final PackageParser.SigningDetails signingDetails;
5670            final Object obj = mSettings.getUserIdLPr(uid);
5671            if (obj != null) {
5672                if (obj instanceof SharedUserSetting) {
5673                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5674                    if (isCallerInstantApp) {
5675                        return false;
5676                    }
5677                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5678                } else if (obj instanceof PackageSetting) {
5679                    final PackageSetting ps = (PackageSetting) obj;
5680                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5681                        return false;
5682                    }
5683                    signingDetails = ps.signatures.mSigningDetails;
5684                } else {
5685                    return false;
5686                }
5687            } else {
5688                return false;
5689            }
5690            switch (type) {
5691                case CERT_INPUT_RAW_X509:
5692                    return signingDetails.hasCertificate(certificate);
5693                case CERT_INPUT_SHA256:
5694                    return signingDetails.hasSha256Certificate(certificate);
5695                default:
5696                    return false;
5697            }
5698        }
5699    }
5700
5701    /**
5702     * This method should typically only be used when granting or revoking
5703     * permissions, since the app may immediately restart after this call.
5704     * <p>
5705     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5706     * guard your work against the app being relaunched.
5707     */
5708    private void killUid(int appId, int userId, String reason) {
5709        final long identity = Binder.clearCallingIdentity();
5710        try {
5711            IActivityManager am = ActivityManager.getService();
5712            if (am != null) {
5713                try {
5714                    am.killUid(appId, userId, reason);
5715                } catch (RemoteException e) {
5716                    /* ignore - same process */
5717                }
5718            }
5719        } finally {
5720            Binder.restoreCallingIdentity(identity);
5721        }
5722    }
5723
5724    /**
5725     * If the database version for this type of package (internal storage or
5726     * external storage) is less than the version where package signatures
5727     * were updated, return true.
5728     */
5729    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5730        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5731        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5732    }
5733
5734    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5735        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5736        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5737    }
5738
5739    @Override
5740    public List<String> getAllPackages() {
5741        final int callingUid = Binder.getCallingUid();
5742        final int callingUserId = UserHandle.getUserId(callingUid);
5743        synchronized (mPackages) {
5744            if (canViewInstantApps(callingUid, callingUserId)) {
5745                return new ArrayList<String>(mPackages.keySet());
5746            }
5747            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5748            final List<String> result = new ArrayList<>();
5749            if (instantAppPkgName != null) {
5750                // caller is an instant application; filter unexposed applications
5751                for (PackageParser.Package pkg : mPackages.values()) {
5752                    if (!pkg.visibleToInstantApps) {
5753                        continue;
5754                    }
5755                    result.add(pkg.packageName);
5756                }
5757            } else {
5758                // caller is a normal application; filter instant applications
5759                for (PackageParser.Package pkg : mPackages.values()) {
5760                    final PackageSetting ps =
5761                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5762                    if (ps != null
5763                            && ps.getInstantApp(callingUserId)
5764                            && !mInstantAppRegistry.isInstantAccessGranted(
5765                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5766                        continue;
5767                    }
5768                    result.add(pkg.packageName);
5769                }
5770            }
5771            return result;
5772        }
5773    }
5774
5775    @Override
5776    public String[] getPackagesForUid(int uid) {
5777        final int callingUid = Binder.getCallingUid();
5778        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5779        final int userId = UserHandle.getUserId(uid);
5780        uid = UserHandle.getAppId(uid);
5781        // reader
5782        synchronized (mPackages) {
5783            Object obj = mSettings.getUserIdLPr(uid);
5784            if (obj instanceof SharedUserSetting) {
5785                if (isCallerInstantApp) {
5786                    return null;
5787                }
5788                final SharedUserSetting sus = (SharedUserSetting) obj;
5789                final int N = sus.packages.size();
5790                String[] res = new String[N];
5791                final Iterator<PackageSetting> it = sus.packages.iterator();
5792                int i = 0;
5793                while (it.hasNext()) {
5794                    PackageSetting ps = it.next();
5795                    if (ps.getInstalled(userId)) {
5796                        res[i++] = ps.name;
5797                    } else {
5798                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5799                    }
5800                }
5801                return res;
5802            } else if (obj instanceof PackageSetting) {
5803                final PackageSetting ps = (PackageSetting) obj;
5804                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5805                    return new String[]{ps.name};
5806                }
5807            }
5808        }
5809        return null;
5810    }
5811
5812    @Override
5813    public String getNameForUid(int uid) {
5814        final int callingUid = Binder.getCallingUid();
5815        if (getInstantAppPackageName(callingUid) != null) {
5816            return null;
5817        }
5818        synchronized (mPackages) {
5819            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5820            if (obj instanceof SharedUserSetting) {
5821                final SharedUserSetting sus = (SharedUserSetting) obj;
5822                return sus.name + ":" + sus.userId;
5823            } else if (obj instanceof PackageSetting) {
5824                final PackageSetting ps = (PackageSetting) obj;
5825                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5826                    return null;
5827                }
5828                return ps.name;
5829            }
5830            return null;
5831        }
5832    }
5833
5834    @Override
5835    public String[] getNamesForUids(int[] uids) {
5836        if (uids == null || uids.length == 0) {
5837            return null;
5838        }
5839        final int callingUid = Binder.getCallingUid();
5840        if (getInstantAppPackageName(callingUid) != null) {
5841            return null;
5842        }
5843        final String[] names = new String[uids.length];
5844        synchronized (mPackages) {
5845            for (int i = uids.length - 1; i >= 0; i--) {
5846                final int uid = uids[i];
5847                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5848                if (obj instanceof SharedUserSetting) {
5849                    final SharedUserSetting sus = (SharedUserSetting) obj;
5850                    names[i] = "shared:" + sus.name;
5851                } else if (obj instanceof PackageSetting) {
5852                    final PackageSetting ps = (PackageSetting) obj;
5853                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5854                        names[i] = null;
5855                    } else {
5856                        names[i] = ps.name;
5857                    }
5858                } else {
5859                    names[i] = null;
5860                }
5861            }
5862        }
5863        return names;
5864    }
5865
5866    @Override
5867    public int getUidForSharedUser(String sharedUserName) {
5868        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5869            return -1;
5870        }
5871        if (sharedUserName == null) {
5872            return -1;
5873        }
5874        // reader
5875        synchronized (mPackages) {
5876            SharedUserSetting suid;
5877            try {
5878                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5879                if (suid != null) {
5880                    return suid.userId;
5881                }
5882            } catch (PackageManagerException ignore) {
5883                // can't happen, but, still need to catch it
5884            }
5885            return -1;
5886        }
5887    }
5888
5889    @Override
5890    public int getFlagsForUid(int uid) {
5891        final int callingUid = Binder.getCallingUid();
5892        if (getInstantAppPackageName(callingUid) != null) {
5893            return 0;
5894        }
5895        synchronized (mPackages) {
5896            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5897            if (obj instanceof SharedUserSetting) {
5898                final SharedUserSetting sus = (SharedUserSetting) obj;
5899                return sus.pkgFlags;
5900            } else if (obj instanceof PackageSetting) {
5901                final PackageSetting ps = (PackageSetting) obj;
5902                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5903                    return 0;
5904                }
5905                return ps.pkgFlags;
5906            }
5907        }
5908        return 0;
5909    }
5910
5911    @Override
5912    public int getPrivateFlagsForUid(int uid) {
5913        final int callingUid = Binder.getCallingUid();
5914        if (getInstantAppPackageName(callingUid) != null) {
5915            return 0;
5916        }
5917        synchronized (mPackages) {
5918            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5919            if (obj instanceof SharedUserSetting) {
5920                final SharedUserSetting sus = (SharedUserSetting) obj;
5921                return sus.pkgPrivateFlags;
5922            } else if (obj instanceof PackageSetting) {
5923                final PackageSetting ps = (PackageSetting) obj;
5924                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5925                    return 0;
5926                }
5927                return ps.pkgPrivateFlags;
5928            }
5929        }
5930        return 0;
5931    }
5932
5933    @Override
5934    public boolean isUidPrivileged(int uid) {
5935        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5936            return false;
5937        }
5938        uid = UserHandle.getAppId(uid);
5939        // reader
5940        synchronized (mPackages) {
5941            Object obj = mSettings.getUserIdLPr(uid);
5942            if (obj instanceof SharedUserSetting) {
5943                final SharedUserSetting sus = (SharedUserSetting) obj;
5944                final Iterator<PackageSetting> it = sus.packages.iterator();
5945                while (it.hasNext()) {
5946                    if (it.next().isPrivileged()) {
5947                        return true;
5948                    }
5949                }
5950            } else if (obj instanceof PackageSetting) {
5951                final PackageSetting ps = (PackageSetting) obj;
5952                return ps.isPrivileged();
5953            }
5954        }
5955        return false;
5956    }
5957
5958    @Override
5959    public String[] getAppOpPermissionPackages(String permName) {
5960        return mPermissionManager.getAppOpPermissionPackages(permName);
5961    }
5962
5963    @Override
5964    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5965            int flags, int userId) {
5966        return resolveIntentInternal(intent, resolvedType, flags, userId, false,
5967                Binder.getCallingUid());
5968    }
5969
5970    /**
5971     * Normally instant apps can only be resolved when they're visible to the caller.
5972     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5973     * since we need to allow the system to start any installed application.
5974     */
5975    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5976            int flags, int userId, boolean resolveForStart, int filterCallingUid) {
5977        try {
5978            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5979
5980            if (!sUserManager.exists(userId)) return null;
5981            final int callingUid = Binder.getCallingUid();
5982            flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart);
5983            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5984                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5985
5986            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5987            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5988                    flags, filterCallingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5989            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5990
5991            final ResolveInfo bestChoice =
5992                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5993            return bestChoice;
5994        } finally {
5995            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5996        }
5997    }
5998
5999    @Override
6000    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6001        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6002            throw new SecurityException(
6003                    "findPersistentPreferredActivity can only be run by the system");
6004        }
6005        if (!sUserManager.exists(userId)) {
6006            return null;
6007        }
6008        final int callingUid = Binder.getCallingUid();
6009        intent = updateIntentForResolve(intent);
6010        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6011        final int flags = updateFlagsForResolve(
6012                0, userId, intent, callingUid, false /*includeInstantApps*/);
6013        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6014                userId);
6015        synchronized (mPackages) {
6016            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6017                    userId);
6018        }
6019    }
6020
6021    @Override
6022    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6023            IntentFilter filter, int match, ComponentName activity) {
6024        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6025            return;
6026        }
6027        final int userId = UserHandle.getCallingUserId();
6028        if (DEBUG_PREFERRED) {
6029            Log.v(TAG, "setLastChosenActivity intent=" + intent
6030                + " resolvedType=" + resolvedType
6031                + " flags=" + flags
6032                + " filter=" + filter
6033                + " match=" + match
6034                + " activity=" + activity);
6035            filter.dump(new PrintStreamPrinter(System.out), "    ");
6036        }
6037        intent.setComponent(null);
6038        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6039                userId);
6040        // Find any earlier preferred or last chosen entries and nuke them
6041        findPreferredActivity(intent, resolvedType,
6042                flags, query, 0, false, true, false, userId);
6043        // Add the new activity as the last chosen for this filter
6044        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6045                "Setting last chosen");
6046    }
6047
6048    @Override
6049    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6050        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6051            return null;
6052        }
6053        final int userId = UserHandle.getCallingUserId();
6054        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6055        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6056                userId);
6057        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6058                false, false, false, userId);
6059    }
6060
6061    /**
6062     * Returns whether or not instant apps have been disabled remotely.
6063     */
6064    private boolean areWebInstantAppsDisabled() {
6065        return mWebInstantAppsDisabled;
6066    }
6067
6068    private boolean isInstantAppResolutionAllowed(
6069            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6070            boolean skipPackageCheck) {
6071        if (mInstantAppResolverConnection == null) {
6072            return false;
6073        }
6074        if (mInstantAppInstallerActivity == null) {
6075            return false;
6076        }
6077        if (intent.getComponent() != null) {
6078            return false;
6079        }
6080        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6081            return false;
6082        }
6083        if (!skipPackageCheck && intent.getPackage() != null) {
6084            return false;
6085        }
6086        if (!intent.isWebIntent()) {
6087            // for non web intents, we should not resolve externally if an app already exists to
6088            // handle it or if the caller didn't explicitly request it.
6089            if ((resolvedActivities != null && resolvedActivities.size() != 0)
6090                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
6091                return false;
6092            }
6093        } else {
6094            if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
6095                return false;
6096            } else if (areWebInstantAppsDisabled()) {
6097                return false;
6098            }
6099        }
6100        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6101        // Or if there's already an ephemeral app installed that handles the action
6102        synchronized (mPackages) {
6103            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6104            for (int n = 0; n < count; n++) {
6105                final ResolveInfo info = resolvedActivities.get(n);
6106                final String packageName = info.activityInfo.packageName;
6107                final PackageSetting ps = mSettings.mPackages.get(packageName);
6108                if (ps != null) {
6109                    // only check domain verification status if the app is not a browser
6110                    if (!info.handleAllWebDataURI) {
6111                        // Try to get the status from User settings first
6112                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6113                        final int status = (int) (packedStatus >> 32);
6114                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6115                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6116                            if (DEBUG_INSTANT) {
6117                                Slog.v(TAG, "DENY instant app;"
6118                                    + " pkg: " + packageName + ", status: " + status);
6119                            }
6120                            return false;
6121                        }
6122                    }
6123                    if (ps.getInstantApp(userId)) {
6124                        if (DEBUG_INSTANT) {
6125                            Slog.v(TAG, "DENY instant app installed;"
6126                                    + " pkg: " + packageName);
6127                        }
6128                        return false;
6129                    }
6130                }
6131            }
6132        }
6133        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6134        return true;
6135    }
6136
6137    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6138            Intent origIntent, String resolvedType, String callingPackage,
6139            Bundle verificationBundle, int userId) {
6140        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6141                new InstantAppRequest(responseObj, origIntent, resolvedType,
6142                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6143        mHandler.sendMessage(msg);
6144    }
6145
6146    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6147            int flags, List<ResolveInfo> query, int userId) {
6148        if (query != null) {
6149            final int N = query.size();
6150            if (N == 1) {
6151                return query.get(0);
6152            } else if (N > 1) {
6153                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6154                // If there is more than one activity with the same priority,
6155                // then let the user decide between them.
6156                ResolveInfo r0 = query.get(0);
6157                ResolveInfo r1 = query.get(1);
6158                if (DEBUG_INTENT_MATCHING || debug) {
6159                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6160                            + r1.activityInfo.name + "=" + r1.priority);
6161                }
6162                // If the first activity has a higher priority, or a different
6163                // default, then it is always desirable to pick it.
6164                if (r0.priority != r1.priority
6165                        || r0.preferredOrder != r1.preferredOrder
6166                        || r0.isDefault != r1.isDefault) {
6167                    return query.get(0);
6168                }
6169                // If we have saved a preference for a preferred activity for
6170                // this Intent, use that.
6171                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6172                        flags, query, r0.priority, true, false, debug, userId);
6173                if (ri != null) {
6174                    return ri;
6175                }
6176                // If we have an ephemeral app, use it
6177                for (int i = 0; i < N; i++) {
6178                    ri = query.get(i);
6179                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6180                        final String packageName = ri.activityInfo.packageName;
6181                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6182                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6183                        final int status = (int)(packedStatus >> 32);
6184                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6185                            return ri;
6186                        }
6187                    }
6188                }
6189                ri = new ResolveInfo(mResolveInfo);
6190                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6191                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6192                // If all of the options come from the same package, show the application's
6193                // label and icon instead of the generic resolver's.
6194                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6195                // and then throw away the ResolveInfo itself, meaning that the caller loses
6196                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6197                // a fallback for this case; we only set the target package's resources on
6198                // the ResolveInfo, not the ActivityInfo.
6199                final String intentPackage = intent.getPackage();
6200                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6201                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6202                    ri.resolvePackageName = intentPackage;
6203                    if (userNeedsBadging(userId)) {
6204                        ri.noResourceId = true;
6205                    } else {
6206                        ri.icon = appi.icon;
6207                    }
6208                    ri.iconResourceId = appi.icon;
6209                    ri.labelRes = appi.labelRes;
6210                }
6211                ri.activityInfo.applicationInfo = new ApplicationInfo(
6212                        ri.activityInfo.applicationInfo);
6213                if (userId != 0) {
6214                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6215                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6216                }
6217                // Make sure that the resolver is displayable in car mode
6218                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6219                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6220                return ri;
6221            }
6222        }
6223        return null;
6224    }
6225
6226    /**
6227     * Return true if the given list is not empty and all of its contents have
6228     * an activityInfo with the given package name.
6229     */
6230    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6231        if (ArrayUtils.isEmpty(list)) {
6232            return false;
6233        }
6234        for (int i = 0, N = list.size(); i < N; i++) {
6235            final ResolveInfo ri = list.get(i);
6236            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6237            if (ai == null || !packageName.equals(ai.packageName)) {
6238                return false;
6239            }
6240        }
6241        return true;
6242    }
6243
6244    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6245            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6246        final int N = query.size();
6247        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6248                .get(userId);
6249        // Get the list of persistent preferred activities that handle the intent
6250        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6251        List<PersistentPreferredActivity> pprefs = ppir != null
6252                ? ppir.queryIntent(intent, resolvedType,
6253                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6254                        userId)
6255                : null;
6256        if (pprefs != null && pprefs.size() > 0) {
6257            final int M = pprefs.size();
6258            for (int i=0; i<M; i++) {
6259                final PersistentPreferredActivity ppa = pprefs.get(i);
6260                if (DEBUG_PREFERRED || debug) {
6261                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6262                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6263                            + "\n  component=" + ppa.mComponent);
6264                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6265                }
6266                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6267                        flags | MATCH_DISABLED_COMPONENTS, userId);
6268                if (DEBUG_PREFERRED || debug) {
6269                    Slog.v(TAG, "Found persistent preferred activity:");
6270                    if (ai != null) {
6271                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6272                    } else {
6273                        Slog.v(TAG, "  null");
6274                    }
6275                }
6276                if (ai == null) {
6277                    // This previously registered persistent preferred activity
6278                    // component is no longer known. Ignore it and do NOT remove it.
6279                    continue;
6280                }
6281                for (int j=0; j<N; j++) {
6282                    final ResolveInfo ri = query.get(j);
6283                    if (!ri.activityInfo.applicationInfo.packageName
6284                            .equals(ai.applicationInfo.packageName)) {
6285                        continue;
6286                    }
6287                    if (!ri.activityInfo.name.equals(ai.name)) {
6288                        continue;
6289                    }
6290                    //  Found a persistent preference that can handle the intent.
6291                    if (DEBUG_PREFERRED || debug) {
6292                        Slog.v(TAG, "Returning persistent preferred activity: " +
6293                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6294                    }
6295                    return ri;
6296                }
6297            }
6298        }
6299        return null;
6300    }
6301
6302    // TODO: handle preferred activities missing while user has amnesia
6303    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6304            List<ResolveInfo> query, int priority, boolean always,
6305            boolean removeMatches, boolean debug, int userId) {
6306        if (!sUserManager.exists(userId)) return null;
6307        final int callingUid = Binder.getCallingUid();
6308        flags = updateFlagsForResolve(
6309                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6310        intent = updateIntentForResolve(intent);
6311        // writer
6312        synchronized (mPackages) {
6313            // Try to find a matching persistent preferred activity.
6314            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6315                    debug, userId);
6316
6317            // If a persistent preferred activity matched, use it.
6318            if (pri != null) {
6319                return pri;
6320            }
6321
6322            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6323            // Get the list of preferred activities that handle the intent
6324            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6325            List<PreferredActivity> prefs = pir != null
6326                    ? pir.queryIntent(intent, resolvedType,
6327                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6328                            userId)
6329                    : null;
6330            if (prefs != null && prefs.size() > 0) {
6331                boolean changed = false;
6332                try {
6333                    // First figure out how good the original match set is.
6334                    // We will only allow preferred activities that came
6335                    // from the same match quality.
6336                    int match = 0;
6337
6338                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6339
6340                    final int N = query.size();
6341                    for (int j=0; j<N; j++) {
6342                        final ResolveInfo ri = query.get(j);
6343                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6344                                + ": 0x" + Integer.toHexString(match));
6345                        if (ri.match > match) {
6346                            match = ri.match;
6347                        }
6348                    }
6349
6350                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6351                            + Integer.toHexString(match));
6352
6353                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6354                    final int M = prefs.size();
6355                    for (int i=0; i<M; i++) {
6356                        final PreferredActivity pa = prefs.get(i);
6357                        if (DEBUG_PREFERRED || debug) {
6358                            Slog.v(TAG, "Checking PreferredActivity ds="
6359                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6360                                    + "\n  component=" + pa.mPref.mComponent);
6361                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6362                        }
6363                        if (pa.mPref.mMatch != match) {
6364                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6365                                    + Integer.toHexString(pa.mPref.mMatch));
6366                            continue;
6367                        }
6368                        // If it's not an "always" type preferred activity and that's what we're
6369                        // looking for, skip it.
6370                        if (always && !pa.mPref.mAlways) {
6371                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6372                            continue;
6373                        }
6374                        final ActivityInfo ai = getActivityInfo(
6375                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6376                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6377                                userId);
6378                        if (DEBUG_PREFERRED || debug) {
6379                            Slog.v(TAG, "Found preferred activity:");
6380                            if (ai != null) {
6381                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6382                            } else {
6383                                Slog.v(TAG, "  null");
6384                            }
6385                        }
6386                        if (ai == null) {
6387                            // This previously registered preferred activity
6388                            // component is no longer known.  Most likely an update
6389                            // to the app was installed and in the new version this
6390                            // component no longer exists.  Clean it up by removing
6391                            // it from the preferred activities list, and skip it.
6392                            Slog.w(TAG, "Removing dangling preferred activity: "
6393                                    + pa.mPref.mComponent);
6394                            pir.removeFilter(pa);
6395                            changed = true;
6396                            continue;
6397                        }
6398                        for (int j=0; j<N; j++) {
6399                            final ResolveInfo ri = query.get(j);
6400                            if (!ri.activityInfo.applicationInfo.packageName
6401                                    .equals(ai.applicationInfo.packageName)) {
6402                                continue;
6403                            }
6404                            if (!ri.activityInfo.name.equals(ai.name)) {
6405                                continue;
6406                            }
6407
6408                            if (removeMatches) {
6409                                pir.removeFilter(pa);
6410                                changed = true;
6411                                if (DEBUG_PREFERRED) {
6412                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6413                                }
6414                                break;
6415                            }
6416
6417                            // Okay we found a previously set preferred or last chosen app.
6418                            // If the result set is different from when this
6419                            // was created, and is not a subset of the preferred set, we need to
6420                            // clear it and re-ask the user their preference, if we're looking for
6421                            // an "always" type entry.
6422                            if (always && !pa.mPref.sameSet(query)) {
6423                                if (pa.mPref.isSuperset(query)) {
6424                                    // some components of the set are no longer present in
6425                                    // the query, but the preferred activity can still be reused
6426                                    if (DEBUG_PREFERRED) {
6427                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6428                                                + " still valid as only non-preferred components"
6429                                                + " were removed for " + intent + " type "
6430                                                + resolvedType);
6431                                    }
6432                                    // remove obsolete components and re-add the up-to-date filter
6433                                    PreferredActivity freshPa = new PreferredActivity(pa,
6434                                            pa.mPref.mMatch,
6435                                            pa.mPref.discardObsoleteComponents(query),
6436                                            pa.mPref.mComponent,
6437                                            pa.mPref.mAlways);
6438                                    pir.removeFilter(pa);
6439                                    pir.addFilter(freshPa);
6440                                    changed = true;
6441                                } else {
6442                                    Slog.i(TAG,
6443                                            "Result set changed, dropping preferred activity for "
6444                                                    + intent + " type " + resolvedType);
6445                                    if (DEBUG_PREFERRED) {
6446                                        Slog.v(TAG, "Removing preferred activity since set changed "
6447                                                + pa.mPref.mComponent);
6448                                    }
6449                                    pir.removeFilter(pa);
6450                                    // Re-add the filter as a "last chosen" entry (!always)
6451                                    PreferredActivity lastChosen = new PreferredActivity(
6452                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6453                                    pir.addFilter(lastChosen);
6454                                    changed = true;
6455                                    return null;
6456                                }
6457                            }
6458
6459                            // Yay! Either the set matched or we're looking for the last chosen
6460                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6461                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6462                            return ri;
6463                        }
6464                    }
6465                } finally {
6466                    if (changed) {
6467                        if (DEBUG_PREFERRED) {
6468                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6469                        }
6470                        scheduleWritePackageRestrictionsLocked(userId);
6471                    }
6472                }
6473            }
6474        }
6475        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6476        return null;
6477    }
6478
6479    /*
6480     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6481     */
6482    @Override
6483    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6484            int targetUserId) {
6485        mContext.enforceCallingOrSelfPermission(
6486                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6487        List<CrossProfileIntentFilter> matches =
6488                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6489        if (matches != null) {
6490            int size = matches.size();
6491            for (int i = 0; i < size; i++) {
6492                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6493            }
6494        }
6495        if (intent.hasWebURI()) {
6496            // cross-profile app linking works only towards the parent.
6497            final int callingUid = Binder.getCallingUid();
6498            final UserInfo parent = getProfileParent(sourceUserId);
6499            synchronized(mPackages) {
6500                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6501                        false /*includeInstantApps*/);
6502                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6503                        intent, resolvedType, flags, sourceUserId, parent.id);
6504                return xpDomainInfo != null;
6505            }
6506        }
6507        return false;
6508    }
6509
6510    private UserInfo getProfileParent(int userId) {
6511        final long identity = Binder.clearCallingIdentity();
6512        try {
6513            return sUserManager.getProfileParent(userId);
6514        } finally {
6515            Binder.restoreCallingIdentity(identity);
6516        }
6517    }
6518
6519    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6520            String resolvedType, int userId) {
6521        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6522        if (resolver != null) {
6523            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6524        }
6525        return null;
6526    }
6527
6528    @Override
6529    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6530            String resolvedType, int flags, int userId) {
6531        try {
6532            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6533
6534            return new ParceledListSlice<>(
6535                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6536        } finally {
6537            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6538        }
6539    }
6540
6541    /**
6542     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6543     * instant, returns {@code null}.
6544     */
6545    private String getInstantAppPackageName(int callingUid) {
6546        synchronized (mPackages) {
6547            // If the caller is an isolated app use the owner's uid for the lookup.
6548            if (Process.isIsolated(callingUid)) {
6549                callingUid = mIsolatedOwners.get(callingUid);
6550            }
6551            final int appId = UserHandle.getAppId(callingUid);
6552            final Object obj = mSettings.getUserIdLPr(appId);
6553            if (obj instanceof PackageSetting) {
6554                final PackageSetting ps = (PackageSetting) obj;
6555                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6556                return isInstantApp ? ps.pkg.packageName : null;
6557            }
6558        }
6559        return null;
6560    }
6561
6562    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6563            String resolvedType, int flags, int userId) {
6564        return queryIntentActivitiesInternal(
6565                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6566                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6567    }
6568
6569    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6570            String resolvedType, int flags, int filterCallingUid, int userId,
6571            boolean resolveForStart, boolean allowDynamicSplits) {
6572        if (!sUserManager.exists(userId)) return Collections.emptyList();
6573        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6574        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6575                false /* requireFullPermission */, false /* checkShell */,
6576                "query intent activities");
6577        final String pkgName = intent.getPackage();
6578        ComponentName comp = intent.getComponent();
6579        if (comp == null) {
6580            if (intent.getSelector() != null) {
6581                intent = intent.getSelector();
6582                comp = intent.getComponent();
6583            }
6584        }
6585
6586        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6587                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6588        if (comp != null) {
6589            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6590            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6591            if (ai != null) {
6592                // When specifying an explicit component, we prevent the activity from being
6593                // used when either 1) the calling package is normal and the activity is within
6594                // an ephemeral application or 2) the calling package is ephemeral and the
6595                // activity is not visible to ephemeral applications.
6596                final boolean matchInstantApp =
6597                        (flags & PackageManager.MATCH_INSTANT) != 0;
6598                final boolean matchVisibleToInstantAppOnly =
6599                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6600                final boolean matchExplicitlyVisibleOnly =
6601                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6602                final boolean isCallerInstantApp =
6603                        instantAppPkgName != null;
6604                final boolean isTargetSameInstantApp =
6605                        comp.getPackageName().equals(instantAppPkgName);
6606                final boolean isTargetInstantApp =
6607                        (ai.applicationInfo.privateFlags
6608                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6609                final boolean isTargetVisibleToInstantApp =
6610                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6611                final boolean isTargetExplicitlyVisibleToInstantApp =
6612                        isTargetVisibleToInstantApp
6613                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6614                final boolean isTargetHiddenFromInstantApp =
6615                        !isTargetVisibleToInstantApp
6616                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6617                final boolean blockResolution =
6618                        !isTargetSameInstantApp
6619                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6620                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6621                                        && isTargetHiddenFromInstantApp));
6622                if (!blockResolution) {
6623                    final ResolveInfo ri = new ResolveInfo();
6624                    ri.activityInfo = ai;
6625                    list.add(ri);
6626                }
6627            }
6628            return applyPostResolutionFilter(
6629                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6630        }
6631
6632        // reader
6633        boolean sortResult = false;
6634        boolean addInstant = false;
6635        List<ResolveInfo> result;
6636        synchronized (mPackages) {
6637            if (pkgName == null) {
6638                List<CrossProfileIntentFilter> matchingFilters =
6639                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6640                // Check for results that need to skip the current profile.
6641                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6642                        resolvedType, flags, userId);
6643                if (xpResolveInfo != null) {
6644                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6645                    xpResult.add(xpResolveInfo);
6646                    return applyPostResolutionFilter(
6647                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6648                            allowDynamicSplits, filterCallingUid, userId, intent);
6649                }
6650
6651                // Check for results in the current profile.
6652                result = filterIfNotSystemUser(mActivities.queryIntent(
6653                        intent, resolvedType, flags, userId), userId);
6654                addInstant = isInstantAppResolutionAllowed(intent, result, userId,
6655                        false /*skipPackageCheck*/);
6656                // Check for cross profile results.
6657                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6658                xpResolveInfo = queryCrossProfileIntents(
6659                        matchingFilters, intent, resolvedType, flags, userId,
6660                        hasNonNegativePriorityResult);
6661                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6662                    boolean isVisibleToUser = filterIfNotSystemUser(
6663                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6664                    if (isVisibleToUser) {
6665                        result.add(xpResolveInfo);
6666                        sortResult = true;
6667                    }
6668                }
6669                if (intent.hasWebURI()) {
6670                    CrossProfileDomainInfo xpDomainInfo = null;
6671                    final UserInfo parent = getProfileParent(userId);
6672                    if (parent != null) {
6673                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6674                                flags, userId, parent.id);
6675                    }
6676                    if (xpDomainInfo != null) {
6677                        if (xpResolveInfo != null) {
6678                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6679                            // in the result.
6680                            result.remove(xpResolveInfo);
6681                        }
6682                        if (result.size() == 0 && !addInstant) {
6683                            // No result in current profile, but found candidate in parent user.
6684                            // And we are not going to add emphemeral app, so we can return the
6685                            // result straight away.
6686                            result.add(xpDomainInfo.resolveInfo);
6687                            return applyPostResolutionFilter(result, instantAppPkgName,
6688                                    allowDynamicSplits, filterCallingUid, userId, intent);
6689                        }
6690                    } else if (result.size() <= 1 && !addInstant) {
6691                        // No result in parent user and <= 1 result in current profile, and we
6692                        // are not going to add emphemeral app, so we can return the result without
6693                        // further processing.
6694                        return applyPostResolutionFilter(result, instantAppPkgName,
6695                                allowDynamicSplits, filterCallingUid, userId, intent);
6696                    }
6697                    // We have more than one candidate (combining results from current and parent
6698                    // profile), so we need filtering and sorting.
6699                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6700                            intent, flags, result, xpDomainInfo, userId);
6701                    sortResult = true;
6702                }
6703            } else {
6704                final PackageParser.Package pkg = mPackages.get(pkgName);
6705                result = null;
6706                if (pkg != null) {
6707                    result = filterIfNotSystemUser(
6708                            mActivities.queryIntentForPackage(
6709                                    intent, resolvedType, flags, pkg.activities, userId),
6710                            userId);
6711                }
6712                if (result == null || result.size() == 0) {
6713                    // the caller wants to resolve for a particular package; however, there
6714                    // were no installed results, so, try to find an ephemeral result
6715                    addInstant = isInstantAppResolutionAllowed(
6716                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6717                    if (result == null) {
6718                        result = new ArrayList<>();
6719                    }
6720                }
6721            }
6722        }
6723        if (addInstant) {
6724            result = maybeAddInstantAppInstaller(
6725                    result, intent, resolvedType, flags, userId, resolveForStart);
6726        }
6727        if (sortResult) {
6728            Collections.sort(result, mResolvePrioritySorter);
6729        }
6730        return applyPostResolutionFilter(
6731                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6732    }
6733
6734    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6735            String resolvedType, int flags, int userId, boolean resolveForStart) {
6736        // first, check to see if we've got an instant app already installed
6737        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6738        ResolveInfo localInstantApp = null;
6739        boolean blockResolution = false;
6740        if (!alreadyResolvedLocally) {
6741            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6742                    flags
6743                        | PackageManager.GET_RESOLVED_FILTER
6744                        | PackageManager.MATCH_INSTANT
6745                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6746                    userId);
6747            for (int i = instantApps.size() - 1; i >= 0; --i) {
6748                final ResolveInfo info = instantApps.get(i);
6749                final String packageName = info.activityInfo.packageName;
6750                final PackageSetting ps = mSettings.mPackages.get(packageName);
6751                if (ps.getInstantApp(userId)) {
6752                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6753                    final int status = (int)(packedStatus >> 32);
6754                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6755                        // there's a local instant application installed, but, the user has
6756                        // chosen to never use it; skip resolution and don't acknowledge
6757                        // an instant application is even available
6758                        if (DEBUG_INSTANT) {
6759                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6760                        }
6761                        blockResolution = true;
6762                        break;
6763                    } else {
6764                        // we have a locally installed instant application; skip resolution
6765                        // but acknowledge there's an instant application available
6766                        if (DEBUG_INSTANT) {
6767                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6768                        }
6769                        localInstantApp = info;
6770                        break;
6771                    }
6772                }
6773            }
6774        }
6775        // no app installed, let's see if one's available
6776        AuxiliaryResolveInfo auxiliaryResponse = null;
6777        if (!blockResolution) {
6778            if (localInstantApp == null) {
6779                // we don't have an instant app locally, resolve externally
6780                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6781                final InstantAppRequest requestObject = new InstantAppRequest(
6782                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6783                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6784                        resolveForStart);
6785                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6786                        mInstantAppResolverConnection, requestObject);
6787                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6788            } else {
6789                // we have an instant application locally, but, we can't admit that since
6790                // callers shouldn't be able to determine prior browsing. create a dummy
6791                // auxiliary response so the downstream code behaves as if there's an
6792                // instant application available externally. when it comes time to start
6793                // the instant application, we'll do the right thing.
6794                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6795                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6796                                        ai.packageName, ai.longVersionCode, null /* splitName */);
6797            }
6798        }
6799        if (intent.isWebIntent() && auxiliaryResponse == null) {
6800            return result;
6801        }
6802        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6803        if (ps == null
6804                || ps.getUserState().get(userId) == null
6805                || !ps.getUserState().get(userId).isEnabled(mInstantAppInstallerActivity, 0)) {
6806            return result;
6807        }
6808        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6809        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6810                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6811        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6812                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6813        // add a non-generic filter
6814        ephemeralInstaller.filter = new IntentFilter();
6815        if (intent.getAction() != null) {
6816            ephemeralInstaller.filter.addAction(intent.getAction());
6817        }
6818        if (intent.getData() != null && intent.getData().getPath() != null) {
6819            ephemeralInstaller.filter.addDataPath(
6820                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6821        }
6822        ephemeralInstaller.isInstantAppAvailable = true;
6823        // make sure this resolver is the default
6824        ephemeralInstaller.isDefault = true;
6825        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6826        if (DEBUG_INSTANT) {
6827            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6828        }
6829
6830        result.add(ephemeralInstaller);
6831        return result;
6832    }
6833
6834    private static class CrossProfileDomainInfo {
6835        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6836        ResolveInfo resolveInfo;
6837        /* Best domain verification status of the activities found in the other profile */
6838        int bestDomainVerificationStatus;
6839    }
6840
6841    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6842            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6843        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6844                sourceUserId)) {
6845            return null;
6846        }
6847        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6848                resolvedType, flags, parentUserId);
6849
6850        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6851            return null;
6852        }
6853        CrossProfileDomainInfo result = null;
6854        int size = resultTargetUser.size();
6855        for (int i = 0; i < size; i++) {
6856            ResolveInfo riTargetUser = resultTargetUser.get(i);
6857            // Intent filter verification is only for filters that specify a host. So don't return
6858            // those that handle all web uris.
6859            if (riTargetUser.handleAllWebDataURI) {
6860                continue;
6861            }
6862            String packageName = riTargetUser.activityInfo.packageName;
6863            PackageSetting ps = mSettings.mPackages.get(packageName);
6864            if (ps == null) {
6865                continue;
6866            }
6867            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6868            int status = (int)(verificationState >> 32);
6869            if (result == null) {
6870                result = new CrossProfileDomainInfo();
6871                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6872                        sourceUserId, parentUserId);
6873                result.bestDomainVerificationStatus = status;
6874            } else {
6875                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6876                        result.bestDomainVerificationStatus);
6877            }
6878        }
6879        // Don't consider matches with status NEVER across profiles.
6880        if (result != null && result.bestDomainVerificationStatus
6881                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6882            return null;
6883        }
6884        return result;
6885    }
6886
6887    /**
6888     * Verification statuses are ordered from the worse to the best, except for
6889     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6890     */
6891    private int bestDomainVerificationStatus(int status1, int status2) {
6892        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6893            return status2;
6894        }
6895        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6896            return status1;
6897        }
6898        return (int) MathUtils.max(status1, status2);
6899    }
6900
6901    private boolean isUserEnabled(int userId) {
6902        long callingId = Binder.clearCallingIdentity();
6903        try {
6904            UserInfo userInfo = sUserManager.getUserInfo(userId);
6905            return userInfo != null && userInfo.isEnabled();
6906        } finally {
6907            Binder.restoreCallingIdentity(callingId);
6908        }
6909    }
6910
6911    /**
6912     * Filter out activities with systemUserOnly flag set, when current user is not System.
6913     *
6914     * @return filtered list
6915     */
6916    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6917        if (userId == UserHandle.USER_SYSTEM) {
6918            return resolveInfos;
6919        }
6920        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6921            ResolveInfo info = resolveInfos.get(i);
6922            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6923                resolveInfos.remove(i);
6924            }
6925        }
6926        return resolveInfos;
6927    }
6928
6929    /**
6930     * Filters out ephemeral activities.
6931     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6932     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6933     *
6934     * @param resolveInfos The pre-filtered list of resolved activities
6935     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6936     *          is performed.
6937     * @param intent
6938     * @return A filtered list of resolved activities.
6939     */
6940    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6941            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId,
6942            Intent intent) {
6943        final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled();
6944        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6945            final ResolveInfo info = resolveInfos.get(i);
6946            // remove locally resolved instant app web results when disabled
6947            if (info.isInstantAppAvailable && blockInstant) {
6948                resolveInfos.remove(i);
6949                continue;
6950            }
6951            // allow activities that are defined in the provided package
6952            if (allowDynamicSplits
6953                    && info.activityInfo != null
6954                    && info.activityInfo.splitName != null
6955                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6956                            info.activityInfo.splitName)) {
6957                if (mInstantAppInstallerActivity == null) {
6958                    if (DEBUG_INSTALL) {
6959                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6960                    }
6961                    resolveInfos.remove(i);
6962                    continue;
6963                }
6964                if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) {
6965                    resolveInfos.remove(i);
6966                    continue;
6967                }
6968                // requested activity is defined in a split that hasn't been installed yet.
6969                // add the installer to the resolve list
6970                if (DEBUG_INSTALL) {
6971                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6972                }
6973                final ResolveInfo installerInfo = new ResolveInfo(
6974                        mInstantAppInstallerInfo);
6975                final ComponentName installFailureActivity = findInstallFailureActivity(
6976                        info.activityInfo.packageName,  filterCallingUid, userId);
6977                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6978                        installFailureActivity,
6979                        info.activityInfo.packageName,
6980                        info.activityInfo.applicationInfo.longVersionCode,
6981                        info.activityInfo.splitName);
6982                // add a non-generic filter
6983                installerInfo.filter = new IntentFilter();
6984
6985                // This resolve info may appear in the chooser UI, so let us make it
6986                // look as the one it replaces as far as the user is concerned which
6987                // requires loading the correct label and icon for the resolve info.
6988                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6989                installerInfo.labelRes = info.resolveLabelResId();
6990                installerInfo.icon = info.resolveIconResId();
6991                installerInfo.isInstantAppAvailable = true;
6992                resolveInfos.set(i, installerInfo);
6993                continue;
6994            }
6995            // caller is a full app, don't need to apply any other filtering
6996            if (ephemeralPkgName == null) {
6997                continue;
6998            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6999                // caller is same app; don't need to apply any other filtering
7000                continue;
7001            }
7002            // allow activities that have been explicitly exposed to ephemeral apps
7003            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7004            if (!isEphemeralApp
7005                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7006                continue;
7007            }
7008            resolveInfos.remove(i);
7009        }
7010        return resolveInfos;
7011    }
7012
7013    /**
7014     * Returns the activity component that can handle install failures.
7015     * <p>By default, the instant application installer handles failures. However, an
7016     * application may want to handle failures on its own. Applications do this by
7017     * creating an activity with an intent filter that handles the action
7018     * {@link Intent#ACTION_INSTALL_FAILURE}.
7019     */
7020    private @Nullable ComponentName findInstallFailureActivity(
7021            String packageName, int filterCallingUid, int userId) {
7022        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7023        failureActivityIntent.setPackage(packageName);
7024        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7025        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7026                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7027                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7028        final int NR = result.size();
7029        if (NR > 0) {
7030            for (int i = 0; i < NR; i++) {
7031                final ResolveInfo info = result.get(i);
7032                if (info.activityInfo.splitName != null) {
7033                    continue;
7034                }
7035                return new ComponentName(packageName, info.activityInfo.name);
7036            }
7037        }
7038        return null;
7039    }
7040
7041    /**
7042     * @param resolveInfos list of resolve infos in descending priority order
7043     * @return if the list contains a resolve info with non-negative priority
7044     */
7045    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7046        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7047    }
7048
7049    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7050            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7051            int userId) {
7052        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7053
7054        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7055            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7056                    candidates.size());
7057        }
7058
7059        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7060        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7061        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7062        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7063        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7064        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7065
7066        synchronized (mPackages) {
7067            final int count = candidates.size();
7068            // First, try to use linked apps. Partition the candidates into four lists:
7069            // one for the final results, one for the "do not use ever", one for "undefined status"
7070            // and finally one for "browser app type".
7071            for (int n=0; n<count; n++) {
7072                ResolveInfo info = candidates.get(n);
7073                String packageName = info.activityInfo.packageName;
7074                PackageSetting ps = mSettings.mPackages.get(packageName);
7075                if (ps != null) {
7076                    // Add to the special match all list (Browser use case)
7077                    if (info.handleAllWebDataURI) {
7078                        matchAllList.add(info);
7079                        continue;
7080                    }
7081                    // Try to get the status from User settings first
7082                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7083                    int status = (int)(packedStatus >> 32);
7084                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7085                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7086                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7087                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7088                                    + " : linkgen=" + linkGeneration);
7089                        }
7090                        // Use link-enabled generation as preferredOrder, i.e.
7091                        // prefer newly-enabled over earlier-enabled.
7092                        info.preferredOrder = linkGeneration;
7093                        alwaysList.add(info);
7094                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7095                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7096                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7097                        }
7098                        neverList.add(info);
7099                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7100                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7101                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7102                        }
7103                        alwaysAskList.add(info);
7104                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7105                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7106                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7107                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7108                        }
7109                        undefinedList.add(info);
7110                    }
7111                }
7112            }
7113
7114            // We'll want to include browser possibilities in a few cases
7115            boolean includeBrowser = false;
7116
7117            // First try to add the "always" resolution(s) for the current user, if any
7118            if (alwaysList.size() > 0) {
7119                result.addAll(alwaysList);
7120            } else {
7121                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7122                result.addAll(undefinedList);
7123                // Maybe add one for the other profile.
7124                if (xpDomainInfo != null && (
7125                        xpDomainInfo.bestDomainVerificationStatus
7126                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7127                    result.add(xpDomainInfo.resolveInfo);
7128                }
7129                includeBrowser = true;
7130            }
7131
7132            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7133            // If there were 'always' entries their preferred order has been set, so we also
7134            // back that off to make the alternatives equivalent
7135            if (alwaysAskList.size() > 0) {
7136                for (ResolveInfo i : result) {
7137                    i.preferredOrder = 0;
7138                }
7139                result.addAll(alwaysAskList);
7140                includeBrowser = true;
7141            }
7142
7143            if (includeBrowser) {
7144                // Also add browsers (all of them or only the default one)
7145                if (DEBUG_DOMAIN_VERIFICATION) {
7146                    Slog.v(TAG, "   ...including browsers in candidate set");
7147                }
7148                if ((matchFlags & MATCH_ALL) != 0) {
7149                    result.addAll(matchAllList);
7150                } else {
7151                    // Browser/generic handling case.  If there's a default browser, go straight
7152                    // to that (but only if there is no other higher-priority match).
7153                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7154                    int maxMatchPrio = 0;
7155                    ResolveInfo defaultBrowserMatch = null;
7156                    final int numCandidates = matchAllList.size();
7157                    for (int n = 0; n < numCandidates; n++) {
7158                        ResolveInfo info = matchAllList.get(n);
7159                        // track the highest overall match priority...
7160                        if (info.priority > maxMatchPrio) {
7161                            maxMatchPrio = info.priority;
7162                        }
7163                        // ...and the highest-priority default browser match
7164                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7165                            if (defaultBrowserMatch == null
7166                                    || (defaultBrowserMatch.priority < info.priority)) {
7167                                if (debug) {
7168                                    Slog.v(TAG, "Considering default browser match " + info);
7169                                }
7170                                defaultBrowserMatch = info;
7171                            }
7172                        }
7173                    }
7174                    if (defaultBrowserMatch != null
7175                            && defaultBrowserMatch.priority >= maxMatchPrio
7176                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7177                    {
7178                        if (debug) {
7179                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7180                        }
7181                        result.add(defaultBrowserMatch);
7182                    } else {
7183                        result.addAll(matchAllList);
7184                    }
7185                }
7186
7187                // If there is nothing selected, add all candidates and remove the ones that the user
7188                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7189                if (result.size() == 0) {
7190                    result.addAll(candidates);
7191                    result.removeAll(neverList);
7192                }
7193            }
7194        }
7195        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7196            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7197                    result.size());
7198            for (ResolveInfo info : result) {
7199                Slog.v(TAG, "  + " + info.activityInfo);
7200            }
7201        }
7202        return result;
7203    }
7204
7205    // Returns a packed value as a long:
7206    //
7207    // high 'int'-sized word: link status: undefined/ask/never/always.
7208    // low 'int'-sized word: relative priority among 'always' results.
7209    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7210        long result = ps.getDomainVerificationStatusForUser(userId);
7211        // if none available, get the master status
7212        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7213            if (ps.getIntentFilterVerificationInfo() != null) {
7214                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7215            }
7216        }
7217        return result;
7218    }
7219
7220    private ResolveInfo querySkipCurrentProfileIntents(
7221            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7222            int flags, int sourceUserId) {
7223        if (matchingFilters != null) {
7224            int size = matchingFilters.size();
7225            for (int i = 0; i < size; i ++) {
7226                CrossProfileIntentFilter filter = matchingFilters.get(i);
7227                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7228                    // Checking if there are activities in the target user that can handle the
7229                    // intent.
7230                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7231                            resolvedType, flags, sourceUserId);
7232                    if (resolveInfo != null) {
7233                        return resolveInfo;
7234                    }
7235                }
7236            }
7237        }
7238        return null;
7239    }
7240
7241    // Return matching ResolveInfo in target user if any.
7242    private ResolveInfo queryCrossProfileIntents(
7243            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7244            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7245        if (matchingFilters != null) {
7246            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7247            // match the same intent. For performance reasons, it is better not to
7248            // run queryIntent twice for the same userId
7249            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7250            int size = matchingFilters.size();
7251            for (int i = 0; i < size; i++) {
7252                CrossProfileIntentFilter filter = matchingFilters.get(i);
7253                int targetUserId = filter.getTargetUserId();
7254                boolean skipCurrentProfile =
7255                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7256                boolean skipCurrentProfileIfNoMatchFound =
7257                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7258                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7259                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7260                    // Checking if there are activities in the target user that can handle the
7261                    // intent.
7262                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7263                            resolvedType, flags, sourceUserId);
7264                    if (resolveInfo != null) return resolveInfo;
7265                    alreadyTriedUserIds.put(targetUserId, true);
7266                }
7267            }
7268        }
7269        return null;
7270    }
7271
7272    /**
7273     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7274     * will forward the intent to the filter's target user.
7275     * Otherwise, returns null.
7276     */
7277    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7278            String resolvedType, int flags, int sourceUserId) {
7279        int targetUserId = filter.getTargetUserId();
7280        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7281                resolvedType, flags, targetUserId);
7282        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7283            // If all the matches in the target profile are suspended, return null.
7284            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7285                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7286                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7287                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7288                            targetUserId);
7289                }
7290            }
7291        }
7292        return null;
7293    }
7294
7295    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7296            int sourceUserId, int targetUserId) {
7297        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7298        long ident = Binder.clearCallingIdentity();
7299        boolean targetIsProfile;
7300        try {
7301            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7302        } finally {
7303            Binder.restoreCallingIdentity(ident);
7304        }
7305        String className;
7306        if (targetIsProfile) {
7307            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7308        } else {
7309            className = FORWARD_INTENT_TO_PARENT;
7310        }
7311        ComponentName forwardingActivityComponentName = new ComponentName(
7312                mAndroidApplication.packageName, className);
7313        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7314                sourceUserId);
7315        if (!targetIsProfile) {
7316            forwardingActivityInfo.showUserIcon = targetUserId;
7317            forwardingResolveInfo.noResourceId = true;
7318        }
7319        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7320        forwardingResolveInfo.priority = 0;
7321        forwardingResolveInfo.preferredOrder = 0;
7322        forwardingResolveInfo.match = 0;
7323        forwardingResolveInfo.isDefault = true;
7324        forwardingResolveInfo.filter = filter;
7325        forwardingResolveInfo.targetUserId = targetUserId;
7326        return forwardingResolveInfo;
7327    }
7328
7329    @Override
7330    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7331            Intent[] specifics, String[] specificTypes, Intent intent,
7332            String resolvedType, int flags, int userId) {
7333        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7334                specificTypes, intent, resolvedType, flags, userId));
7335    }
7336
7337    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7338            Intent[] specifics, String[] specificTypes, Intent intent,
7339            String resolvedType, int flags, int userId) {
7340        if (!sUserManager.exists(userId)) return Collections.emptyList();
7341        final int callingUid = Binder.getCallingUid();
7342        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7343                false /*includeInstantApps*/);
7344        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7345                false /*requireFullPermission*/, false /*checkShell*/,
7346                "query intent activity options");
7347        final String resultsAction = intent.getAction();
7348
7349        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7350                | PackageManager.GET_RESOLVED_FILTER, userId);
7351
7352        if (DEBUG_INTENT_MATCHING) {
7353            Log.v(TAG, "Query " + intent + ": " + results);
7354        }
7355
7356        int specificsPos = 0;
7357        int N;
7358
7359        // todo: note that the algorithm used here is O(N^2).  This
7360        // isn't a problem in our current environment, but if we start running
7361        // into situations where we have more than 5 or 10 matches then this
7362        // should probably be changed to something smarter...
7363
7364        // First we go through and resolve each of the specific items
7365        // that were supplied, taking care of removing any corresponding
7366        // duplicate items in the generic resolve list.
7367        if (specifics != null) {
7368            for (int i=0; i<specifics.length; i++) {
7369                final Intent sintent = specifics[i];
7370                if (sintent == null) {
7371                    continue;
7372                }
7373
7374                if (DEBUG_INTENT_MATCHING) {
7375                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7376                }
7377
7378                String action = sintent.getAction();
7379                if (resultsAction != null && resultsAction.equals(action)) {
7380                    // If this action was explicitly requested, then don't
7381                    // remove things that have it.
7382                    action = null;
7383                }
7384
7385                ResolveInfo ri = null;
7386                ActivityInfo ai = null;
7387
7388                ComponentName comp = sintent.getComponent();
7389                if (comp == null) {
7390                    ri = resolveIntent(
7391                        sintent,
7392                        specificTypes != null ? specificTypes[i] : null,
7393                            flags, userId);
7394                    if (ri == null) {
7395                        continue;
7396                    }
7397                    if (ri == mResolveInfo) {
7398                        // ACK!  Must do something better with this.
7399                    }
7400                    ai = ri.activityInfo;
7401                    comp = new ComponentName(ai.applicationInfo.packageName,
7402                            ai.name);
7403                } else {
7404                    ai = getActivityInfo(comp, flags, userId);
7405                    if (ai == null) {
7406                        continue;
7407                    }
7408                }
7409
7410                // Look for any generic query activities that are duplicates
7411                // of this specific one, and remove them from the results.
7412                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7413                N = results.size();
7414                int j;
7415                for (j=specificsPos; j<N; j++) {
7416                    ResolveInfo sri = results.get(j);
7417                    if ((sri.activityInfo.name.equals(comp.getClassName())
7418                            && sri.activityInfo.applicationInfo.packageName.equals(
7419                                    comp.getPackageName()))
7420                        || (action != null && sri.filter.matchAction(action))) {
7421                        results.remove(j);
7422                        if (DEBUG_INTENT_MATCHING) Log.v(
7423                            TAG, "Removing duplicate item from " + j
7424                            + " due to specific " + specificsPos);
7425                        if (ri == null) {
7426                            ri = sri;
7427                        }
7428                        j--;
7429                        N--;
7430                    }
7431                }
7432
7433                // Add this specific item to its proper place.
7434                if (ri == null) {
7435                    ri = new ResolveInfo();
7436                    ri.activityInfo = ai;
7437                }
7438                results.add(specificsPos, ri);
7439                ri.specificIndex = i;
7440                specificsPos++;
7441            }
7442        }
7443
7444        // Now we go through the remaining generic results and remove any
7445        // duplicate actions that are found here.
7446        N = results.size();
7447        for (int i=specificsPos; i<N-1; i++) {
7448            final ResolveInfo rii = results.get(i);
7449            if (rii.filter == null) {
7450                continue;
7451            }
7452
7453            // Iterate over all of the actions of this result's intent
7454            // filter...  typically this should be just one.
7455            final Iterator<String> it = rii.filter.actionsIterator();
7456            if (it == null) {
7457                continue;
7458            }
7459            while (it.hasNext()) {
7460                final String action = it.next();
7461                if (resultsAction != null && resultsAction.equals(action)) {
7462                    // If this action was explicitly requested, then don't
7463                    // remove things that have it.
7464                    continue;
7465                }
7466                for (int j=i+1; j<N; j++) {
7467                    final ResolveInfo rij = results.get(j);
7468                    if (rij.filter != null && rij.filter.hasAction(action)) {
7469                        results.remove(j);
7470                        if (DEBUG_INTENT_MATCHING) Log.v(
7471                            TAG, "Removing duplicate item from " + j
7472                            + " due to action " + action + " at " + i);
7473                        j--;
7474                        N--;
7475                    }
7476                }
7477            }
7478
7479            // If the caller didn't request filter information, drop it now
7480            // so we don't have to marshall/unmarshall it.
7481            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7482                rii.filter = null;
7483            }
7484        }
7485
7486        // Filter out the caller activity if so requested.
7487        if (caller != null) {
7488            N = results.size();
7489            for (int i=0; i<N; i++) {
7490                ActivityInfo ainfo = results.get(i).activityInfo;
7491                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7492                        && caller.getClassName().equals(ainfo.name)) {
7493                    results.remove(i);
7494                    break;
7495                }
7496            }
7497        }
7498
7499        // If the caller didn't request filter information,
7500        // drop them now so we don't have to
7501        // marshall/unmarshall it.
7502        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7503            N = results.size();
7504            for (int i=0; i<N; i++) {
7505                results.get(i).filter = null;
7506            }
7507        }
7508
7509        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7510        return results;
7511    }
7512
7513    @Override
7514    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7515            String resolvedType, int flags, int userId) {
7516        return new ParceledListSlice<>(
7517                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7518                        false /*allowDynamicSplits*/));
7519    }
7520
7521    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7522            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7523        if (!sUserManager.exists(userId)) return Collections.emptyList();
7524        final int callingUid = Binder.getCallingUid();
7525        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7526                false /*requireFullPermission*/, false /*checkShell*/,
7527                "query intent receivers");
7528        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7529        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7530                false /*includeInstantApps*/);
7531        ComponentName comp = intent.getComponent();
7532        if (comp == null) {
7533            if (intent.getSelector() != null) {
7534                intent = intent.getSelector();
7535                comp = intent.getComponent();
7536            }
7537        }
7538        if (comp != null) {
7539            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7540            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7541            if (ai != null) {
7542                // When specifying an explicit component, we prevent the activity from being
7543                // used when either 1) the calling package is normal and the activity is within
7544                // an instant application or 2) the calling package is ephemeral and the
7545                // activity is not visible to instant applications.
7546                final boolean matchInstantApp =
7547                        (flags & PackageManager.MATCH_INSTANT) != 0;
7548                final boolean matchVisibleToInstantAppOnly =
7549                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7550                final boolean matchExplicitlyVisibleOnly =
7551                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7552                final boolean isCallerInstantApp =
7553                        instantAppPkgName != null;
7554                final boolean isTargetSameInstantApp =
7555                        comp.getPackageName().equals(instantAppPkgName);
7556                final boolean isTargetInstantApp =
7557                        (ai.applicationInfo.privateFlags
7558                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7559                final boolean isTargetVisibleToInstantApp =
7560                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7561                final boolean isTargetExplicitlyVisibleToInstantApp =
7562                        isTargetVisibleToInstantApp
7563                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7564                final boolean isTargetHiddenFromInstantApp =
7565                        !isTargetVisibleToInstantApp
7566                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7567                final boolean blockResolution =
7568                        !isTargetSameInstantApp
7569                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7570                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7571                                        && isTargetHiddenFromInstantApp));
7572                if (!blockResolution) {
7573                    ResolveInfo ri = new ResolveInfo();
7574                    ri.activityInfo = ai;
7575                    list.add(ri);
7576                }
7577            }
7578            return applyPostResolutionFilter(
7579                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7580        }
7581
7582        // reader
7583        synchronized (mPackages) {
7584            String pkgName = intent.getPackage();
7585            if (pkgName == null) {
7586                final List<ResolveInfo> result =
7587                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7588                return applyPostResolutionFilter(
7589                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7590            }
7591            final PackageParser.Package pkg = mPackages.get(pkgName);
7592            if (pkg != null) {
7593                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7594                        intent, resolvedType, flags, pkg.receivers, userId);
7595                return applyPostResolutionFilter(
7596                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7597            }
7598            return Collections.emptyList();
7599        }
7600    }
7601
7602    @Override
7603    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7604        final int callingUid = Binder.getCallingUid();
7605        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7606    }
7607
7608    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7609            int userId, int callingUid) {
7610        if (!sUserManager.exists(userId)) return null;
7611        flags = updateFlagsForResolve(
7612                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7613        List<ResolveInfo> query = queryIntentServicesInternal(
7614                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7615        if (query != null) {
7616            if (query.size() >= 1) {
7617                // If there is more than one service with the same priority,
7618                // just arbitrarily pick the first one.
7619                return query.get(0);
7620            }
7621        }
7622        return null;
7623    }
7624
7625    @Override
7626    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7627            String resolvedType, int flags, int userId) {
7628        final int callingUid = Binder.getCallingUid();
7629        return new ParceledListSlice<>(queryIntentServicesInternal(
7630                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7631    }
7632
7633    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7634            String resolvedType, int flags, int userId, int callingUid,
7635            boolean includeInstantApps) {
7636        if (!sUserManager.exists(userId)) return Collections.emptyList();
7637        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7638                false /*requireFullPermission*/, false /*checkShell*/,
7639                "query intent receivers");
7640        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7641        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7642        ComponentName comp = intent.getComponent();
7643        if (comp == null) {
7644            if (intent.getSelector() != null) {
7645                intent = intent.getSelector();
7646                comp = intent.getComponent();
7647            }
7648        }
7649        if (comp != null) {
7650            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7651            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7652            if (si != null) {
7653                // When specifying an explicit component, we prevent the service from being
7654                // used when either 1) the service is in an instant application and the
7655                // caller is not the same instant application or 2) the calling package is
7656                // ephemeral and the activity is not visible to ephemeral applications.
7657                final boolean matchInstantApp =
7658                        (flags & PackageManager.MATCH_INSTANT) != 0;
7659                final boolean matchVisibleToInstantAppOnly =
7660                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7661                final boolean isCallerInstantApp =
7662                        instantAppPkgName != null;
7663                final boolean isTargetSameInstantApp =
7664                        comp.getPackageName().equals(instantAppPkgName);
7665                final boolean isTargetInstantApp =
7666                        (si.applicationInfo.privateFlags
7667                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7668                final boolean isTargetHiddenFromInstantApp =
7669                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7670                final boolean blockResolution =
7671                        !isTargetSameInstantApp
7672                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7673                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7674                                        && isTargetHiddenFromInstantApp));
7675                if (!blockResolution) {
7676                    final ResolveInfo ri = new ResolveInfo();
7677                    ri.serviceInfo = si;
7678                    list.add(ri);
7679                }
7680            }
7681            return list;
7682        }
7683
7684        // reader
7685        synchronized (mPackages) {
7686            String pkgName = intent.getPackage();
7687            if (pkgName == null) {
7688                return applyPostServiceResolutionFilter(
7689                        mServices.queryIntent(intent, resolvedType, flags, userId),
7690                        instantAppPkgName);
7691            }
7692            final PackageParser.Package pkg = mPackages.get(pkgName);
7693            if (pkg != null) {
7694                return applyPostServiceResolutionFilter(
7695                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7696                                userId),
7697                        instantAppPkgName);
7698            }
7699            return Collections.emptyList();
7700        }
7701    }
7702
7703    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7704            String instantAppPkgName) {
7705        if (instantAppPkgName == null) {
7706            return resolveInfos;
7707        }
7708        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7709            final ResolveInfo info = resolveInfos.get(i);
7710            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7711            // allow services that are defined in the provided package
7712            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7713                if (info.serviceInfo.splitName != null
7714                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7715                                info.serviceInfo.splitName)) {
7716                    // requested service is defined in a split that hasn't been installed yet.
7717                    // add the installer to the resolve list
7718                    if (DEBUG_INSTANT) {
7719                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7720                    }
7721                    final ResolveInfo installerInfo = new ResolveInfo(
7722                            mInstantAppInstallerInfo);
7723                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7724                            null /* installFailureActivity */,
7725                            info.serviceInfo.packageName,
7726                            info.serviceInfo.applicationInfo.longVersionCode,
7727                            info.serviceInfo.splitName);
7728                    // add a non-generic filter
7729                    installerInfo.filter = new IntentFilter();
7730                    // load resources from the correct package
7731                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7732                    resolveInfos.set(i, installerInfo);
7733                }
7734                continue;
7735            }
7736            // allow services that have been explicitly exposed to ephemeral apps
7737            if (!isEphemeralApp
7738                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7739                continue;
7740            }
7741            resolveInfos.remove(i);
7742        }
7743        return resolveInfos;
7744    }
7745
7746    @Override
7747    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7748            String resolvedType, int flags, int userId) {
7749        return new ParceledListSlice<>(
7750                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7751    }
7752
7753    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7754            Intent intent, String resolvedType, int flags, int userId) {
7755        if (!sUserManager.exists(userId)) return Collections.emptyList();
7756        final int callingUid = Binder.getCallingUid();
7757        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7758        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7759                false /*includeInstantApps*/);
7760        ComponentName comp = intent.getComponent();
7761        if (comp == null) {
7762            if (intent.getSelector() != null) {
7763                intent = intent.getSelector();
7764                comp = intent.getComponent();
7765            }
7766        }
7767        if (comp != null) {
7768            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7769            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7770            if (pi != null) {
7771                // When specifying an explicit component, we prevent the provider from being
7772                // used when either 1) the provider is in an instant application and the
7773                // caller is not the same instant application or 2) the calling package is an
7774                // instant application and the provider is not visible to instant applications.
7775                final boolean matchInstantApp =
7776                        (flags & PackageManager.MATCH_INSTANT) != 0;
7777                final boolean matchVisibleToInstantAppOnly =
7778                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7779                final boolean isCallerInstantApp =
7780                        instantAppPkgName != null;
7781                final boolean isTargetSameInstantApp =
7782                        comp.getPackageName().equals(instantAppPkgName);
7783                final boolean isTargetInstantApp =
7784                        (pi.applicationInfo.privateFlags
7785                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7786                final boolean isTargetHiddenFromInstantApp =
7787                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7788                final boolean blockResolution =
7789                        !isTargetSameInstantApp
7790                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7791                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7792                                        && isTargetHiddenFromInstantApp));
7793                if (!blockResolution) {
7794                    final ResolveInfo ri = new ResolveInfo();
7795                    ri.providerInfo = pi;
7796                    list.add(ri);
7797                }
7798            }
7799            return list;
7800        }
7801
7802        // reader
7803        synchronized (mPackages) {
7804            String pkgName = intent.getPackage();
7805            if (pkgName == null) {
7806                return applyPostContentProviderResolutionFilter(
7807                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7808                        instantAppPkgName);
7809            }
7810            final PackageParser.Package pkg = mPackages.get(pkgName);
7811            if (pkg != null) {
7812                return applyPostContentProviderResolutionFilter(
7813                        mProviders.queryIntentForPackage(
7814                        intent, resolvedType, flags, pkg.providers, userId),
7815                        instantAppPkgName);
7816            }
7817            return Collections.emptyList();
7818        }
7819    }
7820
7821    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7822            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7823        if (instantAppPkgName == null) {
7824            return resolveInfos;
7825        }
7826        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7827            final ResolveInfo info = resolveInfos.get(i);
7828            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7829            // allow providers that are defined in the provided package
7830            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7831                if (info.providerInfo.splitName != null
7832                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7833                                info.providerInfo.splitName)) {
7834                    // requested provider is defined in a split that hasn't been installed yet.
7835                    // add the installer to the resolve list
7836                    if (DEBUG_INSTANT) {
7837                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7838                    }
7839                    final ResolveInfo installerInfo = new ResolveInfo(
7840                            mInstantAppInstallerInfo);
7841                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7842                            null /*failureActivity*/,
7843                            info.providerInfo.packageName,
7844                            info.providerInfo.applicationInfo.longVersionCode,
7845                            info.providerInfo.splitName);
7846                    // add a non-generic filter
7847                    installerInfo.filter = new IntentFilter();
7848                    // load resources from the correct package
7849                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7850                    resolveInfos.set(i, installerInfo);
7851                }
7852                continue;
7853            }
7854            // allow providers that have been explicitly exposed to instant applications
7855            if (!isEphemeralApp
7856                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7857                continue;
7858            }
7859            resolveInfos.remove(i);
7860        }
7861        return resolveInfos;
7862    }
7863
7864    @Override
7865    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7866        final int callingUid = Binder.getCallingUid();
7867        if (getInstantAppPackageName(callingUid) != null) {
7868            return ParceledListSlice.emptyList();
7869        }
7870        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7871        flags = updateFlagsForPackage(flags, userId, null);
7872        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7873        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7874                true /* requireFullPermission */, false /* checkShell */,
7875                "get installed packages");
7876
7877        // writer
7878        synchronized (mPackages) {
7879            ArrayList<PackageInfo> list;
7880            if (listUninstalled) {
7881                list = new ArrayList<>(mSettings.mPackages.size());
7882                for (PackageSetting ps : mSettings.mPackages.values()) {
7883                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7884                        continue;
7885                    }
7886                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7887                        continue;
7888                    }
7889                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7890                    if (pi != null) {
7891                        list.add(pi);
7892                    }
7893                }
7894            } else {
7895                list = new ArrayList<>(mPackages.size());
7896                for (PackageParser.Package p : mPackages.values()) {
7897                    final PackageSetting ps = (PackageSetting) p.mExtras;
7898                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7899                        continue;
7900                    }
7901                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7902                        continue;
7903                    }
7904                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7905                            p.mExtras, flags, userId);
7906                    if (pi != null) {
7907                        list.add(pi);
7908                    }
7909                }
7910            }
7911
7912            return new ParceledListSlice<>(list);
7913        }
7914    }
7915
7916    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7917            String[] permissions, boolean[] tmp, int flags, int userId) {
7918        int numMatch = 0;
7919        final PermissionsState permissionsState = ps.getPermissionsState();
7920        for (int i=0; i<permissions.length; i++) {
7921            final String permission = permissions[i];
7922            if (permissionsState.hasPermission(permission, userId)) {
7923                tmp[i] = true;
7924                numMatch++;
7925            } else {
7926                tmp[i] = false;
7927            }
7928        }
7929        if (numMatch == 0) {
7930            return;
7931        }
7932        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7933
7934        // The above might return null in cases of uninstalled apps or install-state
7935        // skew across users/profiles.
7936        if (pi != null) {
7937            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7938                if (numMatch == permissions.length) {
7939                    pi.requestedPermissions = permissions;
7940                } else {
7941                    pi.requestedPermissions = new String[numMatch];
7942                    numMatch = 0;
7943                    for (int i=0; i<permissions.length; i++) {
7944                        if (tmp[i]) {
7945                            pi.requestedPermissions[numMatch] = permissions[i];
7946                            numMatch++;
7947                        }
7948                    }
7949                }
7950            }
7951            list.add(pi);
7952        }
7953    }
7954
7955    @Override
7956    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7957            String[] permissions, int flags, int userId) {
7958        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7959        flags = updateFlagsForPackage(flags, userId, permissions);
7960        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7961                true /* requireFullPermission */, false /* checkShell */,
7962                "get packages holding permissions");
7963        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7964
7965        // writer
7966        synchronized (mPackages) {
7967            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7968            boolean[] tmpBools = new boolean[permissions.length];
7969            if (listUninstalled) {
7970                for (PackageSetting ps : mSettings.mPackages.values()) {
7971                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7972                            userId);
7973                }
7974            } else {
7975                for (PackageParser.Package pkg : mPackages.values()) {
7976                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7977                    if (ps != null) {
7978                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7979                                userId);
7980                    }
7981                }
7982            }
7983
7984            return new ParceledListSlice<PackageInfo>(list);
7985        }
7986    }
7987
7988    @Override
7989    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7990        final int callingUid = Binder.getCallingUid();
7991        if (getInstantAppPackageName(callingUid) != null) {
7992            return ParceledListSlice.emptyList();
7993        }
7994        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7995        flags = updateFlagsForApplication(flags, userId, null);
7996        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7997
7998        // writer
7999        synchronized (mPackages) {
8000            ArrayList<ApplicationInfo> list;
8001            if (listUninstalled) {
8002                list = new ArrayList<>(mSettings.mPackages.size());
8003                for (PackageSetting ps : mSettings.mPackages.values()) {
8004                    ApplicationInfo ai;
8005                    int effectiveFlags = flags;
8006                    if (ps.isSystem()) {
8007                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8008                    }
8009                    if (ps.pkg != null) {
8010                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8011                            continue;
8012                        }
8013                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8014                            continue;
8015                        }
8016                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8017                                ps.readUserState(userId), userId);
8018                        if (ai != null) {
8019                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8020                        }
8021                    } else {
8022                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8023                        // and already converts to externally visible package name
8024                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8025                                callingUid, effectiveFlags, userId);
8026                    }
8027                    if (ai != null) {
8028                        list.add(ai);
8029                    }
8030                }
8031            } else {
8032                list = new ArrayList<>(mPackages.size());
8033                for (PackageParser.Package p : mPackages.values()) {
8034                    if (p.mExtras != null) {
8035                        PackageSetting ps = (PackageSetting) p.mExtras;
8036                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8037                            continue;
8038                        }
8039                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8040                            continue;
8041                        }
8042                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8043                                ps.readUserState(userId), userId);
8044                        if (ai != null) {
8045                            ai.packageName = resolveExternalPackageNameLPr(p);
8046                            list.add(ai);
8047                        }
8048                    }
8049                }
8050            }
8051
8052            return new ParceledListSlice<>(list);
8053        }
8054    }
8055
8056    @Override
8057    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8058        if (HIDE_EPHEMERAL_APIS) {
8059            return null;
8060        }
8061        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8062            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8063                    "getEphemeralApplications");
8064        }
8065        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8066                true /* requireFullPermission */, false /* checkShell */,
8067                "getEphemeralApplications");
8068        synchronized (mPackages) {
8069            List<InstantAppInfo> instantApps = mInstantAppRegistry
8070                    .getInstantAppsLPr(userId);
8071            if (instantApps != null) {
8072                return new ParceledListSlice<>(instantApps);
8073            }
8074        }
8075        return null;
8076    }
8077
8078    @Override
8079    public boolean isInstantApp(String packageName, int userId) {
8080        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8081                true /* requireFullPermission */, false /* checkShell */,
8082                "isInstantApp");
8083        if (HIDE_EPHEMERAL_APIS) {
8084            return false;
8085        }
8086
8087        synchronized (mPackages) {
8088            int callingUid = Binder.getCallingUid();
8089            if (Process.isIsolated(callingUid)) {
8090                callingUid = mIsolatedOwners.get(callingUid);
8091            }
8092            final PackageSetting ps = mSettings.mPackages.get(packageName);
8093            PackageParser.Package pkg = mPackages.get(packageName);
8094            final boolean returnAllowed =
8095                    ps != null
8096                    && (isCallerSameApp(packageName, callingUid)
8097                            || canViewInstantApps(callingUid, userId)
8098                            || mInstantAppRegistry.isInstantAccessGranted(
8099                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8100            if (returnAllowed) {
8101                return ps.getInstantApp(userId);
8102            }
8103        }
8104        return false;
8105    }
8106
8107    @Override
8108    public byte[] getInstantAppCookie(String packageName, int userId) {
8109        if (HIDE_EPHEMERAL_APIS) {
8110            return null;
8111        }
8112
8113        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8114                true /* requireFullPermission */, false /* checkShell */,
8115                "getInstantAppCookie");
8116        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8117            return null;
8118        }
8119        synchronized (mPackages) {
8120            return mInstantAppRegistry.getInstantAppCookieLPw(
8121                    packageName, userId);
8122        }
8123    }
8124
8125    @Override
8126    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8127        if (HIDE_EPHEMERAL_APIS) {
8128            return true;
8129        }
8130
8131        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8132                true /* requireFullPermission */, true /* checkShell */,
8133                "setInstantAppCookie");
8134        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8135            return false;
8136        }
8137        synchronized (mPackages) {
8138            return mInstantAppRegistry.setInstantAppCookieLPw(
8139                    packageName, cookie, userId);
8140        }
8141    }
8142
8143    @Override
8144    public Bitmap getInstantAppIcon(String packageName, int userId) {
8145        if (HIDE_EPHEMERAL_APIS) {
8146            return null;
8147        }
8148
8149        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8150            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8151                    "getInstantAppIcon");
8152        }
8153        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8154                true /* requireFullPermission */, false /* checkShell */,
8155                "getInstantAppIcon");
8156
8157        synchronized (mPackages) {
8158            return mInstantAppRegistry.getInstantAppIconLPw(
8159                    packageName, userId);
8160        }
8161    }
8162
8163    private boolean isCallerSameApp(String packageName, int uid) {
8164        PackageParser.Package pkg = mPackages.get(packageName);
8165        return pkg != null
8166                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8167    }
8168
8169    @Override
8170    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8171        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8172            return ParceledListSlice.emptyList();
8173        }
8174        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8175    }
8176
8177    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8178        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8179
8180        // reader
8181        synchronized (mPackages) {
8182            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8183            final int userId = UserHandle.getCallingUserId();
8184            while (i.hasNext()) {
8185                final PackageParser.Package p = i.next();
8186                if (p.applicationInfo == null) continue;
8187
8188                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8189                        && !p.applicationInfo.isDirectBootAware();
8190                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8191                        && p.applicationInfo.isDirectBootAware();
8192
8193                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8194                        && (!mSafeMode || isSystemApp(p))
8195                        && (matchesUnaware || matchesAware)) {
8196                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8197                    if (ps != null) {
8198                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8199                                ps.readUserState(userId), userId);
8200                        if (ai != null) {
8201                            finalList.add(ai);
8202                        }
8203                    }
8204                }
8205            }
8206        }
8207
8208        return finalList;
8209    }
8210
8211    @Override
8212    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8213        return resolveContentProviderInternal(name, flags, userId);
8214    }
8215
8216    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8217        if (!sUserManager.exists(userId)) return null;
8218        flags = updateFlagsForComponent(flags, userId, name);
8219        final int callingUid = Binder.getCallingUid();
8220        synchronized (mPackages) {
8221            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8222            PackageSetting ps = provider != null
8223                    ? mSettings.mPackages.get(provider.owner.packageName)
8224                    : null;
8225            if (ps != null) {
8226                // provider not enabled
8227                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8228                    return null;
8229                }
8230                final ComponentName component =
8231                        new ComponentName(provider.info.packageName, provider.info.name);
8232                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8233                    return null;
8234                }
8235                return PackageParser.generateProviderInfo(
8236                        provider, flags, ps.readUserState(userId), userId);
8237            }
8238            return null;
8239        }
8240    }
8241
8242    /**
8243     * @deprecated
8244     */
8245    @Deprecated
8246    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8247        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8248            return;
8249        }
8250        // reader
8251        synchronized (mPackages) {
8252            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8253                    .entrySet().iterator();
8254            final int userId = UserHandle.getCallingUserId();
8255            while (i.hasNext()) {
8256                Map.Entry<String, PackageParser.Provider> entry = i.next();
8257                PackageParser.Provider p = entry.getValue();
8258                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8259
8260                if (ps != null && p.syncable
8261                        && (!mSafeMode || (p.info.applicationInfo.flags
8262                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8263                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8264                            ps.readUserState(userId), userId);
8265                    if (info != null) {
8266                        outNames.add(entry.getKey());
8267                        outInfo.add(info);
8268                    }
8269                }
8270            }
8271        }
8272    }
8273
8274    @Override
8275    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8276            int uid, int flags, String metaDataKey) {
8277        final int callingUid = Binder.getCallingUid();
8278        final int userId = processName != null ? UserHandle.getUserId(uid)
8279                : UserHandle.getCallingUserId();
8280        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8281        flags = updateFlagsForComponent(flags, userId, processName);
8282        ArrayList<ProviderInfo> finalList = null;
8283        // reader
8284        synchronized (mPackages) {
8285            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8286            while (i.hasNext()) {
8287                final PackageParser.Provider p = i.next();
8288                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8289                if (ps != null && p.info.authority != null
8290                        && (processName == null
8291                                || (p.info.processName.equals(processName)
8292                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8293                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8294
8295                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8296                    // parameter.
8297                    if (metaDataKey != null
8298                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8299                        continue;
8300                    }
8301                    final ComponentName component =
8302                            new ComponentName(p.info.packageName, p.info.name);
8303                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8304                        continue;
8305                    }
8306                    if (finalList == null) {
8307                        finalList = new ArrayList<ProviderInfo>(3);
8308                    }
8309                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8310                            ps.readUserState(userId), userId);
8311                    if (info != null) {
8312                        finalList.add(info);
8313                    }
8314                }
8315            }
8316        }
8317
8318        if (finalList != null) {
8319            Collections.sort(finalList, mProviderInitOrderSorter);
8320            return new ParceledListSlice<ProviderInfo>(finalList);
8321        }
8322
8323        return ParceledListSlice.emptyList();
8324    }
8325
8326    @Override
8327    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8328        // reader
8329        synchronized (mPackages) {
8330            final int callingUid = Binder.getCallingUid();
8331            final int callingUserId = UserHandle.getUserId(callingUid);
8332            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8333            if (ps == null) return null;
8334            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8335                return null;
8336            }
8337            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8338            return PackageParser.generateInstrumentationInfo(i, flags);
8339        }
8340    }
8341
8342    @Override
8343    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8344            String targetPackage, int flags) {
8345        final int callingUid = Binder.getCallingUid();
8346        final int callingUserId = UserHandle.getUserId(callingUid);
8347        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8348        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8349            return ParceledListSlice.emptyList();
8350        }
8351        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8352    }
8353
8354    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8355            int flags) {
8356        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8357
8358        // reader
8359        synchronized (mPackages) {
8360            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8361            while (i.hasNext()) {
8362                final PackageParser.Instrumentation p = i.next();
8363                if (targetPackage == null
8364                        || targetPackage.equals(p.info.targetPackage)) {
8365                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8366                            flags);
8367                    if (ii != null) {
8368                        finalList.add(ii);
8369                    }
8370                }
8371            }
8372        }
8373
8374        return finalList;
8375    }
8376
8377    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8378        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8379        try {
8380            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8381        } finally {
8382            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8383        }
8384    }
8385
8386    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8387        final File[] files = scanDir.listFiles();
8388        if (ArrayUtils.isEmpty(files)) {
8389            Log.d(TAG, "No files in app dir " + scanDir);
8390            return;
8391        }
8392
8393        if (DEBUG_PACKAGE_SCANNING) {
8394            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8395                    + " flags=0x" + Integer.toHexString(parseFlags));
8396        }
8397        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8398                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8399                mParallelPackageParserCallback)) {
8400            // Submit files for parsing in parallel
8401            int fileCount = 0;
8402            for (File file : files) {
8403                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8404                        && !PackageInstallerService.isStageName(file.getName());
8405                if (!isPackage) {
8406                    // Ignore entries which are not packages
8407                    continue;
8408                }
8409                parallelPackageParser.submit(file, parseFlags);
8410                fileCount++;
8411            }
8412
8413            // Process results one by one
8414            for (; fileCount > 0; fileCount--) {
8415                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8416                Throwable throwable = parseResult.throwable;
8417                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8418
8419                if (throwable == null) {
8420                    // TODO(toddke): move lower in the scan chain
8421                    // Static shared libraries have synthetic package names
8422                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8423                        renameStaticSharedLibraryPackage(parseResult.pkg);
8424                    }
8425                    try {
8426                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8427                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8428                                    currentTime, null);
8429                        }
8430                    } catch (PackageManagerException e) {
8431                        errorCode = e.error;
8432                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8433                    }
8434                } else if (throwable instanceof PackageParser.PackageParserException) {
8435                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8436                            throwable;
8437                    errorCode = e.error;
8438                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8439                } else {
8440                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8441                            + parseResult.scanFile, throwable);
8442                }
8443
8444                // Delete invalid userdata apps
8445                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8446                        errorCode != PackageManager.INSTALL_SUCCEEDED) {
8447                    logCriticalInfo(Log.WARN,
8448                            "Deleting invalid package at " + parseResult.scanFile);
8449                    removeCodePathLI(parseResult.scanFile);
8450                }
8451            }
8452        }
8453    }
8454
8455    public static void reportSettingsProblem(int priority, String msg) {
8456        logCriticalInfo(priority, msg);
8457    }
8458
8459    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8460            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8461        // When upgrading from pre-N MR1, verify the package time stamp using the package
8462        // directory and not the APK file.
8463        final long lastModifiedTime = mIsPreNMR1Upgrade
8464                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8465        if (ps != null && !forceCollect
8466                && ps.codePathString.equals(pkg.codePath)
8467                && ps.timeStamp == lastModifiedTime
8468                && !isCompatSignatureUpdateNeeded(pkg)
8469                && !isRecoverSignatureUpdateNeeded(pkg)) {
8470            if (ps.signatures.mSigningDetails.signatures != null
8471                    && ps.signatures.mSigningDetails.signatures.length != 0
8472                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8473                            != SignatureSchemeVersion.UNKNOWN) {
8474                // Optimization: reuse the existing cached signing data
8475                // if the package appears to be unchanged.
8476                pkg.mSigningDetails =
8477                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8478                return;
8479            }
8480
8481            Slog.w(TAG, "PackageSetting for " + ps.name
8482                    + " is missing signatures.  Collecting certs again to recover them.");
8483        } else {
8484            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8485                    (forceCollect ? " (forced)" : ""));
8486        }
8487
8488        try {
8489            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8490            PackageParser.collectCertificates(pkg, skipVerify);
8491        } catch (PackageParserException e) {
8492            throw PackageManagerException.from(e);
8493        } finally {
8494            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8495        }
8496    }
8497
8498    /**
8499     * Clear the package profile if this was an upgrade and the package
8500     * version was updated.
8501     */
8502    private void maybeClearProfilesForUpgradesLI(
8503            @Nullable PackageSetting originalPkgSetting,
8504            @NonNull PackageParser.Package currentPkg) {
8505        if (originalPkgSetting == null || !isUpgrade()) {
8506          return;
8507        }
8508        if (originalPkgSetting.versionCode == currentPkg.mVersionCode) {
8509          return;
8510        }
8511
8512        clearAppProfilesLIF(currentPkg, UserHandle.USER_ALL);
8513        if (DEBUG_INSTALL) {
8514            Slog.d(TAG, originalPkgSetting.name
8515                  + " clear profile due to version change "
8516                  + originalPkgSetting.versionCode + " != "
8517                  + currentPkg.mVersionCode);
8518        }
8519    }
8520
8521    /**
8522     *  Traces a package scan.
8523     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8524     */
8525    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8526            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8527        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8528        try {
8529            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8530        } finally {
8531            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8532        }
8533    }
8534
8535    /**
8536     *  Scans a package and returns the newly parsed package.
8537     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8538     */
8539    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8540            long currentTime, UserHandle user) throws PackageManagerException {
8541        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8542        PackageParser pp = new PackageParser();
8543        pp.setSeparateProcesses(mSeparateProcesses);
8544        pp.setOnlyCoreApps(mOnlyCore);
8545        pp.setDisplayMetrics(mMetrics);
8546        pp.setCallback(mPackageParserCallback);
8547
8548        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8549        final PackageParser.Package pkg;
8550        try {
8551            pkg = pp.parsePackage(scanFile, parseFlags);
8552        } catch (PackageParserException e) {
8553            throw PackageManagerException.from(e);
8554        } finally {
8555            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8556        }
8557
8558        // Static shared libraries have synthetic package names
8559        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8560            renameStaticSharedLibraryPackage(pkg);
8561        }
8562
8563        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8564    }
8565
8566    /**
8567     *  Scans a package and returns the newly parsed package.
8568     *  @throws PackageManagerException on a parse error.
8569     */
8570    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8571            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8572            @Nullable UserHandle user)
8573                    throws PackageManagerException {
8574        // If the package has children and this is the first dive in the function
8575        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8576        // packages (parent and children) would be successfully scanned before the
8577        // actual scan since scanning mutates internal state and we want to atomically
8578        // install the package and its children.
8579        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8580            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8581                scanFlags |= SCAN_CHECK_ONLY;
8582            }
8583        } else {
8584            scanFlags &= ~SCAN_CHECK_ONLY;
8585        }
8586
8587        // Scan the parent
8588        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8589                scanFlags, currentTime, user);
8590
8591        // Scan the children
8592        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8593        for (int i = 0; i < childCount; i++) {
8594            PackageParser.Package childPackage = pkg.childPackages.get(i);
8595            addForInitLI(childPackage, parseFlags, scanFlags,
8596                    currentTime, user);
8597        }
8598
8599
8600        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8601            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8602        }
8603
8604        return scannedPkg;
8605    }
8606
8607    /**
8608     * Returns if full apk verification can be skipped for the whole package, including the splits.
8609     */
8610    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8611        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8612            return false;
8613        }
8614        // TODO: Allow base and splits to be verified individually.
8615        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8616            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8617                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8618                    return false;
8619                }
8620            }
8621        }
8622        return true;
8623    }
8624
8625    /**
8626     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8627     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8628     * match one in a trusted source, and should be done separately.
8629     */
8630    private boolean canSkipFullApkVerification(String apkPath) {
8631        byte[] rootHashObserved = null;
8632        try {
8633            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8634            if (rootHashObserved == null) {
8635                return false;  // APK does not contain Merkle tree root hash.
8636            }
8637            synchronized (mInstallLock) {
8638                // Returns whether the observed root hash matches what kernel has.
8639                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8640                return true;
8641            }
8642        } catch (InstallerException | IOException | DigestException |
8643                NoSuchAlgorithmException e) {
8644            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8645        }
8646        return false;
8647    }
8648
8649    /**
8650     * Adds a new package to the internal data structures during platform initialization.
8651     * <p>After adding, the package is known to the system and available for querying.
8652     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8653     * etc...], additional checks are performed. Basic verification [such as ensuring
8654     * matching signatures, checking version codes, etc...] occurs if the package is
8655     * identical to a previously known package. If the package fails a signature check,
8656     * the version installed on /data will be removed. If the version of the new package
8657     * is less than or equal than the version on /data, it will be ignored.
8658     * <p>Regardless of the package location, the results are applied to the internal
8659     * structures and the package is made available to the rest of the system.
8660     * <p>NOTE: The return value should be removed. It's the passed in package object.
8661     */
8662    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8663            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8664            @Nullable UserHandle user)
8665                    throws PackageManagerException {
8666        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8667        final String renamedPkgName;
8668        final PackageSetting disabledPkgSetting;
8669        final boolean isSystemPkgUpdated;
8670        final boolean pkgAlreadyExists;
8671        PackageSetting pkgSetting;
8672
8673        // NOTE: installPackageLI() has the same code to setup the package's
8674        // application info. This probably should be done lower in the call
8675        // stack [such as scanPackageOnly()]. However, we verify the application
8676        // info prior to that [in scanPackageNew()] and thus have to setup
8677        // the application info early.
8678        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8679        pkg.setApplicationInfoCodePath(pkg.codePath);
8680        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8681        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8682        pkg.setApplicationInfoResourcePath(pkg.codePath);
8683        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8684        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8685
8686        synchronized (mPackages) {
8687            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8688            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8689            if (realPkgName != null) {
8690                ensurePackageRenamed(pkg, renamedPkgName);
8691            }
8692            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8693            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8694            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8695            pkgAlreadyExists = pkgSetting != null;
8696            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8697            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8698            isSystemPkgUpdated = disabledPkgSetting != null;
8699
8700            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8701                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8702            }
8703
8704            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8705                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8706                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8707                    : null;
8708            if (DEBUG_PACKAGE_SCANNING
8709                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8710                    && sharedUserSetting != null) {
8711                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8712                        + " (uid=" + sharedUserSetting.userId + "):"
8713                        + " packages=" + sharedUserSetting.packages);
8714            }
8715
8716            if (scanSystemPartition) {
8717                // Potentially prune child packages. If the application on the /system
8718                // partition has been updated via OTA, but, is still disabled by a
8719                // version on /data, cycle through all of its children packages and
8720                // remove children that are no longer defined.
8721                if (isSystemPkgUpdated) {
8722                    final int scannedChildCount = (pkg.childPackages != null)
8723                            ? pkg.childPackages.size() : 0;
8724                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8725                            ? disabledPkgSetting.childPackageNames.size() : 0;
8726                    for (int i = 0; i < disabledChildCount; i++) {
8727                        String disabledChildPackageName =
8728                                disabledPkgSetting.childPackageNames.get(i);
8729                        boolean disabledPackageAvailable = false;
8730                        for (int j = 0; j < scannedChildCount; j++) {
8731                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8732                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8733                                disabledPackageAvailable = true;
8734                                break;
8735                            }
8736                        }
8737                        if (!disabledPackageAvailable) {
8738                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8739                        }
8740                    }
8741                    // we're updating the disabled package, so, scan it as the package setting
8742                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, null,
8743                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8744                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8745                            (pkg == mPlatformPackage), user);
8746                    applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage);
8747                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8748                }
8749            }
8750        }
8751
8752        final boolean newPkgChangedPaths =
8753                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8754        final boolean newPkgVersionGreater =
8755                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8756        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8757                && newPkgChangedPaths && newPkgVersionGreater;
8758        if (isSystemPkgBetter) {
8759            // The version of the application on /system is greater than the version on
8760            // /data. Switch back to the application on /system.
8761            // It's safe to assume the application on /system will correctly scan. If not,
8762            // there won't be a working copy of the application.
8763            synchronized (mPackages) {
8764                // just remove the loaded entries from package lists
8765                mPackages.remove(pkgSetting.name);
8766            }
8767
8768            logCriticalInfo(Log.WARN,
8769                    "System package updated;"
8770                    + " name: " + pkgSetting.name
8771                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8772                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8773
8774            final InstallArgs args = createInstallArgsForExisting(
8775                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8776                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8777            args.cleanUpResourcesLI();
8778            synchronized (mPackages) {
8779                mSettings.enableSystemPackageLPw(pkgSetting.name);
8780            }
8781        }
8782
8783        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8784            // The version of the application on the /system partition is less than or
8785            // equal to the version on the /data partition. Even though the disabled system package
8786            // is likely to be replaced by a version on the /data partition, we make assumptions
8787            // that it's part of the mPackages collection during package manager initialization. So,
8788            // add it to mPackages if there isn't already a package in the collection and then throw
8789            // an exception to use the application already installed on the /data partition.
8790            synchronized (mPackages) {
8791                if (!mPackages.containsKey(pkg.packageName)) {
8792                    mPackages.put(pkg.packageName, pkg);
8793                }
8794            }
8795            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8796                    + pkg.codePath + " ignored: updated version " + pkgSetting.versionCode
8797                    + " better than this " + pkg.getLongVersionCode());
8798        }
8799
8800        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8801        // force re-collecting certificate.
8802        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8803                disabledPkgSetting);
8804        // Full APK verification can be skipped during certificate collection, only if the file is
8805        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8806        // cases, only data in Signing Block is verified instead of the whole file.
8807        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8808                (forceCollect && canSkipFullPackageVerification(pkg));
8809        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8810
8811        // Reset profile if the application version is changed
8812        maybeClearProfilesForUpgradesLI(pkgSetting, pkg);
8813
8814        /*
8815         * A new system app appeared, but we already had a non-system one of the
8816         * same name installed earlier.
8817         */
8818        boolean shouldHideSystemApp = false;
8819        // A new application appeared on /system, but, we already have a copy of
8820        // the application installed on /data.
8821        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8822                && !pkgSetting.isSystem()) {
8823
8824            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8825                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
8826                            && !pkgSetting.signatures.mSigningDetails.checkCapability(
8827                                    pkg.mSigningDetails,
8828                                    PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
8829                logCriticalInfo(Log.WARN,
8830                        "System package signature mismatch;"
8831                        + " name: " + pkgSetting.name);
8832                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8833                        "scanPackageInternalLI")) {
8834                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8835                }
8836                pkgSetting = null;
8837            } else if (newPkgVersionGreater) {
8838                // The application on /system is newer than the application on /data.
8839                // Simply remove the application on /data [keeping application data]
8840                // and replace it with the version on /system.
8841                logCriticalInfo(Log.WARN,
8842                        "System package enabled;"
8843                        + " name: " + pkgSetting.name
8844                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8845                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8846                InstallArgs args = createInstallArgsForExisting(
8847                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8848                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8849                synchronized (mInstallLock) {
8850                    args.cleanUpResourcesLI();
8851                }
8852            } else {
8853                // The application on /system is older than the application on /data. Hide
8854                // the application on /system and the version on /data will be scanned later
8855                // and re-added like an update.
8856                shouldHideSystemApp = true;
8857                logCriticalInfo(Log.INFO,
8858                        "System package disabled;"
8859                        + " name: " + pkgSetting.name
8860                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8861                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8862            }
8863        }
8864
8865        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8866                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8867
8868        if (shouldHideSystemApp) {
8869            synchronized (mPackages) {
8870                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8871            }
8872        }
8873        return scannedPkg;
8874    }
8875
8876    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8877        // Derive the new package synthetic package name
8878        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8879                + pkg.staticSharedLibVersion);
8880    }
8881
8882    private static String fixProcessName(String defProcessName,
8883            String processName) {
8884        if (processName == null) {
8885            return defProcessName;
8886        }
8887        return processName;
8888    }
8889
8890    /**
8891     * Enforces that only the system UID or root's UID can call a method exposed
8892     * via Binder.
8893     *
8894     * @param message used as message if SecurityException is thrown
8895     * @throws SecurityException if the caller is not system or root
8896     */
8897    private static final void enforceSystemOrRoot(String message) {
8898        final int uid = Binder.getCallingUid();
8899        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8900            throw new SecurityException(message);
8901        }
8902    }
8903
8904    @Override
8905    public void performFstrimIfNeeded() {
8906        enforceSystemOrRoot("Only the system can request fstrim");
8907
8908        // Before everything else, see whether we need to fstrim.
8909        try {
8910            IStorageManager sm = PackageHelper.getStorageManager();
8911            if (sm != null) {
8912                boolean doTrim = false;
8913                final long interval = android.provider.Settings.Global.getLong(
8914                        mContext.getContentResolver(),
8915                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8916                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8917                if (interval > 0) {
8918                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8919                    if (timeSinceLast > interval) {
8920                        doTrim = true;
8921                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8922                                + "; running immediately");
8923                    }
8924                }
8925                if (doTrim) {
8926                    final boolean dexOptDialogShown;
8927                    synchronized (mPackages) {
8928                        dexOptDialogShown = mDexOptDialogShown;
8929                    }
8930                    if (!isFirstBoot() && dexOptDialogShown) {
8931                        try {
8932                            ActivityManager.getService().showBootMessage(
8933                                    mContext.getResources().getString(
8934                                            R.string.android_upgrading_fstrim), true);
8935                        } catch (RemoteException e) {
8936                        }
8937                    }
8938                    sm.runMaintenance();
8939                }
8940            } else {
8941                Slog.e(TAG, "storageManager service unavailable!");
8942            }
8943        } catch (RemoteException e) {
8944            // Can't happen; StorageManagerService is local
8945        }
8946    }
8947
8948    @Override
8949    public void updatePackagesIfNeeded() {
8950        enforceSystemOrRoot("Only the system can request package update");
8951
8952        // We need to re-extract after an OTA.
8953        boolean causeUpgrade = isUpgrade();
8954
8955        // First boot or factory reset.
8956        // Note: we also handle devices that are upgrading to N right now as if it is their
8957        //       first boot, as they do not have profile data.
8958        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8959
8960        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8961        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8962
8963        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8964            return;
8965        }
8966
8967        List<PackageParser.Package> pkgs;
8968        synchronized (mPackages) {
8969            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8970        }
8971
8972        final long startTime = System.nanoTime();
8973        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8974                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
8975                    false /* bootComplete */);
8976
8977        final int elapsedTimeSeconds =
8978                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8979
8980        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8981        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8982        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8983        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8984        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8985    }
8986
8987    /*
8988     * Return the prebuilt profile path given a package base code path.
8989     */
8990    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8991        return pkg.baseCodePath + ".prof";
8992    }
8993
8994    /**
8995     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8996     * containing statistics about the invocation. The array consists of three elements,
8997     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8998     * and {@code numberOfPackagesFailed}.
8999     */
9000    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9001            final int compilationReason, boolean bootComplete) {
9002
9003        int numberOfPackagesVisited = 0;
9004        int numberOfPackagesOptimized = 0;
9005        int numberOfPackagesSkipped = 0;
9006        int numberOfPackagesFailed = 0;
9007        final int numberOfPackagesToDexopt = pkgs.size();
9008
9009        for (PackageParser.Package pkg : pkgs) {
9010            numberOfPackagesVisited++;
9011
9012            boolean useProfileForDexopt = false;
9013
9014            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9015                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9016                // that are already compiled.
9017                File profileFile = new File(getPrebuildProfilePath(pkg));
9018                // Copy profile if it exists.
9019                if (profileFile.exists()) {
9020                    try {
9021                        // We could also do this lazily before calling dexopt in
9022                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9023                        // is that we don't have a good way to say "do this only once".
9024                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9025                                pkg.applicationInfo.uid, pkg.packageName,
9026                                ArtManager.getProfileName(null))) {
9027                            Log.e(TAG, "Installer failed to copy system profile!");
9028                        } else {
9029                            // Disabled as this causes speed-profile compilation during first boot
9030                            // even if things are already compiled.
9031                            // useProfileForDexopt = true;
9032                        }
9033                    } catch (Exception e) {
9034                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9035                                e);
9036                    }
9037                } else {
9038                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9039                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
9040                    // minimize the number off apps being speed-profile compiled during first boot.
9041                    // The other paths will not change the filter.
9042                    if (disabledPs != null && disabledPs.pkg.isStub) {
9043                        // The package is the stub one, remove the stub suffix to get the normal
9044                        // package and APK names.
9045                        String systemProfilePath =
9046                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
9047                        profileFile = new File(systemProfilePath);
9048                        // If we have a profile for a compressed APK, copy it to the reference
9049                        // location.
9050                        // Note that copying the profile here will cause it to override the
9051                        // reference profile every OTA even though the existing reference profile
9052                        // may have more data. We can't copy during decompression since the
9053                        // directories are not set up at that point.
9054                        if (profileFile.exists()) {
9055                            try {
9056                                // We could also do this lazily before calling dexopt in
9057                                // PackageDexOptimizer to prevent this happening on first boot. The
9058                                // issue is that we don't have a good way to say "do this only
9059                                // once".
9060                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9061                                        pkg.applicationInfo.uid, pkg.packageName,
9062                                        ArtManager.getProfileName(null))) {
9063                                    Log.e(TAG, "Failed to copy system profile for stub package!");
9064                                } else {
9065                                    useProfileForDexopt = true;
9066                                }
9067                            } catch (Exception e) {
9068                                Log.e(TAG, "Failed to copy profile " +
9069                                        profileFile.getAbsolutePath() + " ", e);
9070                            }
9071                        }
9072                    }
9073                }
9074            }
9075
9076            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9077                if (DEBUG_DEXOPT) {
9078                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9079                }
9080                numberOfPackagesSkipped++;
9081                continue;
9082            }
9083
9084            if (DEBUG_DEXOPT) {
9085                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9086                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9087            }
9088
9089            if (showDialog) {
9090                try {
9091                    ActivityManager.getService().showBootMessage(
9092                            mContext.getResources().getString(R.string.android_upgrading_apk,
9093                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9094                } catch (RemoteException e) {
9095                }
9096                synchronized (mPackages) {
9097                    mDexOptDialogShown = true;
9098                }
9099            }
9100
9101            int pkgCompilationReason = compilationReason;
9102            if (useProfileForDexopt) {
9103                // Use background dexopt mode to try and use the profile. Note that this does not
9104                // guarantee usage of the profile.
9105                pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT;
9106            }
9107
9108            // checkProfiles is false to avoid merging profiles during boot which
9109            // might interfere with background compilation (b/28612421).
9110            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9111            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9112            // trade-off worth doing to save boot time work.
9113            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9114            if (compilationReason == REASON_FIRST_BOOT) {
9115                // TODO: This doesn't cover the upgrade case, we should check for this too.
9116                dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE;
9117            }
9118            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9119                    pkg.packageName,
9120                    pkgCompilationReason,
9121                    dexoptFlags));
9122
9123            switch (primaryDexOptStaus) {
9124                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9125                    numberOfPackagesOptimized++;
9126                    break;
9127                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9128                    numberOfPackagesSkipped++;
9129                    break;
9130                case PackageDexOptimizer.DEX_OPT_FAILED:
9131                    numberOfPackagesFailed++;
9132                    break;
9133                default:
9134                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9135                    break;
9136            }
9137        }
9138
9139        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9140                numberOfPackagesFailed };
9141    }
9142
9143    @Override
9144    public void notifyPackageUse(String packageName, int reason) {
9145        synchronized (mPackages) {
9146            final int callingUid = Binder.getCallingUid();
9147            final int callingUserId = UserHandle.getUserId(callingUid);
9148            if (getInstantAppPackageName(callingUid) != null) {
9149                if (!isCallerSameApp(packageName, callingUid)) {
9150                    return;
9151                }
9152            } else {
9153                if (isInstantApp(packageName, callingUserId)) {
9154                    return;
9155                }
9156            }
9157            notifyPackageUseLocked(packageName, reason);
9158        }
9159    }
9160
9161    @GuardedBy("mPackages")
9162    private void notifyPackageUseLocked(String packageName, int reason) {
9163        final PackageParser.Package p = mPackages.get(packageName);
9164        if (p == null) {
9165            return;
9166        }
9167        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9168    }
9169
9170    @Override
9171    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9172            List<String> classPaths, String loaderIsa) {
9173        int userId = UserHandle.getCallingUserId();
9174        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9175        if (ai == null) {
9176            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9177                + loadingPackageName + ", user=" + userId);
9178            return;
9179        }
9180        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9181    }
9182
9183    @Override
9184    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9185            IDexModuleRegisterCallback callback) {
9186        int userId = UserHandle.getCallingUserId();
9187        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9188        DexManager.RegisterDexModuleResult result;
9189        if (ai == null) {
9190            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9191                     " calling user. package=" + packageName + ", user=" + userId);
9192            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9193        } else {
9194            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9195        }
9196
9197        if (callback != null) {
9198            mHandler.post(() -> {
9199                try {
9200                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9201                } catch (RemoteException e) {
9202                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9203                }
9204            });
9205        }
9206    }
9207
9208    /**
9209     * Ask the package manager to perform a dex-opt with the given compiler filter.
9210     *
9211     * Note: exposed only for the shell command to allow moving packages explicitly to a
9212     *       definite state.
9213     */
9214    @Override
9215    public boolean performDexOptMode(String packageName,
9216            boolean checkProfiles, String targetCompilerFilter, boolean force,
9217            boolean bootComplete, String splitName) {
9218        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9219                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9220                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9221        return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN,
9222                targetCompilerFilter, splitName, flags));
9223    }
9224
9225    /**
9226     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9227     * secondary dex files belonging to the given package.
9228     *
9229     * Note: exposed only for the shell command to allow moving packages explicitly to a
9230     *       definite state.
9231     */
9232    @Override
9233    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9234            boolean force) {
9235        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9236                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9237                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9238                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9239        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9240    }
9241
9242    /*package*/ boolean performDexOpt(DexoptOptions options) {
9243        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9244            return false;
9245        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9246            return false;
9247        }
9248
9249        if (options.isDexoptOnlySecondaryDex()) {
9250            return mDexManager.dexoptSecondaryDex(options);
9251        } else {
9252            int dexoptStatus = performDexOptWithStatus(options);
9253            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9254        }
9255    }
9256
9257    /**
9258     * Perform dexopt on the given package and return one of following result:
9259     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9260     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9261     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9262     */
9263    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9264        return performDexOptTraced(options);
9265    }
9266
9267    private int performDexOptTraced(DexoptOptions options) {
9268        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9269        try {
9270            return performDexOptInternal(options);
9271        } finally {
9272            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9273        }
9274    }
9275
9276    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9277    // if the package can now be considered up to date for the given filter.
9278    private int performDexOptInternal(DexoptOptions options) {
9279        PackageParser.Package p;
9280        synchronized (mPackages) {
9281            p = mPackages.get(options.getPackageName());
9282            if (p == null) {
9283                // Package could not be found. Report failure.
9284                return PackageDexOptimizer.DEX_OPT_FAILED;
9285            }
9286            mPackageUsage.maybeWriteAsync(mPackages);
9287            mCompilerStats.maybeWriteAsync();
9288        }
9289        long callingId = Binder.clearCallingIdentity();
9290        try {
9291            synchronized (mInstallLock) {
9292                return performDexOptInternalWithDependenciesLI(p, options);
9293            }
9294        } finally {
9295            Binder.restoreCallingIdentity(callingId);
9296        }
9297    }
9298
9299    public ArraySet<String> getOptimizablePackages() {
9300        ArraySet<String> pkgs = new ArraySet<String>();
9301        synchronized (mPackages) {
9302            for (PackageParser.Package p : mPackages.values()) {
9303                if (PackageDexOptimizer.canOptimizePackage(p)) {
9304                    pkgs.add(p.packageName);
9305                }
9306            }
9307        }
9308        return pkgs;
9309    }
9310
9311    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9312            DexoptOptions options) {
9313        // Select the dex optimizer based on the force parameter.
9314        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9315        //       allocate an object here.
9316        PackageDexOptimizer pdo = options.isForce()
9317                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9318                : mPackageDexOptimizer;
9319
9320        // Dexopt all dependencies first. Note: we ignore the return value and march on
9321        // on errors.
9322        // Note that we are going to call performDexOpt on those libraries as many times as
9323        // they are referenced in packages. When we do a batch of performDexOpt (for example
9324        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9325        // and the first package that uses the library will dexopt it. The
9326        // others will see that the compiled code for the library is up to date.
9327        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9328        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9329        if (!deps.isEmpty()) {
9330            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9331                    options.getCompilationReason(), options.getCompilerFilter(),
9332                    options.getSplitName(),
9333                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9334            for (PackageParser.Package depPackage : deps) {
9335                // TODO: Analyze and investigate if we (should) profile libraries.
9336                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9337                        getOrCreateCompilerPackageStats(depPackage),
9338                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9339            }
9340        }
9341        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9342                getOrCreateCompilerPackageStats(p),
9343                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9344    }
9345
9346    /**
9347     * Reconcile the information we have about the secondary dex files belonging to
9348     * {@code packagName} and the actual dex files. For all dex files that were
9349     * deleted, update the internal records and delete the generated oat files.
9350     */
9351    @Override
9352    public void reconcileSecondaryDexFiles(String packageName) {
9353        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9354            return;
9355        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9356            return;
9357        }
9358        mDexManager.reconcileSecondaryDexFiles(packageName);
9359    }
9360
9361    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9362    // a reference there.
9363    /*package*/ DexManager getDexManager() {
9364        return mDexManager;
9365    }
9366
9367    /**
9368     * Execute the background dexopt job immediately.
9369     */
9370    @Override
9371    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9372        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9373            return false;
9374        }
9375        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9376    }
9377
9378    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9379        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9380                || p.usesStaticLibraries != null) {
9381            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9382            Set<String> collectedNames = new HashSet<>();
9383            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9384
9385            retValue.remove(p);
9386
9387            return retValue;
9388        } else {
9389            return Collections.emptyList();
9390        }
9391    }
9392
9393    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9394            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9395        if (!collectedNames.contains(p.packageName)) {
9396            collectedNames.add(p.packageName);
9397            collected.add(p);
9398
9399            if (p.usesLibraries != null) {
9400                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9401                        null, collected, collectedNames);
9402            }
9403            if (p.usesOptionalLibraries != null) {
9404                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9405                        null, collected, collectedNames);
9406            }
9407            if (p.usesStaticLibraries != null) {
9408                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9409                        p.usesStaticLibrariesVersions, collected, collectedNames);
9410            }
9411        }
9412    }
9413
9414    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9415            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9416        final int libNameCount = libs.size();
9417        for (int i = 0; i < libNameCount; i++) {
9418            String libName = libs.get(i);
9419            long version = (versions != null && versions.length == libNameCount)
9420                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9421            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9422            if (libPkg != null) {
9423                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9424            }
9425        }
9426    }
9427
9428    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9429        synchronized (mPackages) {
9430            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9431            if (libEntry != null) {
9432                return mPackages.get(libEntry.apk);
9433            }
9434            return null;
9435        }
9436    }
9437
9438    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9439        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9440        if (versionedLib == null) {
9441            return null;
9442        }
9443        return versionedLib.get(version);
9444    }
9445
9446    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9447        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9448                pkg.staticSharedLibName);
9449        if (versionedLib == null) {
9450            return null;
9451        }
9452        long previousLibVersion = -1;
9453        final int versionCount = versionedLib.size();
9454        for (int i = 0; i < versionCount; i++) {
9455            final long libVersion = versionedLib.keyAt(i);
9456            if (libVersion < pkg.staticSharedLibVersion) {
9457                previousLibVersion = Math.max(previousLibVersion, libVersion);
9458            }
9459        }
9460        if (previousLibVersion >= 0) {
9461            return versionedLib.get(previousLibVersion);
9462        }
9463        return null;
9464    }
9465
9466    public void shutdown() {
9467        mPackageUsage.writeNow(mPackages);
9468        mCompilerStats.writeNow();
9469        mDexManager.writePackageDexUsageNow();
9470
9471        // This is the last chance to write out pending restriction settings
9472        synchronized (mPackages) {
9473            if (mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
9474                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
9475                for (int userId : mDirtyUsers) {
9476                    mSettings.writePackageRestrictionsLPr(userId);
9477                }
9478                mDirtyUsers.clear();
9479            }
9480        }
9481    }
9482
9483    @Override
9484    public void dumpProfiles(String packageName) {
9485        PackageParser.Package pkg;
9486        synchronized (mPackages) {
9487            pkg = mPackages.get(packageName);
9488            if (pkg == null) {
9489                throw new IllegalArgumentException("Unknown package: " + packageName);
9490            }
9491        }
9492        /* Only the shell, root, or the app user should be able to dump profiles. */
9493        int callingUid = Binder.getCallingUid();
9494        if (callingUid != Process.SHELL_UID &&
9495            callingUid != Process.ROOT_UID &&
9496            callingUid != pkg.applicationInfo.uid) {
9497            throw new SecurityException("dumpProfiles");
9498        }
9499
9500        synchronized (mInstallLock) {
9501            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9502            mArtManagerService.dumpProfiles(pkg);
9503            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9504        }
9505    }
9506
9507    @Override
9508    public void forceDexOpt(String packageName) {
9509        enforceSystemOrRoot("forceDexOpt");
9510
9511        PackageParser.Package pkg;
9512        synchronized (mPackages) {
9513            pkg = mPackages.get(packageName);
9514            if (pkg == null) {
9515                throw new IllegalArgumentException("Unknown package: " + packageName);
9516            }
9517        }
9518
9519        synchronized (mInstallLock) {
9520            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9521
9522            // Whoever is calling forceDexOpt wants a compiled package.
9523            // Don't use profiles since that may cause compilation to be skipped.
9524            final int res = performDexOptInternalWithDependenciesLI(
9525                    pkg,
9526                    new DexoptOptions(packageName,
9527                            getDefaultCompilerFilter(),
9528                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9529
9530            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9531            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9532                throw new IllegalStateException("Failed to dexopt: " + res);
9533            }
9534        }
9535    }
9536
9537    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9538        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9539            Slog.w(TAG, "Unable to update from " + oldPkg.name
9540                    + " to " + newPkg.packageName
9541                    + ": old package not in system partition");
9542            return false;
9543        } else if (mPackages.get(oldPkg.name) != null) {
9544            Slog.w(TAG, "Unable to update from " + oldPkg.name
9545                    + " to " + newPkg.packageName
9546                    + ": old package still exists");
9547            return false;
9548        }
9549        return true;
9550    }
9551
9552    void removeCodePathLI(File codePath) {
9553        if (codePath.isDirectory()) {
9554            try {
9555                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9556            } catch (InstallerException e) {
9557                Slog.w(TAG, "Failed to remove code path", e);
9558            }
9559        } else {
9560            codePath.delete();
9561        }
9562    }
9563
9564    private int[] resolveUserIds(int userId) {
9565        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9566    }
9567
9568    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9569        if (pkg == null) {
9570            Slog.wtf(TAG, "Package was null!", new Throwable());
9571            return;
9572        }
9573        clearAppDataLeafLIF(pkg, userId, flags);
9574        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9575        for (int i = 0; i < childCount; i++) {
9576            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9577        }
9578
9579        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9580    }
9581
9582    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9583        final PackageSetting ps;
9584        synchronized (mPackages) {
9585            ps = mSettings.mPackages.get(pkg.packageName);
9586        }
9587        for (int realUserId : resolveUserIds(userId)) {
9588            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9589            try {
9590                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9591                        ceDataInode);
9592            } catch (InstallerException e) {
9593                Slog.w(TAG, String.valueOf(e));
9594            }
9595        }
9596    }
9597
9598    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9599        if (pkg == null) {
9600            Slog.wtf(TAG, "Package was null!", new Throwable());
9601            return;
9602        }
9603        destroyAppDataLeafLIF(pkg, userId, flags);
9604        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9605        for (int i = 0; i < childCount; i++) {
9606            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9607        }
9608    }
9609
9610    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9611        final PackageSetting ps;
9612        synchronized (mPackages) {
9613            ps = mSettings.mPackages.get(pkg.packageName);
9614        }
9615        for (int realUserId : resolveUserIds(userId)) {
9616            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9617            try {
9618                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9619                        ceDataInode);
9620            } catch (InstallerException e) {
9621                Slog.w(TAG, String.valueOf(e));
9622            }
9623            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9624        }
9625    }
9626
9627    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9628        if (pkg == null) {
9629            Slog.wtf(TAG, "Package was null!", new Throwable());
9630            return;
9631        }
9632        destroyAppProfilesLeafLIF(pkg);
9633        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9634        for (int i = 0; i < childCount; i++) {
9635            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9636        }
9637    }
9638
9639    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9640        try {
9641            mInstaller.destroyAppProfiles(pkg.packageName);
9642        } catch (InstallerException e) {
9643            Slog.w(TAG, String.valueOf(e));
9644        }
9645    }
9646
9647    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9648        if (pkg == null) {
9649            Slog.wtf(TAG, "Package was null!", new Throwable());
9650            return;
9651        }
9652        mArtManagerService.clearAppProfiles(pkg);
9653        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9654        for (int i = 0; i < childCount; i++) {
9655            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9656        }
9657    }
9658
9659    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9660            long lastUpdateTime) {
9661        // Set parent install/update time
9662        PackageSetting ps = (PackageSetting) pkg.mExtras;
9663        if (ps != null) {
9664            ps.firstInstallTime = firstInstallTime;
9665            ps.lastUpdateTime = lastUpdateTime;
9666        }
9667        // Set children install/update time
9668        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9669        for (int i = 0; i < childCount; i++) {
9670            PackageParser.Package childPkg = pkg.childPackages.get(i);
9671            ps = (PackageSetting) childPkg.mExtras;
9672            if (ps != null) {
9673                ps.firstInstallTime = firstInstallTime;
9674                ps.lastUpdateTime = lastUpdateTime;
9675            }
9676        }
9677    }
9678
9679    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9680            SharedLibraryEntry file,
9681            PackageParser.Package changingLib) {
9682        if (file.path != null) {
9683            usesLibraryFiles.add(file.path);
9684            return;
9685        }
9686        PackageParser.Package p = mPackages.get(file.apk);
9687        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9688            // If we are doing this while in the middle of updating a library apk,
9689            // then we need to make sure to use that new apk for determining the
9690            // dependencies here.  (We haven't yet finished committing the new apk
9691            // to the package manager state.)
9692            if (p == null || p.packageName.equals(changingLib.packageName)) {
9693                p = changingLib;
9694            }
9695        }
9696        if (p != null) {
9697            usesLibraryFiles.addAll(p.getAllCodePaths());
9698            if (p.usesLibraryFiles != null) {
9699                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9700            }
9701        }
9702    }
9703
9704    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9705            PackageParser.Package changingLib) throws PackageManagerException {
9706        if (pkg == null) {
9707            return;
9708        }
9709        // The collection used here must maintain the order of addition (so
9710        // that libraries are searched in the correct order) and must have no
9711        // duplicates.
9712        Set<String> usesLibraryFiles = null;
9713        if (pkg.usesLibraries != null) {
9714            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9715                    null, null, pkg.packageName, changingLib, true,
9716                    pkg.applicationInfo.targetSdkVersion, null);
9717        }
9718        if (pkg.usesStaticLibraries != null) {
9719            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9720                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9721                    pkg.packageName, changingLib, true,
9722                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9723        }
9724        if (pkg.usesOptionalLibraries != null) {
9725            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9726                    null, null, pkg.packageName, changingLib, false,
9727                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9728        }
9729        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9730            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9731        } else {
9732            pkg.usesLibraryFiles = null;
9733        }
9734    }
9735
9736    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9737            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9738            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9739            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9740            throws PackageManagerException {
9741        final int libCount = requestedLibraries.size();
9742        for (int i = 0; i < libCount; i++) {
9743            final String libName = requestedLibraries.get(i);
9744            final long libVersion = requiredVersions != null ? requiredVersions[i]
9745                    : SharedLibraryInfo.VERSION_UNDEFINED;
9746            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9747            if (libEntry == null) {
9748                if (required) {
9749                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9750                            "Package " + packageName + " requires unavailable shared library "
9751                                    + libName + "; failing!");
9752                } else if (DEBUG_SHARED_LIBRARIES) {
9753                    Slog.i(TAG, "Package " + packageName
9754                            + " desires unavailable shared library "
9755                            + libName + "; ignoring!");
9756                }
9757            } else {
9758                if (requiredVersions != null && requiredCertDigests != null) {
9759                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9760                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9761                            "Package " + packageName + " requires unavailable static shared"
9762                                    + " library " + libName + " version "
9763                                    + libEntry.info.getLongVersion() + "; failing!");
9764                    }
9765
9766                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9767                    if (libPkg == null) {
9768                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9769                                "Package " + packageName + " requires unavailable static shared"
9770                                        + " library; failing!");
9771                    }
9772
9773                    final String[] expectedCertDigests = requiredCertDigests[i];
9774
9775
9776                    if (expectedCertDigests.length > 1) {
9777
9778                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9779                        final String[] libCertDigests = (targetSdk >= Build.VERSION_CODES.O_MR1)
9780                                ? PackageUtils.computeSignaturesSha256Digests(
9781                                libPkg.mSigningDetails.signatures)
9782                                : PackageUtils.computeSignaturesSha256Digests(
9783                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9784
9785                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9786                        // target O we don't parse the "additional-certificate" tags similarly
9787                        // how we only consider all certs only for apps targeting O (see above).
9788                        // Therefore, the size check is safe to make.
9789                        if (expectedCertDigests.length != libCertDigests.length) {
9790                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9791                                    "Package " + packageName + " requires differently signed" +
9792                                            " static shared library; failing!");
9793                        }
9794
9795                        // Use a predictable order as signature order may vary
9796                        Arrays.sort(libCertDigests);
9797                        Arrays.sort(expectedCertDigests);
9798
9799                        final int certCount = libCertDigests.length;
9800                        for (int j = 0; j < certCount; j++) {
9801                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9802                                throw new PackageManagerException(
9803                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9804                                        "Package " + packageName + " requires differently signed" +
9805                                                " static shared library; failing!");
9806                            }
9807                        }
9808                    } else {
9809
9810                        // lib signing cert could have rotated beyond the one expected, check to see
9811                        // if the new one has been blessed by the old
9812                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9813                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9814                            throw new PackageManagerException(
9815                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9816                                    "Package " + packageName + " requires differently signed" +
9817                                            " static shared library; failing!");
9818                        }
9819                    }
9820                }
9821
9822                if (outUsedLibraries == null) {
9823                    // Use LinkedHashSet to preserve the order of files added to
9824                    // usesLibraryFiles while eliminating duplicates.
9825                    outUsedLibraries = new LinkedHashSet<>();
9826                }
9827                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9828            }
9829        }
9830        return outUsedLibraries;
9831    }
9832
9833    private static boolean hasString(List<String> list, List<String> which) {
9834        if (list == null) {
9835            return false;
9836        }
9837        for (int i=list.size()-1; i>=0; i--) {
9838            for (int j=which.size()-1; j>=0; j--) {
9839                if (which.get(j).equals(list.get(i))) {
9840                    return true;
9841                }
9842            }
9843        }
9844        return false;
9845    }
9846
9847    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9848            PackageParser.Package changingPkg) {
9849        ArrayList<PackageParser.Package> res = null;
9850        for (PackageParser.Package pkg : mPackages.values()) {
9851            if (changingPkg != null
9852                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9853                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9854                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9855                            changingPkg.staticSharedLibName)) {
9856                return null;
9857            }
9858            if (res == null) {
9859                res = new ArrayList<>();
9860            }
9861            res.add(pkg);
9862            try {
9863                updateSharedLibrariesLPr(pkg, changingPkg);
9864            } catch (PackageManagerException e) {
9865                // If a system app update or an app and a required lib missing we
9866                // delete the package and for updated system apps keep the data as
9867                // it is better for the user to reinstall than to be in an limbo
9868                // state. Also libs disappearing under an app should never happen
9869                // - just in case.
9870                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9871                    final int flags = pkg.isUpdatedSystemApp()
9872                            ? PackageManager.DELETE_KEEP_DATA : 0;
9873                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9874                            flags , null, true, null);
9875                }
9876                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9877            }
9878        }
9879        return res;
9880    }
9881
9882    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9883            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9884            @Nullable UserHandle user) throws PackageManagerException {
9885        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9886        // If the package has children and this is the first dive in the function
9887        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9888        // whether all packages (parent and children) would be successfully scanned
9889        // before the actual scan since scanning mutates internal state and we want
9890        // to atomically install the package and its children.
9891        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9892            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9893                scanFlags |= SCAN_CHECK_ONLY;
9894            }
9895        } else {
9896            scanFlags &= ~SCAN_CHECK_ONLY;
9897        }
9898
9899        final PackageParser.Package scannedPkg;
9900        try {
9901            // Scan the parent
9902            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9903            // Scan the children
9904            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9905            for (int i = 0; i < childCount; i++) {
9906                PackageParser.Package childPkg = pkg.childPackages.get(i);
9907                scanPackageNewLI(childPkg, parseFlags,
9908                        scanFlags, currentTime, user);
9909            }
9910        } finally {
9911            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9912        }
9913
9914        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9915            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9916        }
9917
9918        return scannedPkg;
9919    }
9920
9921    /** The result of a package scan. */
9922    private static class ScanResult {
9923        /** Whether or not the package scan was successful */
9924        public final boolean success;
9925        /**
9926         * The final package settings. This may be the same object passed in
9927         * the {@link ScanRequest}, but, with modified values.
9928         */
9929        @Nullable public final PackageSetting pkgSetting;
9930        /** ABI code paths that have changed in the package scan */
9931        @Nullable public final List<String> changedAbiCodePath;
9932        public ScanResult(
9933                boolean success,
9934                @Nullable PackageSetting pkgSetting,
9935                @Nullable List<String> changedAbiCodePath) {
9936            this.success = success;
9937            this.pkgSetting = pkgSetting;
9938            this.changedAbiCodePath = changedAbiCodePath;
9939        }
9940    }
9941
9942    /** A package to be scanned */
9943    private static class ScanRequest {
9944        /** The parsed package */
9945        @NonNull public final PackageParser.Package pkg;
9946        /** The package this package replaces */
9947        @Nullable public final PackageParser.Package oldPkg;
9948        /** Shared user settings, if the package has a shared user */
9949        @Nullable public final SharedUserSetting sharedUserSetting;
9950        /**
9951         * Package settings of the currently installed version.
9952         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9953         * during scan.
9954         */
9955        @Nullable public final PackageSetting pkgSetting;
9956        /** A copy of the settings for the currently installed version */
9957        @Nullable public final PackageSetting oldPkgSetting;
9958        /** Package settings for the disabled version on the /system partition */
9959        @Nullable public final PackageSetting disabledPkgSetting;
9960        /** Package settings for the installed version under its original package name */
9961        @Nullable public final PackageSetting originalPkgSetting;
9962        /** The real package name of a renamed application */
9963        @Nullable public final String realPkgName;
9964        public final @ParseFlags int parseFlags;
9965        public final @ScanFlags int scanFlags;
9966        /** The user for which the package is being scanned */
9967        @Nullable public final UserHandle user;
9968        /** Whether or not the platform package is being scanned */
9969        public final boolean isPlatformPackage;
9970        public ScanRequest(
9971                @NonNull PackageParser.Package pkg,
9972                @Nullable SharedUserSetting sharedUserSetting,
9973                @Nullable PackageParser.Package oldPkg,
9974                @Nullable PackageSetting pkgSetting,
9975                @Nullable PackageSetting disabledPkgSetting,
9976                @Nullable PackageSetting originalPkgSetting,
9977                @Nullable String realPkgName,
9978                @ParseFlags int parseFlags,
9979                @ScanFlags int scanFlags,
9980                boolean isPlatformPackage,
9981                @Nullable UserHandle user) {
9982            this.pkg = pkg;
9983            this.oldPkg = oldPkg;
9984            this.pkgSetting = pkgSetting;
9985            this.sharedUserSetting = sharedUserSetting;
9986            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9987            this.disabledPkgSetting = disabledPkgSetting;
9988            this.originalPkgSetting = originalPkgSetting;
9989            this.realPkgName = realPkgName;
9990            this.parseFlags = parseFlags;
9991            this.scanFlags = scanFlags;
9992            this.isPlatformPackage = isPlatformPackage;
9993            this.user = user;
9994        }
9995    }
9996
9997    /**
9998     * Returns the actual scan flags depending upon the state of the other settings.
9999     * <p>Updated system applications will not have the following flags set
10000     * by default and need to be adjusted after the fact:
10001     * <ul>
10002     * <li>{@link #SCAN_AS_SYSTEM}</li>
10003     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
10004     * <li>{@link #SCAN_AS_OEM}</li>
10005     * <li>{@link #SCAN_AS_VENDOR}</li>
10006     * <li>{@link #SCAN_AS_PRODUCT}</li>
10007     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
10008     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
10009     * </ul>
10010     */
10011    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
10012            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
10013            PackageParser.Package pkg) {
10014        if (disabledPkgSetting != null) {
10015            // updated system application, must at least have SCAN_AS_SYSTEM
10016            scanFlags |= SCAN_AS_SYSTEM;
10017            if ((disabledPkgSetting.pkgPrivateFlags
10018                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
10019                scanFlags |= SCAN_AS_PRIVILEGED;
10020            }
10021            if ((disabledPkgSetting.pkgPrivateFlags
10022                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
10023                scanFlags |= SCAN_AS_OEM;
10024            }
10025            if ((disabledPkgSetting.pkgPrivateFlags
10026                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
10027                scanFlags |= SCAN_AS_VENDOR;
10028            }
10029            if ((disabledPkgSetting.pkgPrivateFlags
10030                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
10031                scanFlags |= SCAN_AS_PRODUCT;
10032            }
10033        }
10034        if (pkgSetting != null) {
10035            final int userId = ((user == null) ? 0 : user.getIdentifier());
10036            if (pkgSetting.getInstantApp(userId)) {
10037                scanFlags |= SCAN_AS_INSTANT_APP;
10038            }
10039            if (pkgSetting.getVirtulalPreload(userId)) {
10040                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
10041            }
10042        }
10043
10044        // Scan as privileged apps that share a user with a priv-app.
10045        final boolean skipVendorPrivilegeScan = ((scanFlags & SCAN_AS_VENDOR) != 0)
10046                && SystemProperties.getInt("ro.vndk.version", 28) < 28;
10047        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0)
10048                && !pkg.isPrivileged()
10049                && (pkg.mSharedUserId != null)
10050                && !skipVendorPrivilegeScan) {
10051            SharedUserSetting sharedUserSetting = null;
10052            try {
10053                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
10054            } catch (PackageManagerException ignore) {}
10055            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
10056                // Exempt SharedUsers signed with the platform key.
10057                // TODO(b/72378145) Fix this exemption. Force signature apps
10058                // to whitelist their privileged permissions just like other
10059                // priv-apps.
10060                synchronized (mPackages) {
10061                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
10062                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
10063                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
10064                        scanFlags |= SCAN_AS_PRIVILEGED;
10065                    }
10066                }
10067            }
10068        }
10069
10070        return scanFlags;
10071    }
10072
10073    // TODO: scanPackageNewLI() and scanPackageOnly() should be merged. But, first, commiting
10074    // the results / removing app data needs to be moved up a level to the callers of this
10075    // method. Also, we need to solve the problem of potentially creating a new shared user
10076    // setting. That can probably be done later and patch things up after the fact.
10077    @GuardedBy("mInstallLock")
10078    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
10079            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
10080            @Nullable UserHandle user) throws PackageManagerException {
10081
10082        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10083        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
10084        if (realPkgName != null) {
10085            ensurePackageRenamed(pkg, renamedPkgName);
10086        }
10087        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
10088        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10089        final PackageSetting disabledPkgSetting =
10090                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10091
10092        if (mTransferedPackages.contains(pkg.packageName)) {
10093            Slog.w(TAG, "Package " + pkg.packageName
10094                    + " was transferred to another, but its .apk remains");
10095        }
10096
10097        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
10098        synchronized (mPackages) {
10099            applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage);
10100            assertPackageIsValid(pkg, parseFlags, scanFlags);
10101
10102            SharedUserSetting sharedUserSetting = null;
10103            if (pkg.mSharedUserId != null) {
10104                // SIDE EFFECTS; may potentially allocate a new shared user
10105                sharedUserSetting = mSettings.getSharedUserLPw(
10106                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10107                if (DEBUG_PACKAGE_SCANNING) {
10108                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10109                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
10110                                + " (uid=" + sharedUserSetting.userId + "):"
10111                                + " packages=" + sharedUserSetting.packages);
10112                }
10113            }
10114
10115            boolean scanSucceeded = false;
10116            try {
10117                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
10118                        pkgSetting == null ? null : pkgSetting.pkg, pkgSetting, disabledPkgSetting,
10119                        originalPkgSetting, realPkgName, parseFlags, scanFlags,
10120                        (pkg == mPlatformPackage), user);
10121                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
10122                if (result.success) {
10123                    commitScanResultsLocked(request, result);
10124                }
10125                scanSucceeded = true;
10126            } finally {
10127                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10128                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
10129                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10130                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10131                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10132                  }
10133            }
10134        }
10135        return pkg;
10136    }
10137
10138    /**
10139     * Commits the package scan and modifies system state.
10140     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
10141     * of committing the package, leaving the system in an inconsistent state.
10142     * This needs to be fixed so, once we get to this point, no errors are
10143     * possible and the system is not left in an inconsistent state.
10144     */
10145    @GuardedBy("mPackages")
10146    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
10147            throws PackageManagerException {
10148        final PackageParser.Package pkg = request.pkg;
10149        final PackageParser.Package oldPkg = request.oldPkg;
10150        final @ParseFlags int parseFlags = request.parseFlags;
10151        final @ScanFlags int scanFlags = request.scanFlags;
10152        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10153        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10154        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10155        final UserHandle user = request.user;
10156        final String realPkgName = request.realPkgName;
10157        final PackageSetting pkgSetting = result.pkgSetting;
10158        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10159        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10160
10161        if (newPkgSettingCreated) {
10162            if (originalPkgSetting != null) {
10163                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10164            }
10165            // THROWS: when we can't allocate a user id. add call to check if there's
10166            // enough space to ensure we won't throw; otherwise, don't modify state
10167            mSettings.addUserToSettingLPw(pkgSetting);
10168
10169            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10170                mTransferedPackages.add(originalPkgSetting.name);
10171            }
10172        }
10173        // TODO(toddke): Consider a method specifically for modifying the Package object
10174        // post scan; or, moving this stuff out of the Package object since it has nothing
10175        // to do with the package on disk.
10176        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10177        // for creating the application ID. If we did this earlier, we would be saving the
10178        // correct ID.
10179        pkg.applicationInfo.uid = pkgSetting.appId;
10180
10181        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10182
10183        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10184            mTransferedPackages.add(pkg.packageName);
10185        }
10186
10187        // THROWS: when requested libraries that can't be found. it only changes
10188        // the state of the passed in pkg object, so, move to the top of the method
10189        // and allow it to abort
10190        if ((scanFlags & SCAN_BOOTING) == 0
10191                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10192            // Check all shared libraries and map to their actual file path.
10193            // We only do this here for apps not on a system dir, because those
10194            // are the only ones that can fail an install due to this.  We
10195            // will take care of the system apps by updating all of their
10196            // library paths after the scan is done. Also during the initial
10197            // scan don't update any libs as we do this wholesale after all
10198            // apps are scanned to avoid dependency based scanning.
10199            updateSharedLibrariesLPr(pkg, null);
10200        }
10201
10202        // All versions of a static shared library are referenced with the same
10203        // package name. Internally, we use a synthetic package name to allow
10204        // multiple versions of the same shared library to be installed. So,
10205        // we need to generate the synthetic package name of the latest shared
10206        // library in order to compare signatures.
10207        PackageSetting signatureCheckPs = pkgSetting;
10208        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10209            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10210            if (libraryEntry != null) {
10211                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10212            }
10213        }
10214
10215        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10216        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10217            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10218                // We just determined the app is signed correctly, so bring
10219                // over the latest parsed certs.
10220                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10221            } else {
10222                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10223                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10224                            "Package " + pkg.packageName + " upgrade keys do not match the "
10225                                    + "previously installed version");
10226                } else {
10227                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10228                    String msg = "System package " + pkg.packageName
10229                            + " signature changed; retaining data.";
10230                    reportSettingsProblem(Log.WARN, msg);
10231                }
10232            }
10233        } else {
10234            try {
10235                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10236                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10237                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10238                        pkg.mSigningDetails, compareCompat, compareRecover);
10239                // The new KeySets will be re-added later in the scanning process.
10240                if (compatMatch) {
10241                    synchronized (mPackages) {
10242                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10243                    }
10244                }
10245                // We just determined the app is signed correctly, so bring
10246                // over the latest parsed certs.
10247                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10248
10249
10250                // if this is is a sharedUser, check to see if the new package is signed by a newer
10251                // signing certificate than the existing one, and if so, copy over the new details
10252                if (signatureCheckPs.sharedUser != null) {
10253                    if (pkg.mSigningDetails.hasAncestor(
10254                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10255                        signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10256                    }
10257                    if (signatureCheckPs.sharedUser.signaturesChanged == null) {
10258                        signatureCheckPs.sharedUser.signaturesChanged = Boolean.FALSE;
10259                    }
10260                }
10261            } catch (PackageManagerException e) {
10262                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10263                    throw e;
10264                }
10265                // The signature has changed, but this package is in the system
10266                // image...  let's recover!
10267                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10268
10269                // If the system app is part of a shared user we allow that shared user to change
10270                // signatures as well as part of an OTA. We still need to verify that the signatures
10271                // are consistent within the shared user for a given boot, so only allow updating
10272                // the signatures on the first package scanned for the shared user (i.e. if the
10273                // signaturesChanged state hasn't been initialized yet in SharedUserSetting).
10274                if (signatureCheckPs.sharedUser != null) {
10275                    if (signatureCheckPs.sharedUser.signaturesChanged != null &&
10276                        compareSignatures(
10277                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10278                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10279                        throw new PackageManagerException(
10280                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10281                                "Signature mismatch for shared user: " + pkgSetting.sharedUser);
10282                    }
10283
10284                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10285                    signatureCheckPs.sharedUser.signaturesChanged = Boolean.TRUE;
10286                }
10287                // File a report about this.
10288                String msg = "System package " + pkg.packageName
10289                        + " signature changed; retaining data.";
10290                reportSettingsProblem(Log.WARN, msg);
10291            } catch (IllegalArgumentException e) {
10292
10293                // should never happen: certs matched when checking, but not when comparing
10294                // old to new for sharedUser
10295                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10296                        "Signing certificates comparison made on incomparable signing details"
10297                        + " but somehow passed verifySignatures!");
10298            }
10299        }
10300
10301        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10302            // This package wants to adopt ownership of permissions from
10303            // another package.
10304            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10305                final String origName = pkg.mAdoptPermissions.get(i);
10306                final PackageSetting orig = mSettings.getPackageLPr(origName);
10307                if (orig != null) {
10308                    if (verifyPackageUpdateLPr(orig, pkg)) {
10309                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10310                                + pkg.packageName);
10311                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10312                    }
10313                }
10314            }
10315        }
10316
10317        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10318            for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
10319                final String codePathString = changedAbiCodePath.get(i);
10320                try {
10321                    mInstaller.rmdex(codePathString,
10322                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10323                } catch (InstallerException ignored) {
10324                }
10325            }
10326        }
10327
10328        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10329            if (oldPkgSetting != null) {
10330                synchronized (mPackages) {
10331                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10332                }
10333            }
10334        } else {
10335            final int userId = user == null ? 0 : user.getIdentifier();
10336            // Modify state for the given package setting
10337            commitPackageSettings(pkg, oldPkg, pkgSetting, user, scanFlags,
10338                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10339            if (pkgSetting.getInstantApp(userId)) {
10340                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10341            }
10342        }
10343    }
10344
10345    /**
10346     * Returns the "real" name of the package.
10347     * <p>This may differ from the package's actual name if the application has already
10348     * been installed under one of this package's original names.
10349     */
10350    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10351            @Nullable String renamedPkgName) {
10352        if (isPackageRenamed(pkg, renamedPkgName)) {
10353            return pkg.mRealPackage;
10354        }
10355        return null;
10356    }
10357
10358    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10359    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10360            @Nullable String renamedPkgName) {
10361        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10362    }
10363
10364    /**
10365     * Returns the original package setting.
10366     * <p>A package can migrate its name during an update. In this scenario, a package
10367     * designates a set of names that it considers as one of its original names.
10368     * <p>An original package must be signed identically and it must have the same
10369     * shared user [if any].
10370     */
10371    @GuardedBy("mPackages")
10372    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10373            @Nullable String renamedPkgName) {
10374        if (!isPackageRenamed(pkg, renamedPkgName)) {
10375            return null;
10376        }
10377        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10378            final PackageSetting originalPs =
10379                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10380            if (originalPs != null) {
10381                // the package is already installed under its original name...
10382                // but, should we use it?
10383                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10384                    // the new package is incompatible with the original
10385                    continue;
10386                } else if (originalPs.sharedUser != null) {
10387                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10388                        // the shared user id is incompatible with the original
10389                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10390                                + " to " + pkg.packageName + ": old uid "
10391                                + originalPs.sharedUser.name
10392                                + " differs from " + pkg.mSharedUserId);
10393                        continue;
10394                    }
10395                    // TODO: Add case when shared user id is added [b/28144775]
10396                } else {
10397                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10398                            + pkg.packageName + " to old name " + originalPs.name);
10399                }
10400                return originalPs;
10401            }
10402        }
10403        return null;
10404    }
10405
10406    /**
10407     * Renames the package if it was installed under a different name.
10408     * <p>When we've already installed the package under an original name, update
10409     * the new package so we can continue to have the old name.
10410     */
10411    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10412            @NonNull String renamedPackageName) {
10413        if (pkg.mOriginalPackages == null
10414                || !pkg.mOriginalPackages.contains(renamedPackageName)
10415                || pkg.packageName.equals(renamedPackageName)) {
10416            return;
10417        }
10418        pkg.setPackageName(renamedPackageName);
10419    }
10420
10421    /**
10422     * Just scans the package without any side effects.
10423     * <p>Not entirely true at the moment. There is still one side effect -- this
10424     * method potentially modifies a live {@link PackageSetting} object representing
10425     * the package being scanned. This will be resolved in the future.
10426     *
10427     * @param request Information about the package to be scanned
10428     * @param isUnderFactoryTest Whether or not the device is under factory test
10429     * @param currentTime The current time, in millis
10430     * @return The results of the scan
10431     */
10432    @GuardedBy("mInstallLock")
10433    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10434            boolean isUnderFactoryTest, long currentTime)
10435                    throws PackageManagerException {
10436        final PackageParser.Package pkg = request.pkg;
10437        PackageSetting pkgSetting = request.pkgSetting;
10438        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10439        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10440        final @ParseFlags int parseFlags = request.parseFlags;
10441        final @ScanFlags int scanFlags = request.scanFlags;
10442        final String realPkgName = request.realPkgName;
10443        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10444        final UserHandle user = request.user;
10445        final boolean isPlatformPackage = request.isPlatformPackage;
10446
10447        List<String> changedAbiCodePath = null;
10448
10449        if (DEBUG_PACKAGE_SCANNING) {
10450            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10451                Log.d(TAG, "Scanning package " + pkg.packageName);
10452        }
10453
10454        DexManager.maybeLogUnexpectedPackageDetails(pkg);
10455
10456        // Initialize package source and resource directories
10457        final File scanFile = new File(pkg.codePath);
10458        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10459        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10460
10461        // We keep references to the derived CPU Abis from settings in oder to reuse
10462        // them in the case where we're not upgrading or booting for the first time.
10463        String primaryCpuAbiFromSettings = null;
10464        String secondaryCpuAbiFromSettings = null;
10465        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10466
10467        if (!needToDeriveAbi) {
10468            if (pkgSetting != null) {
10469                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10470                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10471            } else {
10472                // Re-scanning a system package after uninstalling updates; need to derive ABI
10473                needToDeriveAbi = true;
10474            }
10475        }
10476
10477        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10478            PackageManagerService.reportSettingsProblem(Log.WARN,
10479                    "Package " + pkg.packageName + " shared user changed from "
10480                            + (pkgSetting.sharedUser != null
10481                            ? pkgSetting.sharedUser.name : "<nothing>")
10482                            + " to "
10483                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10484                            + "; replacing with new");
10485            pkgSetting = null;
10486        }
10487
10488        String[] usesStaticLibraries = null;
10489        if (pkg.usesStaticLibraries != null) {
10490            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10491            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10492        }
10493        final boolean createNewPackage = (pkgSetting == null);
10494        if (createNewPackage) {
10495            final String parentPackageName = (pkg.parentPackage != null)
10496                    ? pkg.parentPackage.packageName : null;
10497            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10498            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10499            // REMOVE SharedUserSetting from method; update in a separate call
10500            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10501                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10502                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10503                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10504                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10505                    user, true /*allowInstall*/, instantApp, virtualPreload,
10506                    parentPackageName, pkg.getChildPackageNames(),
10507                    UserManagerService.getInstance(), usesStaticLibraries,
10508                    pkg.usesStaticLibrariesVersions);
10509        } else {
10510            // REMOVE SharedUserSetting from method; update in a separate call.
10511            //
10512            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10513            // secondaryCpuAbi are not known at this point so we always update them
10514            // to null here, only to reset them at a later point.
10515            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10516                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10517                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10518                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10519                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10520                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10521        }
10522        if (createNewPackage && originalPkgSetting != null) {
10523            // This is the initial transition from the original package, so,
10524            // fix up the new package's name now. We must do this after looking
10525            // up the package under its new name, so getPackageLP takes care of
10526            // fiddling things correctly.
10527            pkg.setPackageName(originalPkgSetting.name);
10528
10529            // File a report about this.
10530            String msg = "New package " + pkgSetting.realName
10531                    + " renamed to replace old package " + pkgSetting.name;
10532            reportSettingsProblem(Log.WARN, msg);
10533        }
10534
10535        final int userId = (user == null ? UserHandle.USER_SYSTEM : user.getIdentifier());
10536        // for existing packages, change the install state; but, only if it's explicitly specified
10537        if (!createNewPackage) {
10538            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10539            final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
10540            setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
10541        }
10542
10543        if (disabledPkgSetting != null) {
10544            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10545        }
10546
10547        // Apps which share a sharedUserId must be placed in the same selinux domain. If this
10548        // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its
10549        // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be
10550        // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the
10551        // least restrictive selinux domain.
10552        // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion
10553        // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This
10554        // ensures that all packages continue to run in the same selinux domain.
10555        final int targetSdkVersion =
10556            ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ?
10557            sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion;
10558        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10559        // They currently can be if the sharedUser apps are signed with the platform key.
10560        final boolean isPrivileged = (sharedUserSetting != null) ?
10561            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10562
10563        pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged,
10564                pkg.applicationInfo.targetSandboxVersion, targetSdkVersion);
10565        pkg.applicationInfo.seInfoUser = SELinuxUtil.assignSeinfoUser(pkgSetting.readUserState(
10566                userId == UserHandle.USER_ALL ? UserHandle.USER_SYSTEM : userId));
10567
10568        pkg.mExtras = pkgSetting;
10569        pkg.applicationInfo.processName = fixProcessName(
10570                pkg.applicationInfo.packageName,
10571                pkg.applicationInfo.processName);
10572
10573        if (!isPlatformPackage) {
10574            // Get all of our default paths setup
10575            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10576        }
10577
10578        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10579
10580        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10581            if (needToDeriveAbi) {
10582                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10583                final boolean extractNativeLibs = !pkg.isLibrary();
10584                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10585                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10586
10587                // Some system apps still use directory structure for native libraries
10588                // in which case we might end up not detecting abi solely based on apk
10589                // structure. Try to detect abi based on directory structure.
10590                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10591                        pkg.applicationInfo.primaryCpuAbi == null) {
10592                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10593                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10594                }
10595            } else {
10596                // This is not a first boot or an upgrade, don't bother deriving the
10597                // ABI during the scan. Instead, trust the value that was stored in the
10598                // package setting.
10599                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10600                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10601
10602                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10603
10604                if (DEBUG_ABI_SELECTION) {
10605                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10606                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10607                            pkg.applicationInfo.secondaryCpuAbi);
10608                }
10609            }
10610        } else {
10611            if ((scanFlags & SCAN_MOVE) != 0) {
10612                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10613                // but we already have this packages package info in the PackageSetting. We just
10614                // use that and derive the native library path based on the new codepath.
10615                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10616                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10617            }
10618
10619            // Set native library paths again. For moves, the path will be updated based on the
10620            // ABIs we've determined above. For non-moves, the path will be updated based on the
10621            // ABIs we determined during compilation, but the path will depend on the final
10622            // package path (after the rename away from the stage path).
10623            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10624        }
10625
10626        // This is a special case for the "system" package, where the ABI is
10627        // dictated by the zygote configuration (and init.rc). We should keep track
10628        // of this ABI so that we can deal with "normal" applications that run under
10629        // the same UID correctly.
10630        if (isPlatformPackage) {
10631            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10632                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10633        }
10634
10635        // If there's a mismatch between the abi-override in the package setting
10636        // and the abiOverride specified for the install. Warn about this because we
10637        // would've already compiled the app without taking the package setting into
10638        // account.
10639        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10640            if (cpuAbiOverride == null && pkg.packageName != null) {
10641                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10642                        " for package " + pkg.packageName);
10643            }
10644        }
10645
10646        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10647        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10648        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10649
10650        // Copy the derived override back to the parsed package, so that we can
10651        // update the package settings accordingly.
10652        pkg.cpuAbiOverride = cpuAbiOverride;
10653
10654        if (DEBUG_ABI_SELECTION) {
10655            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10656                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10657                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10658        }
10659
10660        // Push the derived path down into PackageSettings so we know what to
10661        // clean up at uninstall time.
10662        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10663
10664        if (DEBUG_ABI_SELECTION) {
10665            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10666                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10667                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10668        }
10669
10670        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10671            // We don't do this here during boot because we can do it all
10672            // at once after scanning all existing packages.
10673            //
10674            // We also do this *before* we perform dexopt on this package, so that
10675            // we can avoid redundant dexopts, and also to make sure we've got the
10676            // code and package path correct.
10677            changedAbiCodePath =
10678                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10679        }
10680
10681        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10682                android.Manifest.permission.FACTORY_TEST)) {
10683            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10684        }
10685
10686        if (isSystemApp(pkg)) {
10687            pkgSetting.isOrphaned = true;
10688        }
10689
10690        // Take care of first install / last update times.
10691        final long scanFileTime = getLastModifiedTime(pkg);
10692        if (currentTime != 0) {
10693            if (pkgSetting.firstInstallTime == 0) {
10694                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10695            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10696                pkgSetting.lastUpdateTime = currentTime;
10697            }
10698        } else if (pkgSetting.firstInstallTime == 0) {
10699            // We need *something*.  Take time time stamp of the file.
10700            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10701        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10702            if (scanFileTime != pkgSetting.timeStamp) {
10703                // A package on the system image has changed; consider this
10704                // to be an update.
10705                pkgSetting.lastUpdateTime = scanFileTime;
10706            }
10707        }
10708        pkgSetting.setTimeStamp(scanFileTime);
10709
10710        pkgSetting.pkg = pkg;
10711        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10712        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10713            pkgSetting.versionCode = pkg.getLongVersionCode();
10714        }
10715        // Update volume if needed
10716        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10717        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10718            Slog.i(PackageManagerService.TAG,
10719                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10720                    + " package " + pkg.packageName
10721                    + " volume from " + pkgSetting.volumeUuid
10722                    + " to " + volumeUuid);
10723            pkgSetting.volumeUuid = volumeUuid;
10724        }
10725
10726        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10727    }
10728
10729    /**
10730     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10731     */
10732    private static boolean apkHasCode(String fileName) {
10733        StrictJarFile jarFile = null;
10734        try {
10735            jarFile = new StrictJarFile(fileName,
10736                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10737            return jarFile.findEntry("classes.dex") != null;
10738        } catch (IOException ignore) {
10739        } finally {
10740            try {
10741                if (jarFile != null) {
10742                    jarFile.close();
10743                }
10744            } catch (IOException ignore) {}
10745        }
10746        return false;
10747    }
10748
10749    /**
10750     * Enforces code policy for the package. This ensures that if an APK has
10751     * declared hasCode="true" in its manifest that the APK actually contains
10752     * code.
10753     *
10754     * @throws PackageManagerException If bytecode could not be found when it should exist
10755     */
10756    private static void assertCodePolicy(PackageParser.Package pkg)
10757            throws PackageManagerException {
10758        final boolean shouldHaveCode =
10759                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10760        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10761            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10762                    "Package " + pkg.baseCodePath + " code is missing");
10763        }
10764
10765        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10766            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10767                final boolean splitShouldHaveCode =
10768                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10769                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10770                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10771                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10772                }
10773            }
10774        }
10775    }
10776
10777    /**
10778     * Applies policy to the parsed package based upon the given policy flags.
10779     * Ensures the package is in a good state.
10780     * <p>
10781     * Implementation detail: This method must NOT have any side effect. It would
10782     * ideally be static, but, it requires locks to read system state.
10783     */
10784    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10785            final @ScanFlags int scanFlags, PackageParser.Package platformPkg) {
10786        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10787            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10788            if (pkg.applicationInfo.isDirectBootAware()) {
10789                // we're direct boot aware; set for all components
10790                for (PackageParser.Service s : pkg.services) {
10791                    s.info.encryptionAware = s.info.directBootAware = true;
10792                }
10793                for (PackageParser.Provider p : pkg.providers) {
10794                    p.info.encryptionAware = p.info.directBootAware = true;
10795                }
10796                for (PackageParser.Activity a : pkg.activities) {
10797                    a.info.encryptionAware = a.info.directBootAware = true;
10798                }
10799                for (PackageParser.Activity r : pkg.receivers) {
10800                    r.info.encryptionAware = r.info.directBootAware = true;
10801                }
10802            }
10803            if (compressedFileExists(pkg.codePath)) {
10804                pkg.isStub = true;
10805            }
10806        } else {
10807            // non system apps can't be flagged as core
10808            pkg.coreApp = false;
10809            // clear flags not applicable to regular apps
10810            pkg.applicationInfo.flags &=
10811                    ~ApplicationInfo.FLAG_PERSISTENT;
10812            pkg.applicationInfo.privateFlags &=
10813                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10814            pkg.applicationInfo.privateFlags &=
10815                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10816            // cap permission priorities
10817            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10818                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10819                    pkg.permissionGroups.get(i).info.priority = 0;
10820                }
10821            }
10822        }
10823        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10824            // clear protected broadcasts
10825            pkg.protectedBroadcasts = null;
10826            // ignore export request for single user receivers
10827            if (pkg.receivers != null) {
10828                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10829                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10830                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10831                        receiver.info.exported = false;
10832                    }
10833                }
10834            }
10835            // ignore export request for single user services
10836            if (pkg.services != null) {
10837                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10838                    final PackageParser.Service service = pkg.services.get(i);
10839                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10840                        service.info.exported = false;
10841                    }
10842                }
10843            }
10844            // ignore export request for single user providers
10845            if (pkg.providers != null) {
10846                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10847                    final PackageParser.Provider provider = pkg.providers.get(i);
10848                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10849                        provider.info.exported = false;
10850                    }
10851                }
10852            }
10853        }
10854
10855        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10856            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10857        }
10858
10859        if ((scanFlags & SCAN_AS_OEM) != 0) {
10860            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10861        }
10862
10863        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10864            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10865        }
10866
10867        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10868            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10869        }
10870
10871        // Check if the package is signed with the same key as the platform package.
10872        if (PLATFORM_PACKAGE_NAME.equals(pkg.packageName) ||
10873                (platformPkg != null && compareSignatures(
10874                        platformPkg.mSigningDetails.signatures,
10875                        pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH)) {
10876            pkg.applicationInfo.privateFlags |=
10877                ApplicationInfo.PRIVATE_FLAG_SIGNED_WITH_PLATFORM_KEY;
10878        }
10879
10880        if (!isSystemApp(pkg)) {
10881            // Only system apps can use these features.
10882            pkg.mOriginalPackages = null;
10883            pkg.mRealPackage = null;
10884            pkg.mAdoptPermissions = null;
10885        }
10886    }
10887
10888    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10889            throws PackageManagerException {
10890        if (object == null) {
10891            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10892        }
10893        return object;
10894    }
10895
10896    /**
10897     * Asserts the parsed package is valid according to the given policy. If the
10898     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10899     * <p>
10900     * Implementation detail: This method must NOT have any side effects. It would
10901     * ideally be static, but, it requires locks to read system state.
10902     *
10903     * @throws PackageManagerException If the package fails any of the validation checks
10904     */
10905    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10906            final @ScanFlags int scanFlags)
10907                    throws PackageManagerException {
10908        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10909            assertCodePolicy(pkg);
10910        }
10911
10912        if (pkg.applicationInfo.getCodePath() == null ||
10913                pkg.applicationInfo.getResourcePath() == null) {
10914            // Bail out. The resource and code paths haven't been set.
10915            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10916                    "Code and resource paths haven't been set correctly");
10917        }
10918
10919        // Make sure we're not adding any bogus keyset info
10920        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10921        ksms.assertScannedPackageValid(pkg);
10922
10923        synchronized (mPackages) {
10924            // The special "android" package can only be defined once
10925            if (pkg.packageName.equals("android")) {
10926                if (mAndroidApplication != null) {
10927                    Slog.w(TAG, "*************************************************");
10928                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10929                    Slog.w(TAG, " codePath=" + pkg.codePath);
10930                    Slog.w(TAG, "*************************************************");
10931                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10932                            "Core android package being redefined.  Skipping.");
10933                }
10934            }
10935
10936            // A package name must be unique; don't allow duplicates
10937            if (mPackages.containsKey(pkg.packageName)) {
10938                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10939                        "Application package " + pkg.packageName
10940                        + " already installed.  Skipping duplicate.");
10941            }
10942
10943            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10944                // Static libs have a synthetic package name containing the version
10945                // but we still want the base name to be unique.
10946                if (mPackages.containsKey(pkg.manifestPackageName)) {
10947                    throw new PackageManagerException(
10948                            "Duplicate static shared lib provider package");
10949                }
10950
10951                // Static shared libraries should have at least O target SDK
10952                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10953                    throw new PackageManagerException(
10954                            "Packages declaring static-shared libs must target O SDK or higher");
10955                }
10956
10957                // Package declaring static a shared lib cannot be instant apps
10958                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10959                    throw new PackageManagerException(
10960                            "Packages declaring static-shared libs cannot be instant apps");
10961                }
10962
10963                // Package declaring static a shared lib cannot be renamed since the package
10964                // name is synthetic and apps can't code around package manager internals.
10965                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10966                    throw new PackageManagerException(
10967                            "Packages declaring static-shared libs cannot be renamed");
10968                }
10969
10970                // Package declaring static a shared lib cannot declare child packages
10971                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10972                    throw new PackageManagerException(
10973                            "Packages declaring static-shared libs cannot have child packages");
10974                }
10975
10976                // Package declaring static a shared lib cannot declare dynamic libs
10977                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10978                    throw new PackageManagerException(
10979                            "Packages declaring static-shared libs cannot declare dynamic libs");
10980                }
10981
10982                // Package declaring static a shared lib cannot declare shared users
10983                if (pkg.mSharedUserId != null) {
10984                    throw new PackageManagerException(
10985                            "Packages declaring static-shared libs cannot declare shared users");
10986                }
10987
10988                // Static shared libs cannot declare activities
10989                if (!pkg.activities.isEmpty()) {
10990                    throw new PackageManagerException(
10991                            "Static shared libs cannot declare activities");
10992                }
10993
10994                // Static shared libs cannot declare services
10995                if (!pkg.services.isEmpty()) {
10996                    throw new PackageManagerException(
10997                            "Static shared libs cannot declare services");
10998                }
10999
11000                // Static shared libs cannot declare providers
11001                if (!pkg.providers.isEmpty()) {
11002                    throw new PackageManagerException(
11003                            "Static shared libs cannot declare content providers");
11004                }
11005
11006                // Static shared libs cannot declare receivers
11007                if (!pkg.receivers.isEmpty()) {
11008                    throw new PackageManagerException(
11009                            "Static shared libs cannot declare broadcast receivers");
11010                }
11011
11012                // Static shared libs cannot declare permission groups
11013                if (!pkg.permissionGroups.isEmpty()) {
11014                    throw new PackageManagerException(
11015                            "Static shared libs cannot declare permission groups");
11016                }
11017
11018                // Static shared libs cannot declare permissions
11019                if (!pkg.permissions.isEmpty()) {
11020                    throw new PackageManagerException(
11021                            "Static shared libs cannot declare permissions");
11022                }
11023
11024                // Static shared libs cannot declare protected broadcasts
11025                if (pkg.protectedBroadcasts != null) {
11026                    throw new PackageManagerException(
11027                            "Static shared libs cannot declare protected broadcasts");
11028                }
11029
11030                // Static shared libs cannot be overlay targets
11031                if (pkg.mOverlayTarget != null) {
11032                    throw new PackageManagerException(
11033                            "Static shared libs cannot be overlay targets");
11034                }
11035
11036                // The version codes must be ordered as lib versions
11037                long minVersionCode = Long.MIN_VALUE;
11038                long maxVersionCode = Long.MAX_VALUE;
11039
11040                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11041                        pkg.staticSharedLibName);
11042                if (versionedLib != null) {
11043                    final int versionCount = versionedLib.size();
11044                    for (int i = 0; i < versionCount; i++) {
11045                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11046                        final long libVersionCode = libInfo.getDeclaringPackage()
11047                                .getLongVersionCode();
11048                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
11049                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11050                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
11051                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11052                        } else {
11053                            minVersionCode = maxVersionCode = libVersionCode;
11054                            break;
11055                        }
11056                    }
11057                }
11058                if (pkg.getLongVersionCode() < minVersionCode
11059                        || pkg.getLongVersionCode() > maxVersionCode) {
11060                    throw new PackageManagerException("Static shared"
11061                            + " lib version codes must be ordered as lib versions");
11062                }
11063            }
11064
11065            // Only privileged apps and updated privileged apps can add child packages.
11066            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11067                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
11068                    throw new PackageManagerException("Only privileged apps can add child "
11069                            + "packages. Ignoring package " + pkg.packageName);
11070                }
11071                final int childCount = pkg.childPackages.size();
11072                for (int i = 0; i < childCount; i++) {
11073                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11074                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11075                            childPkg.packageName)) {
11076                        throw new PackageManagerException("Can't override child of "
11077                                + "another disabled app. Ignoring package " + pkg.packageName);
11078                    }
11079                }
11080            }
11081
11082            // If we're only installing presumed-existing packages, require that the
11083            // scanned APK is both already known and at the path previously established
11084            // for it.  Previously unknown packages we pick up normally, but if we have an
11085            // a priori expectation about this package's install presence, enforce it.
11086            // With a singular exception for new system packages. When an OTA contains
11087            // a new system package, we allow the codepath to change from a system location
11088            // to the user-installed location. If we don't allow this change, any newer,
11089            // user-installed version of the application will be ignored.
11090            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11091                if (mExpectingBetter.containsKey(pkg.packageName)) {
11092                    logCriticalInfo(Log.WARN,
11093                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11094                } else {
11095                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11096                    if (known != null) {
11097                        if (DEBUG_PACKAGE_SCANNING) {
11098                            Log.d(TAG, "Examining " + pkg.codePath
11099                                    + " and requiring known paths " + known.codePathString
11100                                    + " & " + known.resourcePathString);
11101                        }
11102                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11103                                || !pkg.applicationInfo.getResourcePath().equals(
11104                                        known.resourcePathString)) {
11105                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11106                                    "Application package " + pkg.packageName
11107                                    + " found at " + pkg.applicationInfo.getCodePath()
11108                                    + " but expected at " + known.codePathString
11109                                    + "; ignoring.");
11110                        }
11111                    } else {
11112                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11113                                "Application package " + pkg.packageName
11114                                + " not found; ignoring.");
11115                    }
11116                }
11117            }
11118
11119            // Verify that this new package doesn't have any content providers
11120            // that conflict with existing packages.  Only do this if the
11121            // package isn't already installed, since we don't want to break
11122            // things that are installed.
11123            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11124                final int N = pkg.providers.size();
11125                int i;
11126                for (i=0; i<N; i++) {
11127                    PackageParser.Provider p = pkg.providers.get(i);
11128                    if (p.info.authority != null) {
11129                        String names[] = p.info.authority.split(";");
11130                        for (int j = 0; j < names.length; j++) {
11131                            if (mProvidersByAuthority.containsKey(names[j])) {
11132                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11133                                final String otherPackageName =
11134                                        ((other != null && other.getComponentName() != null) ?
11135                                                other.getComponentName().getPackageName() : "?");
11136                                throw new PackageManagerException(
11137                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11138                                        "Can't install because provider name " + names[j]
11139                                                + " (in package " + pkg.applicationInfo.packageName
11140                                                + ") is already used by " + otherPackageName);
11141                            }
11142                        }
11143                    }
11144                }
11145            }
11146
11147            // Verify that packages sharing a user with a privileged app are marked as privileged.
11148            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
11149                SharedUserSetting sharedUserSetting = null;
11150                try {
11151                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
11152                } catch (PackageManagerException ignore) {}
11153                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
11154                    // Exempt SharedUsers signed with the platform key.
11155                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
11156                    if ((platformPkgSetting.signatures.mSigningDetails
11157                            != PackageParser.SigningDetails.UNKNOWN)
11158                            && (compareSignatures(
11159                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11160                                    pkg.mSigningDetails.signatures)
11161                                            != PackageManager.SIGNATURE_MATCH)) {
11162                        throw new PackageManagerException("Apps that share a user with a " +
11163                                "privileged app must themselves be marked as privileged. " +
11164                                pkg.packageName + " shares privileged user " +
11165                                pkg.mSharedUserId + ".");
11166                    }
11167                }
11168            }
11169
11170            // Apply policies specific for runtime resource overlays (RROs).
11171            if (pkg.mOverlayTarget != null) {
11172                // System overlays have some restrictions on their use of the 'static' state.
11173                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11174                    // We are scanning a system overlay. This can be the first scan of the
11175                    // system/vendor/oem partition, or an update to the system overlay.
11176                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11177                        // This must be an update to a system overlay.
11178                        final PackageSetting previousPkg = assertNotNull(
11179                                mSettings.getPackageLPr(pkg.packageName),
11180                                "previous package state not present");
11181
11182                        // previousPkg.pkg may be null: the package will be not be scanned if the
11183                        // package manager knows there is a newer version on /data.
11184                        // TODO[b/79435695]: Find a better way to keep track of the "static"
11185                        // property for RROs instead of having to parse packages on /system
11186                        PackageParser.Package ppkg = previousPkg.pkg;
11187                        if (ppkg == null) {
11188                            try {
11189                                final PackageParser pp = new PackageParser();
11190                                ppkg = pp.parsePackage(previousPkg.codePath,
11191                                        parseFlags | PackageParser.PARSE_IS_SYSTEM_DIR);
11192                            } catch (PackageParserException e) {
11193                                Slog.w(TAG, "failed to parse " + previousPkg.codePath, e);
11194                            }
11195                        }
11196
11197                        // Static overlays cannot be updated.
11198                        if (ppkg != null && ppkg.mOverlayIsStatic) {
11199                            throw new PackageManagerException("Overlay " + pkg.packageName +
11200                                    " is static and cannot be upgraded.");
11201                        // Non-static overlays cannot be converted to static overlays.
11202                        } else if (pkg.mOverlayIsStatic) {
11203                            throw new PackageManagerException("Overlay " + pkg.packageName +
11204                                    " cannot be upgraded into a static overlay.");
11205                        }
11206                    }
11207                } else {
11208                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11209                    if (pkg.mOverlayIsStatic) {
11210                        throw new PackageManagerException("Overlay " + pkg.packageName +
11211                                " is static but not pre-installed.");
11212                    }
11213
11214                    // The only case where we allow installation of a non-system overlay is when
11215                    // its signature is signed with the platform certificate.
11216                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11217                    if ((platformPkgSetting.signatures.mSigningDetails
11218                            != PackageParser.SigningDetails.UNKNOWN)
11219                            && (compareSignatures(
11220                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11221                                    pkg.mSigningDetails.signatures)
11222                                            != PackageManager.SIGNATURE_MATCH)) {
11223                        throw new PackageManagerException("Overlay " + pkg.packageName +
11224                                " must be signed with the platform certificate.");
11225                    }
11226                }
11227            }
11228        }
11229    }
11230
11231    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11232            int type, String declaringPackageName, long declaringVersionCode) {
11233        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11234        if (versionedLib == null) {
11235            versionedLib = new LongSparseArray<>();
11236            mSharedLibraries.put(name, versionedLib);
11237            if (type == SharedLibraryInfo.TYPE_STATIC) {
11238                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11239            }
11240        } else if (versionedLib.indexOfKey(version) >= 0) {
11241            return false;
11242        }
11243        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11244                version, type, declaringPackageName, declaringVersionCode);
11245        versionedLib.put(version, libEntry);
11246        return true;
11247    }
11248
11249    private boolean removeSharedLibraryLPw(String name, long version) {
11250        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11251        if (versionedLib == null) {
11252            return false;
11253        }
11254        final int libIdx = versionedLib.indexOfKey(version);
11255        if (libIdx < 0) {
11256            return false;
11257        }
11258        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11259        versionedLib.remove(version);
11260        if (versionedLib.size() <= 0) {
11261            mSharedLibraries.remove(name);
11262            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11263                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11264                        .getPackageName());
11265            }
11266        }
11267        return true;
11268    }
11269
11270    /**
11271     * Adds a scanned package to the system. When this method is finished, the package will
11272     * be available for query, resolution, etc...
11273     */
11274    private void commitPackageSettings(PackageParser.Package pkg,
11275            @Nullable PackageParser.Package oldPkg, PackageSetting pkgSetting, UserHandle user,
11276            final @ScanFlags int scanFlags, boolean chatty) {
11277        final String pkgName = pkg.packageName;
11278        if (mCustomResolverComponentName != null &&
11279                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11280            setUpCustomResolverActivity(pkg);
11281        }
11282
11283        if (pkg.packageName.equals("android")) {
11284            synchronized (mPackages) {
11285                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11286                    // Set up information for our fall-back user intent resolution activity.
11287                    mPlatformPackage = pkg;
11288                    pkg.mVersionCode = mSdkVersion;
11289                    pkg.mVersionCodeMajor = 0;
11290                    mAndroidApplication = pkg.applicationInfo;
11291                    if (!mResolverReplaced) {
11292                        mResolveActivity.applicationInfo = mAndroidApplication;
11293                        mResolveActivity.name = ResolverActivity.class.getName();
11294                        mResolveActivity.packageName = mAndroidApplication.packageName;
11295                        mResolveActivity.processName = "system:ui";
11296                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11297                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11298                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11299                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11300                        mResolveActivity.exported = true;
11301                        mResolveActivity.enabled = true;
11302                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11303                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11304                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11305                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11306                                | ActivityInfo.CONFIG_ORIENTATION
11307                                | ActivityInfo.CONFIG_KEYBOARD
11308                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11309                        mResolveInfo.activityInfo = mResolveActivity;
11310                        mResolveInfo.priority = 0;
11311                        mResolveInfo.preferredOrder = 0;
11312                        mResolveInfo.match = 0;
11313                        mResolveComponentName = new ComponentName(
11314                                mAndroidApplication.packageName, mResolveActivity.name);
11315                    }
11316                }
11317            }
11318        }
11319
11320        ArrayList<PackageParser.Package> clientLibPkgs = null;
11321        // writer
11322        synchronized (mPackages) {
11323            boolean hasStaticSharedLibs = false;
11324
11325            // Any app can add new static shared libraries
11326            if (pkg.staticSharedLibName != null) {
11327                // Static shared libs don't allow renaming as they have synthetic package
11328                // names to allow install of multiple versions, so use name from manifest.
11329                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11330                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11331                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11332                    hasStaticSharedLibs = true;
11333                } else {
11334                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11335                                + pkg.staticSharedLibName + " already exists; skipping");
11336                }
11337                // Static shared libs cannot be updated once installed since they
11338                // use synthetic package name which includes the version code, so
11339                // not need to update other packages's shared lib dependencies.
11340            }
11341
11342            if (!hasStaticSharedLibs
11343                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11344                // Only system apps can add new dynamic shared libraries.
11345                if (pkg.libraryNames != null) {
11346                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11347                        String name = pkg.libraryNames.get(i);
11348                        boolean allowed = false;
11349                        if (pkg.isUpdatedSystemApp()) {
11350                            // New library entries can only be added through the
11351                            // system image.  This is important to get rid of a lot
11352                            // of nasty edge cases: for example if we allowed a non-
11353                            // system update of the app to add a library, then uninstalling
11354                            // the update would make the library go away, and assumptions
11355                            // we made such as through app install filtering would now
11356                            // have allowed apps on the device which aren't compatible
11357                            // with it.  Better to just have the restriction here, be
11358                            // conservative, and create many fewer cases that can negatively
11359                            // impact the user experience.
11360                            final PackageSetting sysPs = mSettings
11361                                    .getDisabledSystemPkgLPr(pkg.packageName);
11362                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11363                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11364                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11365                                        allowed = true;
11366                                        break;
11367                                    }
11368                                }
11369                            }
11370                        } else {
11371                            allowed = true;
11372                        }
11373                        if (allowed) {
11374                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11375                                    SharedLibraryInfo.VERSION_UNDEFINED,
11376                                    SharedLibraryInfo.TYPE_DYNAMIC,
11377                                    pkg.packageName, pkg.getLongVersionCode())) {
11378                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11379                                        + name + " already exists; skipping");
11380                            }
11381                        } else {
11382                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11383                                    + name + " that is not declared on system image; skipping");
11384                        }
11385                    }
11386
11387                    if ((scanFlags & SCAN_BOOTING) == 0) {
11388                        // If we are not booting, we need to update any applications
11389                        // that are clients of our shared library.  If we are booting,
11390                        // this will all be done once the scan is complete.
11391                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11392                    }
11393                }
11394            }
11395        }
11396
11397        if ((scanFlags & SCAN_BOOTING) != 0) {
11398            // No apps can run during boot scan, so they don't need to be frozen
11399        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11400            // Caller asked to not kill app, so it's probably not frozen
11401        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11402            // Caller asked us to ignore frozen check for some reason; they
11403            // probably didn't know the package name
11404        } else {
11405            // We're doing major surgery on this package, so it better be frozen
11406            // right now to keep it from launching
11407            checkPackageFrozen(pkgName);
11408        }
11409
11410        // Also need to kill any apps that are dependent on the library.
11411        if (clientLibPkgs != null) {
11412            for (int i=0; i<clientLibPkgs.size(); i++) {
11413                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11414                killApplication(clientPkg.applicationInfo.packageName,
11415                        clientPkg.applicationInfo.uid, "update lib");
11416            }
11417        }
11418
11419        // writer
11420        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11421
11422        synchronized (mPackages) {
11423            // We don't expect installation to fail beyond this point
11424
11425            // Add the new setting to mSettings
11426            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11427            // Add the new setting to mPackages
11428            mPackages.put(pkg.applicationInfo.packageName, pkg);
11429            // Make sure we don't accidentally delete its data.
11430            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11431            while (iter.hasNext()) {
11432                PackageCleanItem item = iter.next();
11433                if (pkgName.equals(item.packageName)) {
11434                    iter.remove();
11435                }
11436            }
11437
11438            // Add the package's KeySets to the global KeySetManagerService
11439            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11440            ksms.addScannedPackageLPw(pkg);
11441
11442            int N = pkg.providers.size();
11443            StringBuilder r = null;
11444            int i;
11445            for (i=0; i<N; i++) {
11446                PackageParser.Provider p = pkg.providers.get(i);
11447                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11448                        p.info.processName);
11449                mProviders.addProvider(p);
11450                p.syncable = p.info.isSyncable;
11451                if (p.info.authority != null) {
11452                    String names[] = p.info.authority.split(";");
11453                    p.info.authority = null;
11454                    for (int j = 0; j < names.length; j++) {
11455                        if (j == 1 && p.syncable) {
11456                            // We only want the first authority for a provider to possibly be
11457                            // syncable, so if we already added this provider using a different
11458                            // authority clear the syncable flag. We copy the provider before
11459                            // changing it because the mProviders object contains a reference
11460                            // to a provider that we don't want to change.
11461                            // Only do this for the second authority since the resulting provider
11462                            // object can be the same for all future authorities for this provider.
11463                            p = new PackageParser.Provider(p);
11464                            p.syncable = false;
11465                        }
11466                        if (!mProvidersByAuthority.containsKey(names[j])) {
11467                            mProvidersByAuthority.put(names[j], p);
11468                            if (p.info.authority == null) {
11469                                p.info.authority = names[j];
11470                            } else {
11471                                p.info.authority = p.info.authority + ";" + names[j];
11472                            }
11473                            if (DEBUG_PACKAGE_SCANNING) {
11474                                if (chatty)
11475                                    Log.d(TAG, "Registered content provider: " + names[j]
11476                                            + ", className = " + p.info.name + ", isSyncable = "
11477                                            + p.info.isSyncable);
11478                            }
11479                        } else {
11480                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11481                            Slog.w(TAG, "Skipping provider name " + names[j] +
11482                                    " (in package " + pkg.applicationInfo.packageName +
11483                                    "): name already used by "
11484                                    + ((other != null && other.getComponentName() != null)
11485                                            ? other.getComponentName().getPackageName() : "?"));
11486                        }
11487                    }
11488                }
11489                if (chatty) {
11490                    if (r == null) {
11491                        r = new StringBuilder(256);
11492                    } else {
11493                        r.append(' ');
11494                    }
11495                    r.append(p.info.name);
11496                }
11497            }
11498            if (r != null) {
11499                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11500            }
11501
11502            N = pkg.services.size();
11503            r = null;
11504            for (i=0; i<N; i++) {
11505                PackageParser.Service s = pkg.services.get(i);
11506                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11507                        s.info.processName);
11508                mServices.addService(s);
11509                if (chatty) {
11510                    if (r == null) {
11511                        r = new StringBuilder(256);
11512                    } else {
11513                        r.append(' ');
11514                    }
11515                    r.append(s.info.name);
11516                }
11517            }
11518            if (r != null) {
11519                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11520            }
11521
11522            N = pkg.receivers.size();
11523            r = null;
11524            for (i=0; i<N; i++) {
11525                PackageParser.Activity a = pkg.receivers.get(i);
11526                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11527                        a.info.processName);
11528                mReceivers.addActivity(a, "receiver");
11529                if (chatty) {
11530                    if (r == null) {
11531                        r = new StringBuilder(256);
11532                    } else {
11533                        r.append(' ');
11534                    }
11535                    r.append(a.info.name);
11536                }
11537            }
11538            if (r != null) {
11539                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11540            }
11541
11542            N = pkg.activities.size();
11543            r = null;
11544            for (i=0; i<N; i++) {
11545                PackageParser.Activity a = pkg.activities.get(i);
11546                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11547                        a.info.processName);
11548                mActivities.addActivity(a, "activity");
11549                if (chatty) {
11550                    if (r == null) {
11551                        r = new StringBuilder(256);
11552                    } else {
11553                        r.append(' ');
11554                    }
11555                    r.append(a.info.name);
11556                }
11557            }
11558            if (r != null) {
11559                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11560            }
11561
11562            // Don't allow ephemeral applications to define new permissions groups.
11563            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11564                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11565                        + " ignored: instant apps cannot define new permission groups.");
11566            } else {
11567                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11568            }
11569
11570            // Don't allow ephemeral applications to define new permissions.
11571            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11572                Slog.w(TAG, "Permissions from package " + pkg.packageName
11573                        + " ignored: instant apps cannot define new permissions.");
11574            } else {
11575                mPermissionManager.addAllPermissions(pkg, chatty);
11576            }
11577
11578            N = pkg.instrumentation.size();
11579            r = null;
11580            for (i=0; i<N; i++) {
11581                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11582                a.info.packageName = pkg.applicationInfo.packageName;
11583                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11584                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11585                a.info.splitNames = pkg.splitNames;
11586                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11587                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11588                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11589                a.info.dataDir = pkg.applicationInfo.dataDir;
11590                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11591                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11592                a.info.primaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11593                a.info.secondaryCpuAbi = pkg.applicationInfo.secondaryCpuAbi;
11594                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11595                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11596                mInstrumentation.put(a.getComponentName(), a);
11597                if (chatty) {
11598                    if (r == null) {
11599                        r = new StringBuilder(256);
11600                    } else {
11601                        r.append(' ');
11602                    }
11603                    r.append(a.info.name);
11604                }
11605            }
11606            if (r != null) {
11607                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11608            }
11609
11610            if (pkg.protectedBroadcasts != null) {
11611                N = pkg.protectedBroadcasts.size();
11612                synchronized (mProtectedBroadcasts) {
11613                    for (i = 0; i < N; i++) {
11614                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11615                    }
11616                }
11617            }
11618
11619            if (oldPkg != null) {
11620                // We need to call revokeRuntimePermissionsIfGroupChanged async as permission
11621                // revoke callbacks from this method might need to kill apps which need the
11622                // mPackages lock on a different thread. This would dead lock.
11623                //
11624                // Hence create a copy of all package names and pass it into
11625                // revokeRuntimePermissionsIfGroupChanged. Only for those permissions might get
11626                // revoked. If a new package is added before the async code runs the permission
11627                // won't be granted yet, hence new packages are no problem.
11628                final ArrayList<String> allPackageNames = new ArrayList<>(mPackages.keySet());
11629
11630                AsyncTask.execute(() ->
11631                        mPermissionManager.revokeRuntimePermissionsIfGroupChanged(pkg, oldPkg,
11632                                allPackageNames, mPermissionCallback));
11633            }
11634        }
11635
11636        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11637    }
11638
11639    /**
11640     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11641     * is derived purely on the basis of the contents of {@code scanFile} and
11642     * {@code cpuAbiOverride}.
11643     *
11644     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11645     */
11646    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11647            boolean extractLibs)
11648                    throws PackageManagerException {
11649        // Give ourselves some initial paths; we'll come back for another
11650        // pass once we've determined ABI below.
11651        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11652
11653        // We would never need to extract libs for forward-locked and external packages,
11654        // since the container service will do it for us. We shouldn't attempt to
11655        // extract libs from system app when it was not updated.
11656        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11657                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11658            extractLibs = false;
11659        }
11660
11661        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11662        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11663
11664        NativeLibraryHelper.Handle handle = null;
11665        try {
11666            handle = NativeLibraryHelper.Handle.create(pkg);
11667            // TODO(multiArch): This can be null for apps that didn't go through the
11668            // usual installation process. We can calculate it again, like we
11669            // do during install time.
11670            //
11671            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11672            // unnecessary.
11673            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11674
11675            // Null out the abis so that they can be recalculated.
11676            pkg.applicationInfo.primaryCpuAbi = null;
11677            pkg.applicationInfo.secondaryCpuAbi = null;
11678            if (isMultiArch(pkg.applicationInfo)) {
11679                // Warn if we've set an abiOverride for multi-lib packages..
11680                // By definition, we need to copy both 32 and 64 bit libraries for
11681                // such packages.
11682                if (pkg.cpuAbiOverride != null
11683                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11684                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11685                }
11686
11687                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11688                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11689                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11690                    if (extractLibs) {
11691                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11692                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11693                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11694                                useIsaSpecificSubdirs);
11695                    } else {
11696                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11697                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11698                    }
11699                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11700                }
11701
11702                // Shared library native code should be in the APK zip aligned
11703                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11704                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11705                            "Shared library native lib extraction not supported");
11706                }
11707
11708                maybeThrowExceptionForMultiArchCopy(
11709                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11710
11711                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11712                    if (extractLibs) {
11713                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11714                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11715                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11716                                useIsaSpecificSubdirs);
11717                    } else {
11718                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11719                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11720                    }
11721                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11722                }
11723
11724                maybeThrowExceptionForMultiArchCopy(
11725                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11726
11727                if (abi64 >= 0) {
11728                    // Shared library native libs should be in the APK zip aligned
11729                    if (extractLibs && pkg.isLibrary()) {
11730                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11731                                "Shared library native lib extraction not supported");
11732                    }
11733                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11734                }
11735
11736                if (abi32 >= 0) {
11737                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11738                    if (abi64 >= 0) {
11739                        if (pkg.use32bitAbi) {
11740                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11741                            pkg.applicationInfo.primaryCpuAbi = abi;
11742                        } else {
11743                            pkg.applicationInfo.secondaryCpuAbi = abi;
11744                        }
11745                    } else {
11746                        pkg.applicationInfo.primaryCpuAbi = abi;
11747                    }
11748                }
11749            } else {
11750                String[] abiList = (cpuAbiOverride != null) ?
11751                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11752
11753                // Enable gross and lame hacks for apps that are built with old
11754                // SDK tools. We must scan their APKs for renderscript bitcode and
11755                // not launch them if it's present. Don't bother checking on devices
11756                // that don't have 64 bit support.
11757                boolean needsRenderScriptOverride = false;
11758                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11759                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11760                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11761                    needsRenderScriptOverride = true;
11762                }
11763
11764                final int copyRet;
11765                if (extractLibs) {
11766                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11767                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11768                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11769                } else {
11770                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11771                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11772                }
11773                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11774
11775                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11776                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11777                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11778                }
11779
11780                if (copyRet >= 0) {
11781                    // Shared libraries that have native libs must be multi-architecture
11782                    if (pkg.isLibrary()) {
11783                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11784                                "Shared library with native libs must be multiarch");
11785                    }
11786                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11787                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11788                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11789                } else if (needsRenderScriptOverride) {
11790                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11791                }
11792            }
11793        } catch (IOException ioe) {
11794            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11795        } finally {
11796            IoUtils.closeQuietly(handle);
11797        }
11798
11799        // Now that we've calculated the ABIs and determined if it's an internal app,
11800        // we will go ahead and populate the nativeLibraryPath.
11801        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11802    }
11803
11804    /**
11805     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11806     * i.e, so that all packages can be run inside a single process if required.
11807     *
11808     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11809     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11810     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11811     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11812     * updating a package that belongs to a shared user.
11813     *
11814     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11815     * adds unnecessary complexity.
11816     */
11817    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11818            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11819        List<String> changedAbiCodePath = null;
11820        String requiredInstructionSet = null;
11821        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11822            requiredInstructionSet = VMRuntime.getInstructionSet(
11823                     scannedPackage.applicationInfo.primaryCpuAbi);
11824        }
11825
11826        PackageSetting requirer = null;
11827        for (PackageSetting ps : packagesForUser) {
11828            // If packagesForUser contains scannedPackage, we skip it. This will happen
11829            // when scannedPackage is an update of an existing package. Without this check,
11830            // we will never be able to change the ABI of any package belonging to a shared
11831            // user, even if it's compatible with other packages.
11832            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11833                if (ps.primaryCpuAbiString == null) {
11834                    continue;
11835                }
11836
11837                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11838                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11839                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11840                    // this but there's not much we can do.
11841                    String errorMessage = "Instruction set mismatch, "
11842                            + ((requirer == null) ? "[caller]" : requirer)
11843                            + " requires " + requiredInstructionSet + " whereas " + ps
11844                            + " requires " + instructionSet;
11845                    Slog.w(TAG, errorMessage);
11846                }
11847
11848                if (requiredInstructionSet == null) {
11849                    requiredInstructionSet = instructionSet;
11850                    requirer = ps;
11851                }
11852            }
11853        }
11854
11855        if (requiredInstructionSet != null) {
11856            String adjustedAbi;
11857            if (requirer != null) {
11858                // requirer != null implies that either scannedPackage was null or that scannedPackage
11859                // did not require an ABI, in which case we have to adjust scannedPackage to match
11860                // the ABI of the set (which is the same as requirer's ABI)
11861                adjustedAbi = requirer.primaryCpuAbiString;
11862                if (scannedPackage != null) {
11863                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11864                }
11865            } else {
11866                // requirer == null implies that we're updating all ABIs in the set to
11867                // match scannedPackage.
11868                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11869            }
11870
11871            for (PackageSetting ps : packagesForUser) {
11872                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11873                    if (ps.primaryCpuAbiString != null) {
11874                        continue;
11875                    }
11876
11877                    ps.primaryCpuAbiString = adjustedAbi;
11878                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11879                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11880                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11881                        if (DEBUG_ABI_SELECTION) {
11882                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11883                                    + " (requirer="
11884                                    + (requirer != null ? requirer.pkg : "null")
11885                                    + ", scannedPackage="
11886                                    + (scannedPackage != null ? scannedPackage : "null")
11887                                    + ")");
11888                        }
11889                        if (changedAbiCodePath == null) {
11890                            changedAbiCodePath = new ArrayList<>();
11891                        }
11892                        changedAbiCodePath.add(ps.codePathString);
11893                    }
11894                }
11895            }
11896        }
11897        return changedAbiCodePath;
11898    }
11899
11900    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11901        synchronized (mPackages) {
11902            mResolverReplaced = true;
11903            // Set up information for custom user intent resolution activity.
11904            mResolveActivity.applicationInfo = pkg.applicationInfo;
11905            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11906            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11907            mResolveActivity.processName = pkg.applicationInfo.packageName;
11908            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11909            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11910                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11911            mResolveActivity.theme = 0;
11912            mResolveActivity.exported = true;
11913            mResolveActivity.enabled = true;
11914            mResolveInfo.activityInfo = mResolveActivity;
11915            mResolveInfo.priority = 0;
11916            mResolveInfo.preferredOrder = 0;
11917            mResolveInfo.match = 0;
11918            mResolveComponentName = mCustomResolverComponentName;
11919            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11920                    mResolveComponentName);
11921        }
11922    }
11923
11924    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11925        if (installerActivity == null) {
11926            if (DEBUG_INSTANT) {
11927                Slog.d(TAG, "Clear ephemeral installer activity");
11928            }
11929            mInstantAppInstallerActivity = null;
11930            return;
11931        }
11932
11933        if (DEBUG_INSTANT) {
11934            Slog.d(TAG, "Set ephemeral installer activity: "
11935                    + installerActivity.getComponentName());
11936        }
11937        // Set up information for ephemeral installer activity
11938        mInstantAppInstallerActivity = installerActivity;
11939        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11940                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11941        mInstantAppInstallerActivity.exported = true;
11942        mInstantAppInstallerActivity.enabled = true;
11943        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11944        mInstantAppInstallerInfo.priority = 1;
11945        mInstantAppInstallerInfo.preferredOrder = 1;
11946        mInstantAppInstallerInfo.isDefault = true;
11947        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11948                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11949    }
11950
11951    private static String calculateBundledApkRoot(final String codePathString) {
11952        final File codePath = new File(codePathString);
11953        final File codeRoot;
11954        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11955            codeRoot = Environment.getRootDirectory();
11956        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11957            codeRoot = Environment.getOemDirectory();
11958        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11959            codeRoot = Environment.getVendorDirectory();
11960        } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) {
11961            codeRoot = Environment.getOdmDirectory();
11962        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11963            codeRoot = Environment.getProductDirectory();
11964        } else {
11965            // Unrecognized code path; take its top real segment as the apk root:
11966            // e.g. /something/app/blah.apk => /something
11967            try {
11968                File f = codePath.getCanonicalFile();
11969                File parent = f.getParentFile();    // non-null because codePath is a file
11970                File tmp;
11971                while ((tmp = parent.getParentFile()) != null) {
11972                    f = parent;
11973                    parent = tmp;
11974                }
11975                codeRoot = f;
11976                Slog.w(TAG, "Unrecognized code path "
11977                        + codePath + " - using " + codeRoot);
11978            } catch (IOException e) {
11979                // Can't canonicalize the code path -- shenanigans?
11980                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11981                return Environment.getRootDirectory().getPath();
11982            }
11983        }
11984        return codeRoot.getPath();
11985    }
11986
11987    /**
11988     * Derive and set the location of native libraries for the given package,
11989     * which varies depending on where and how the package was installed.
11990     */
11991    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11992        final ApplicationInfo info = pkg.applicationInfo;
11993        final String codePath = pkg.codePath;
11994        final File codeFile = new File(codePath);
11995        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11996        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11997
11998        info.nativeLibraryRootDir = null;
11999        info.nativeLibraryRootRequiresIsa = false;
12000        info.nativeLibraryDir = null;
12001        info.secondaryNativeLibraryDir = null;
12002
12003        if (isApkFile(codeFile)) {
12004            // Monolithic install
12005            if (bundledApp) {
12006                // If "/system/lib64/apkname" exists, assume that is the per-package
12007                // native library directory to use; otherwise use "/system/lib/apkname".
12008                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12009                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12010                        getPrimaryInstructionSet(info));
12011
12012                // This is a bundled system app so choose the path based on the ABI.
12013                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12014                // is just the default path.
12015                final String apkName = deriveCodePathName(codePath);
12016                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12017                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12018                        apkName).getAbsolutePath();
12019
12020                if (info.secondaryCpuAbi != null) {
12021                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12022                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12023                            secondaryLibDir, apkName).getAbsolutePath();
12024                }
12025            } else if (asecApp) {
12026                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12027                        .getAbsolutePath();
12028            } else {
12029                final String apkName = deriveCodePathName(codePath);
12030                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12031                        .getAbsolutePath();
12032            }
12033
12034            info.nativeLibraryRootRequiresIsa = false;
12035            info.nativeLibraryDir = info.nativeLibraryRootDir;
12036        } else {
12037            // Cluster install
12038            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12039            info.nativeLibraryRootRequiresIsa = true;
12040
12041            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12042                    getPrimaryInstructionSet(info)).getAbsolutePath();
12043
12044            if (info.secondaryCpuAbi != null) {
12045                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12046                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12047            }
12048        }
12049    }
12050
12051    /**
12052     * Calculate the abis and roots for a bundled app. These can uniquely
12053     * be determined from the contents of the system partition, i.e whether
12054     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12055     * of this information, and instead assume that the system was built
12056     * sensibly.
12057     */
12058    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12059                                           PackageSetting pkgSetting) {
12060        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12061
12062        // If "/system/lib64/apkname" exists, assume that is the per-package
12063        // native library directory to use; otherwise use "/system/lib/apkname".
12064        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12065        setBundledAppAbi(pkg, apkRoot, apkName);
12066        // pkgSetting might be null during rescan following uninstall of updates
12067        // to a bundled app, so accommodate that possibility.  The settings in
12068        // that case will be established later from the parsed package.
12069        //
12070        // If the settings aren't null, sync them up with what we've just derived.
12071        // note that apkRoot isn't stored in the package settings.
12072        if (pkgSetting != null) {
12073            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12074            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12075        }
12076    }
12077
12078    /**
12079     * Deduces the ABI of a bundled app and sets the relevant fields on the
12080     * parsed pkg object.
12081     *
12082     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12083     *        under which system libraries are installed.
12084     * @param apkName the name of the installed package.
12085     */
12086    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12087        final File codeFile = new File(pkg.codePath);
12088
12089        final boolean has64BitLibs;
12090        final boolean has32BitLibs;
12091        if (isApkFile(codeFile)) {
12092            // Monolithic install
12093            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12094            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12095        } else {
12096            // Cluster install
12097            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12098            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12099                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12100                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12101                has64BitLibs = (new File(rootDir, isa)).exists();
12102            } else {
12103                has64BitLibs = false;
12104            }
12105            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12106                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12107                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12108                has32BitLibs = (new File(rootDir, isa)).exists();
12109            } else {
12110                has32BitLibs = false;
12111            }
12112        }
12113
12114        if (has64BitLibs && !has32BitLibs) {
12115            // The package has 64 bit libs, but not 32 bit libs. Its primary
12116            // ABI should be 64 bit. We can safely assume here that the bundled
12117            // native libraries correspond to the most preferred ABI in the list.
12118
12119            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12120            pkg.applicationInfo.secondaryCpuAbi = null;
12121        } else if (has32BitLibs && !has64BitLibs) {
12122            // The package has 32 bit libs but not 64 bit libs. Its primary
12123            // ABI should be 32 bit.
12124
12125            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12126            pkg.applicationInfo.secondaryCpuAbi = null;
12127        } else if (has32BitLibs && has64BitLibs) {
12128            // The application has both 64 and 32 bit bundled libraries. We check
12129            // here that the app declares multiArch support, and warn if it doesn't.
12130            //
12131            // We will be lenient here and record both ABIs. The primary will be the
12132            // ABI that's higher on the list, i.e, a device that's configured to prefer
12133            // 64 bit apps will see a 64 bit primary ABI,
12134
12135            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12136                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12137            }
12138
12139            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12140                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12141                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12142            } else {
12143                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12144                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12145            }
12146        } else {
12147            pkg.applicationInfo.primaryCpuAbi = null;
12148            pkg.applicationInfo.secondaryCpuAbi = null;
12149        }
12150    }
12151
12152    private void killApplication(String pkgName, int appId, String reason) {
12153        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12154    }
12155
12156    private void killApplication(String pkgName, int appId, int userId, String reason) {
12157        // Request the ActivityManager to kill the process(only for existing packages)
12158        // so that we do not end up in a confused state while the user is still using the older
12159        // version of the application while the new one gets installed.
12160        final long token = Binder.clearCallingIdentity();
12161        try {
12162            IActivityManager am = ActivityManager.getService();
12163            if (am != null) {
12164                try {
12165                    am.killApplication(pkgName, appId, userId, reason);
12166                } catch (RemoteException e) {
12167                }
12168            }
12169        } finally {
12170            Binder.restoreCallingIdentity(token);
12171        }
12172    }
12173
12174    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12175        // Remove the parent package setting
12176        PackageSetting ps = (PackageSetting) pkg.mExtras;
12177        if (ps != null) {
12178            removePackageLI(ps, chatty);
12179        }
12180        // Remove the child package setting
12181        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12182        for (int i = 0; i < childCount; i++) {
12183            PackageParser.Package childPkg = pkg.childPackages.get(i);
12184            ps = (PackageSetting) childPkg.mExtras;
12185            if (ps != null) {
12186                removePackageLI(ps, chatty);
12187            }
12188        }
12189    }
12190
12191    void removePackageLI(PackageSetting ps, boolean chatty) {
12192        if (DEBUG_INSTALL) {
12193            if (chatty)
12194                Log.d(TAG, "Removing package " + ps.name);
12195        }
12196
12197        // writer
12198        synchronized (mPackages) {
12199            mPackages.remove(ps.name);
12200            final PackageParser.Package pkg = ps.pkg;
12201            if (pkg != null) {
12202                cleanPackageDataStructuresLILPw(pkg, chatty);
12203            }
12204        }
12205    }
12206
12207    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12208        if (DEBUG_INSTALL) {
12209            if (chatty)
12210                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12211        }
12212
12213        // writer
12214        synchronized (mPackages) {
12215            // Remove the parent package
12216            mPackages.remove(pkg.applicationInfo.packageName);
12217            cleanPackageDataStructuresLILPw(pkg, chatty);
12218
12219            // Remove the child packages
12220            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12221            for (int i = 0; i < childCount; i++) {
12222                PackageParser.Package childPkg = pkg.childPackages.get(i);
12223                mPackages.remove(childPkg.applicationInfo.packageName);
12224                cleanPackageDataStructuresLILPw(childPkg, chatty);
12225            }
12226        }
12227    }
12228
12229    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12230        int N = pkg.providers.size();
12231        StringBuilder r = null;
12232        int i;
12233        for (i=0; i<N; i++) {
12234            PackageParser.Provider p = pkg.providers.get(i);
12235            mProviders.removeProvider(p);
12236            if (p.info.authority == null) {
12237
12238                /* There was another ContentProvider with this authority when
12239                 * this app was installed so this authority is null,
12240                 * Ignore it as we don't have to unregister the provider.
12241                 */
12242                continue;
12243            }
12244            String names[] = p.info.authority.split(";");
12245            for (int j = 0; j < names.length; j++) {
12246                if (mProvidersByAuthority.get(names[j]) == p) {
12247                    mProvidersByAuthority.remove(names[j]);
12248                    if (DEBUG_REMOVE) {
12249                        if (chatty)
12250                            Log.d(TAG, "Unregistered content provider: " + names[j]
12251                                    + ", className = " + p.info.name + ", isSyncable = "
12252                                    + p.info.isSyncable);
12253                    }
12254                }
12255            }
12256            if (DEBUG_REMOVE && chatty) {
12257                if (r == null) {
12258                    r = new StringBuilder(256);
12259                } else {
12260                    r.append(' ');
12261                }
12262                r.append(p.info.name);
12263            }
12264        }
12265        if (r != null) {
12266            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12267        }
12268
12269        N = pkg.services.size();
12270        r = null;
12271        for (i=0; i<N; i++) {
12272            PackageParser.Service s = pkg.services.get(i);
12273            mServices.removeService(s);
12274            if (chatty) {
12275                if (r == null) {
12276                    r = new StringBuilder(256);
12277                } else {
12278                    r.append(' ');
12279                }
12280                r.append(s.info.name);
12281            }
12282        }
12283        if (r != null) {
12284            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12285        }
12286
12287        N = pkg.receivers.size();
12288        r = null;
12289        for (i=0; i<N; i++) {
12290            PackageParser.Activity a = pkg.receivers.get(i);
12291            mReceivers.removeActivity(a, "receiver");
12292            if (DEBUG_REMOVE && chatty) {
12293                if (r == null) {
12294                    r = new StringBuilder(256);
12295                } else {
12296                    r.append(' ');
12297                }
12298                r.append(a.info.name);
12299            }
12300        }
12301        if (r != null) {
12302            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12303        }
12304
12305        N = pkg.activities.size();
12306        r = null;
12307        for (i=0; i<N; i++) {
12308            PackageParser.Activity a = pkg.activities.get(i);
12309            mActivities.removeActivity(a, "activity");
12310            if (DEBUG_REMOVE && chatty) {
12311                if (r == null) {
12312                    r = new StringBuilder(256);
12313                } else {
12314                    r.append(' ');
12315                }
12316                r.append(a.info.name);
12317            }
12318        }
12319        if (r != null) {
12320            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12321        }
12322
12323        mPermissionManager.removeAllPermissions(pkg, chatty);
12324
12325        N = pkg.instrumentation.size();
12326        r = null;
12327        for (i=0; i<N; i++) {
12328            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12329            mInstrumentation.remove(a.getComponentName());
12330            if (DEBUG_REMOVE && chatty) {
12331                if (r == null) {
12332                    r = new StringBuilder(256);
12333                } else {
12334                    r.append(' ');
12335                }
12336                r.append(a.info.name);
12337            }
12338        }
12339        if (r != null) {
12340            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12341        }
12342
12343        r = null;
12344        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12345            // Only system apps can hold shared libraries.
12346            if (pkg.libraryNames != null) {
12347                for (i = 0; i < pkg.libraryNames.size(); i++) {
12348                    String name = pkg.libraryNames.get(i);
12349                    if (removeSharedLibraryLPw(name, 0)) {
12350                        if (DEBUG_REMOVE && chatty) {
12351                            if (r == null) {
12352                                r = new StringBuilder(256);
12353                            } else {
12354                                r.append(' ');
12355                            }
12356                            r.append(name);
12357                        }
12358                    }
12359                }
12360            }
12361        }
12362
12363        r = null;
12364
12365        // Any package can hold static shared libraries.
12366        if (pkg.staticSharedLibName != null) {
12367            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12368                if (DEBUG_REMOVE && chatty) {
12369                    if (r == null) {
12370                        r = new StringBuilder(256);
12371                    } else {
12372                        r.append(' ');
12373                    }
12374                    r.append(pkg.staticSharedLibName);
12375                }
12376            }
12377        }
12378
12379        if (r != null) {
12380            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12381        }
12382    }
12383
12384
12385    final class ActivityIntentResolver
12386            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12387        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12388                boolean defaultOnly, int userId) {
12389            if (!sUserManager.exists(userId)) return null;
12390            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12391            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12392        }
12393
12394        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12395                int userId) {
12396            if (!sUserManager.exists(userId)) return null;
12397            mFlags = flags;
12398            return super.queryIntent(intent, resolvedType,
12399                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12400                    userId);
12401        }
12402
12403        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12404                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12405            if (!sUserManager.exists(userId)) return null;
12406            if (packageActivities == null) {
12407                return null;
12408            }
12409            mFlags = flags;
12410            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12411            final int N = packageActivities.size();
12412            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12413                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12414
12415            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12416            for (int i = 0; i < N; ++i) {
12417                intentFilters = packageActivities.get(i).intents;
12418                if (intentFilters != null && intentFilters.size() > 0) {
12419                    PackageParser.ActivityIntentInfo[] array =
12420                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12421                    intentFilters.toArray(array);
12422                    listCut.add(array);
12423                }
12424            }
12425            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12426        }
12427
12428        /**
12429         * Finds a privileged activity that matches the specified activity names.
12430         */
12431        private PackageParser.Activity findMatchingActivity(
12432                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12433            for (PackageParser.Activity sysActivity : activityList) {
12434                if (sysActivity.info.name.equals(activityInfo.name)) {
12435                    return sysActivity;
12436                }
12437                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12438                    return sysActivity;
12439                }
12440                if (sysActivity.info.targetActivity != null) {
12441                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12442                        return sysActivity;
12443                    }
12444                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12445                        return sysActivity;
12446                    }
12447                }
12448            }
12449            return null;
12450        }
12451
12452        public class IterGenerator<E> {
12453            public Iterator<E> generate(ActivityIntentInfo info) {
12454                return null;
12455            }
12456        }
12457
12458        public class ActionIterGenerator extends IterGenerator<String> {
12459            @Override
12460            public Iterator<String> generate(ActivityIntentInfo info) {
12461                return info.actionsIterator();
12462            }
12463        }
12464
12465        public class CategoriesIterGenerator extends IterGenerator<String> {
12466            @Override
12467            public Iterator<String> generate(ActivityIntentInfo info) {
12468                return info.categoriesIterator();
12469            }
12470        }
12471
12472        public class SchemesIterGenerator extends IterGenerator<String> {
12473            @Override
12474            public Iterator<String> generate(ActivityIntentInfo info) {
12475                return info.schemesIterator();
12476            }
12477        }
12478
12479        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12480            @Override
12481            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12482                return info.authoritiesIterator();
12483            }
12484        }
12485
12486        /**
12487         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12488         * MODIFIED. Do not pass in a list that should not be changed.
12489         */
12490        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12491                IterGenerator<T> generator, Iterator<T> searchIterator) {
12492            // loop through the set of actions; every one must be found in the intent filter
12493            while (searchIterator.hasNext()) {
12494                // we must have at least one filter in the list to consider a match
12495                if (intentList.size() == 0) {
12496                    break;
12497                }
12498
12499                final T searchAction = searchIterator.next();
12500
12501                // loop through the set of intent filters
12502                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12503                while (intentIter.hasNext()) {
12504                    final ActivityIntentInfo intentInfo = intentIter.next();
12505                    boolean selectionFound = false;
12506
12507                    // loop through the intent filter's selection criteria; at least one
12508                    // of them must match the searched criteria
12509                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12510                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12511                        final T intentSelection = intentSelectionIter.next();
12512                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12513                            selectionFound = true;
12514                            break;
12515                        }
12516                    }
12517
12518                    // the selection criteria wasn't found in this filter's set; this filter
12519                    // is not a potential match
12520                    if (!selectionFound) {
12521                        intentIter.remove();
12522                    }
12523                }
12524            }
12525        }
12526
12527        private boolean isProtectedAction(ActivityIntentInfo filter) {
12528            final Iterator<String> actionsIter = filter.actionsIterator();
12529            while (actionsIter != null && actionsIter.hasNext()) {
12530                final String filterAction = actionsIter.next();
12531                if (PROTECTED_ACTIONS.contains(filterAction)) {
12532                    return true;
12533                }
12534            }
12535            return false;
12536        }
12537
12538        /**
12539         * Adjusts the priority of the given intent filter according to policy.
12540         * <p>
12541         * <ul>
12542         * <li>The priority for non privileged applications is capped to '0'</li>
12543         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12544         * <li>The priority for unbundled updates to privileged applications is capped to the
12545         *      priority defined on the system partition</li>
12546         * </ul>
12547         * <p>
12548         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12549         * allowed to obtain any priority on any action.
12550         */
12551        private void adjustPriority(
12552                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12553            // nothing to do; priority is fine as-is
12554            if (intent.getPriority() <= 0) {
12555                return;
12556            }
12557
12558            final ActivityInfo activityInfo = intent.activity.info;
12559            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12560
12561            final boolean privilegedApp =
12562                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12563            if (!privilegedApp) {
12564                // non-privileged applications can never define a priority >0
12565                if (DEBUG_FILTERS) {
12566                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12567                            + " package: " + applicationInfo.packageName
12568                            + " activity: " + intent.activity.className
12569                            + " origPrio: " + intent.getPriority());
12570                }
12571                intent.setPriority(0);
12572                return;
12573            }
12574
12575            if (systemActivities == null) {
12576                // the system package is not disabled; we're parsing the system partition
12577                if (isProtectedAction(intent)) {
12578                    if (mDeferProtectedFilters) {
12579                        // We can't deal with these just yet. No component should ever obtain a
12580                        // >0 priority for a protected actions, with ONE exception -- the setup
12581                        // wizard. The setup wizard, however, cannot be known until we're able to
12582                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12583                        // until all intent filters have been processed. Chicken, meet egg.
12584                        // Let the filter temporarily have a high priority and rectify the
12585                        // priorities after all system packages have been scanned.
12586                        mProtectedFilters.add(intent);
12587                        if (DEBUG_FILTERS) {
12588                            Slog.i(TAG, "Protected action; save for later;"
12589                                    + " package: " + applicationInfo.packageName
12590                                    + " activity: " + intent.activity.className
12591                                    + " origPrio: " + intent.getPriority());
12592                        }
12593                        return;
12594                    } else {
12595                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12596                            Slog.i(TAG, "No setup wizard;"
12597                                + " All protected intents capped to priority 0");
12598                        }
12599                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12600                            if (DEBUG_FILTERS) {
12601                                Slog.i(TAG, "Found setup wizard;"
12602                                    + " allow priority " + intent.getPriority() + ";"
12603                                    + " package: " + intent.activity.info.packageName
12604                                    + " activity: " + intent.activity.className
12605                                    + " priority: " + intent.getPriority());
12606                            }
12607                            // setup wizard gets whatever it wants
12608                            return;
12609                        }
12610                        if (DEBUG_FILTERS) {
12611                            Slog.i(TAG, "Protected action; cap priority to 0;"
12612                                    + " package: " + intent.activity.info.packageName
12613                                    + " activity: " + intent.activity.className
12614                                    + " origPrio: " + intent.getPriority());
12615                        }
12616                        intent.setPriority(0);
12617                        return;
12618                    }
12619                }
12620                // privileged apps on the system image get whatever priority they request
12621                return;
12622            }
12623
12624            // privileged app unbundled update ... try to find the same activity
12625            final PackageParser.Activity foundActivity =
12626                    findMatchingActivity(systemActivities, activityInfo);
12627            if (foundActivity == null) {
12628                // this is a new activity; it cannot obtain >0 priority
12629                if (DEBUG_FILTERS) {
12630                    Slog.i(TAG, "New activity; cap priority to 0;"
12631                            + " package: " + applicationInfo.packageName
12632                            + " activity: " + intent.activity.className
12633                            + " origPrio: " + intent.getPriority());
12634                }
12635                intent.setPriority(0);
12636                return;
12637            }
12638
12639            // found activity, now check for filter equivalence
12640
12641            // a shallow copy is enough; we modify the list, not its contents
12642            final List<ActivityIntentInfo> intentListCopy =
12643                    new ArrayList<>(foundActivity.intents);
12644            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12645
12646            // find matching action subsets
12647            final Iterator<String> actionsIterator = intent.actionsIterator();
12648            if (actionsIterator != null) {
12649                getIntentListSubset(
12650                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12651                if (intentListCopy.size() == 0) {
12652                    // no more intents to match; we're not equivalent
12653                    if (DEBUG_FILTERS) {
12654                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12655                                + " package: " + applicationInfo.packageName
12656                                + " activity: " + intent.activity.className
12657                                + " origPrio: " + intent.getPriority());
12658                    }
12659                    intent.setPriority(0);
12660                    return;
12661                }
12662            }
12663
12664            // find matching category subsets
12665            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12666            if (categoriesIterator != null) {
12667                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12668                        categoriesIterator);
12669                if (intentListCopy.size() == 0) {
12670                    // no more intents to match; we're not equivalent
12671                    if (DEBUG_FILTERS) {
12672                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12673                                + " package: " + applicationInfo.packageName
12674                                + " activity: " + intent.activity.className
12675                                + " origPrio: " + intent.getPriority());
12676                    }
12677                    intent.setPriority(0);
12678                    return;
12679                }
12680            }
12681
12682            // find matching schemes subsets
12683            final Iterator<String> schemesIterator = intent.schemesIterator();
12684            if (schemesIterator != null) {
12685                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12686                        schemesIterator);
12687                if (intentListCopy.size() == 0) {
12688                    // no more intents to match; we're not equivalent
12689                    if (DEBUG_FILTERS) {
12690                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12691                                + " package: " + applicationInfo.packageName
12692                                + " activity: " + intent.activity.className
12693                                + " origPrio: " + intent.getPriority());
12694                    }
12695                    intent.setPriority(0);
12696                    return;
12697                }
12698            }
12699
12700            // find matching authorities subsets
12701            final Iterator<IntentFilter.AuthorityEntry>
12702                    authoritiesIterator = intent.authoritiesIterator();
12703            if (authoritiesIterator != null) {
12704                getIntentListSubset(intentListCopy,
12705                        new AuthoritiesIterGenerator(),
12706                        authoritiesIterator);
12707                if (intentListCopy.size() == 0) {
12708                    // no more intents to match; we're not equivalent
12709                    if (DEBUG_FILTERS) {
12710                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12711                                + " package: " + applicationInfo.packageName
12712                                + " activity: " + intent.activity.className
12713                                + " origPrio: " + intent.getPriority());
12714                    }
12715                    intent.setPriority(0);
12716                    return;
12717                }
12718            }
12719
12720            // we found matching filter(s); app gets the max priority of all intents
12721            int cappedPriority = 0;
12722            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12723                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12724            }
12725            if (intent.getPriority() > cappedPriority) {
12726                if (DEBUG_FILTERS) {
12727                    Slog.i(TAG, "Found matching filter(s);"
12728                            + " cap priority to " + cappedPriority + ";"
12729                            + " package: " + applicationInfo.packageName
12730                            + " activity: " + intent.activity.className
12731                            + " origPrio: " + intent.getPriority());
12732                }
12733                intent.setPriority(cappedPriority);
12734                return;
12735            }
12736            // all this for nothing; the requested priority was <= what was on the system
12737        }
12738
12739        public final void addActivity(PackageParser.Activity a, String type) {
12740            mActivities.put(a.getComponentName(), a);
12741            if (DEBUG_SHOW_INFO)
12742                Log.v(
12743                TAG, "  " + type + " " +
12744                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12745            if (DEBUG_SHOW_INFO)
12746                Log.v(TAG, "    Class=" + a.info.name);
12747            final int NI = a.intents.size();
12748            for (int j=0; j<NI; j++) {
12749                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12750                if ("activity".equals(type)) {
12751                    final PackageSetting ps =
12752                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12753                    final List<PackageParser.Activity> systemActivities =
12754                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12755                    adjustPriority(systemActivities, intent);
12756                }
12757                if (DEBUG_SHOW_INFO) {
12758                    Log.v(TAG, "    IntentFilter:");
12759                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12760                }
12761                if (!intent.debugCheck()) {
12762                    Log.w(TAG, "==> For Activity " + a.info.name);
12763                }
12764                addFilter(intent);
12765            }
12766        }
12767
12768        public final void removeActivity(PackageParser.Activity a, String type) {
12769            mActivities.remove(a.getComponentName());
12770            if (DEBUG_SHOW_INFO) {
12771                Log.v(TAG, "  " + type + " "
12772                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12773                                : a.info.name) + ":");
12774                Log.v(TAG, "    Class=" + a.info.name);
12775            }
12776            final int NI = a.intents.size();
12777            for (int j=0; j<NI; j++) {
12778                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12779                if (DEBUG_SHOW_INFO) {
12780                    Log.v(TAG, "    IntentFilter:");
12781                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12782                }
12783                removeFilter(intent);
12784            }
12785        }
12786
12787        @Override
12788        protected boolean allowFilterResult(
12789                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12790            ActivityInfo filterAi = filter.activity.info;
12791            for (int i=dest.size()-1; i>=0; i--) {
12792                ActivityInfo destAi = dest.get(i).activityInfo;
12793                if (destAi.name == filterAi.name
12794                        && destAi.packageName == filterAi.packageName) {
12795                    return false;
12796                }
12797            }
12798            return true;
12799        }
12800
12801        @Override
12802        protected ActivityIntentInfo[] newArray(int size) {
12803            return new ActivityIntentInfo[size];
12804        }
12805
12806        @Override
12807        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12808            if (!sUserManager.exists(userId)) return true;
12809            PackageParser.Package p = filter.activity.owner;
12810            if (p != null) {
12811                PackageSetting ps = (PackageSetting)p.mExtras;
12812                if (ps != null) {
12813                    // System apps are never considered stopped for purposes of
12814                    // filtering, because there may be no way for the user to
12815                    // actually re-launch them.
12816                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12817                            && ps.getStopped(userId);
12818                }
12819            }
12820            return false;
12821        }
12822
12823        @Override
12824        protected boolean isPackageForFilter(String packageName,
12825                PackageParser.ActivityIntentInfo info) {
12826            return packageName.equals(info.activity.owner.packageName);
12827        }
12828
12829        @Override
12830        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12831                int match, int userId) {
12832            if (!sUserManager.exists(userId)) return null;
12833            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12834                return null;
12835            }
12836            final PackageParser.Activity activity = info.activity;
12837            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12838            if (ps == null) {
12839                return null;
12840            }
12841            final PackageUserState userState = ps.readUserState(userId);
12842            ActivityInfo ai =
12843                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12844            if (ai == null) {
12845                return null;
12846            }
12847            final boolean matchExplicitlyVisibleOnly =
12848                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12849            final boolean matchVisibleToInstantApp =
12850                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12851            final boolean componentVisible =
12852                    matchVisibleToInstantApp
12853                    && info.isVisibleToInstantApp()
12854                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12855            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12856            // throw out filters that aren't visible to ephemeral apps
12857            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12858                return null;
12859            }
12860            // throw out instant app filters if we're not explicitly requesting them
12861            if (!matchInstantApp && userState.instantApp) {
12862                return null;
12863            }
12864            // throw out instant app filters if updates are available; will trigger
12865            // instant app resolution
12866            if (userState.instantApp && ps.isUpdateAvailable()) {
12867                return null;
12868            }
12869            final ResolveInfo res = new ResolveInfo();
12870            res.activityInfo = ai;
12871            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12872                res.filter = info;
12873            }
12874            if (info != null) {
12875                res.handleAllWebDataURI = info.handleAllWebDataURI();
12876            }
12877            res.priority = info.getPriority();
12878            res.preferredOrder = activity.owner.mPreferredOrder;
12879            //System.out.println("Result: " + res.activityInfo.className +
12880            //                   " = " + res.priority);
12881            res.match = match;
12882            res.isDefault = info.hasDefault;
12883            res.labelRes = info.labelRes;
12884            res.nonLocalizedLabel = info.nonLocalizedLabel;
12885            if (userNeedsBadging(userId)) {
12886                res.noResourceId = true;
12887            } else {
12888                res.icon = info.icon;
12889            }
12890            res.iconResourceId = info.icon;
12891            res.system = res.activityInfo.applicationInfo.isSystemApp();
12892            res.isInstantAppAvailable = userState.instantApp;
12893            return res;
12894        }
12895
12896        @Override
12897        protected void sortResults(List<ResolveInfo> results) {
12898            Collections.sort(results, mResolvePrioritySorter);
12899        }
12900
12901        @Override
12902        protected void dumpFilter(PrintWriter out, String prefix,
12903                PackageParser.ActivityIntentInfo filter) {
12904            out.print(prefix); out.print(
12905                    Integer.toHexString(System.identityHashCode(filter.activity)));
12906                    out.print(' ');
12907                    filter.activity.printComponentShortName(out);
12908                    out.print(" filter ");
12909                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12910        }
12911
12912        @Override
12913        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12914            return filter.activity;
12915        }
12916
12917        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12918            PackageParser.Activity activity = (PackageParser.Activity)label;
12919            out.print(prefix); out.print(
12920                    Integer.toHexString(System.identityHashCode(activity)));
12921                    out.print(' ');
12922                    activity.printComponentShortName(out);
12923            if (count > 1) {
12924                out.print(" ("); out.print(count); out.print(" filters)");
12925            }
12926            out.println();
12927        }
12928
12929        // Keys are String (activity class name), values are Activity.
12930        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12931                = new ArrayMap<ComponentName, PackageParser.Activity>();
12932        private int mFlags;
12933    }
12934
12935    private final class ServiceIntentResolver
12936            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12937        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12938                boolean defaultOnly, int userId) {
12939            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12940            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12941        }
12942
12943        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12944                int userId) {
12945            if (!sUserManager.exists(userId)) return null;
12946            mFlags = flags;
12947            return super.queryIntent(intent, resolvedType,
12948                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12949                    userId);
12950        }
12951
12952        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12953                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12954            if (!sUserManager.exists(userId)) return null;
12955            if (packageServices == null) {
12956                return null;
12957            }
12958            mFlags = flags;
12959            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12960            final int N = packageServices.size();
12961            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12962                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12963
12964            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12965            for (int i = 0; i < N; ++i) {
12966                intentFilters = packageServices.get(i).intents;
12967                if (intentFilters != null && intentFilters.size() > 0) {
12968                    PackageParser.ServiceIntentInfo[] array =
12969                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12970                    intentFilters.toArray(array);
12971                    listCut.add(array);
12972                }
12973            }
12974            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12975        }
12976
12977        public final void addService(PackageParser.Service s) {
12978            mServices.put(s.getComponentName(), s);
12979            if (DEBUG_SHOW_INFO) {
12980                Log.v(TAG, "  "
12981                        + (s.info.nonLocalizedLabel != null
12982                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12983                Log.v(TAG, "    Class=" + s.info.name);
12984            }
12985            final int NI = s.intents.size();
12986            int j;
12987            for (j=0; j<NI; j++) {
12988                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12989                if (DEBUG_SHOW_INFO) {
12990                    Log.v(TAG, "    IntentFilter:");
12991                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12992                }
12993                if (!intent.debugCheck()) {
12994                    Log.w(TAG, "==> For Service " + s.info.name);
12995                }
12996                addFilter(intent);
12997            }
12998        }
12999
13000        public final void removeService(PackageParser.Service s) {
13001            mServices.remove(s.getComponentName());
13002            if (DEBUG_SHOW_INFO) {
13003                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13004                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13005                Log.v(TAG, "    Class=" + s.info.name);
13006            }
13007            final int NI = s.intents.size();
13008            int j;
13009            for (j=0; j<NI; j++) {
13010                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13011                if (DEBUG_SHOW_INFO) {
13012                    Log.v(TAG, "    IntentFilter:");
13013                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13014                }
13015                removeFilter(intent);
13016            }
13017        }
13018
13019        @Override
13020        protected boolean allowFilterResult(
13021                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13022            ServiceInfo filterSi = filter.service.info;
13023            for (int i=dest.size()-1; i>=0; i--) {
13024                ServiceInfo destAi = dest.get(i).serviceInfo;
13025                if (destAi.name == filterSi.name
13026                        && destAi.packageName == filterSi.packageName) {
13027                    return false;
13028                }
13029            }
13030            return true;
13031        }
13032
13033        @Override
13034        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13035            return new PackageParser.ServiceIntentInfo[size];
13036        }
13037
13038        @Override
13039        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13040            if (!sUserManager.exists(userId)) return true;
13041            PackageParser.Package p = filter.service.owner;
13042            if (p != null) {
13043                PackageSetting ps = (PackageSetting)p.mExtras;
13044                if (ps != null) {
13045                    // System apps are never considered stopped for purposes of
13046                    // filtering, because there may be no way for the user to
13047                    // actually re-launch them.
13048                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13049                            && ps.getStopped(userId);
13050                }
13051            }
13052            return false;
13053        }
13054
13055        @Override
13056        protected boolean isPackageForFilter(String packageName,
13057                PackageParser.ServiceIntentInfo info) {
13058            return packageName.equals(info.service.owner.packageName);
13059        }
13060
13061        @Override
13062        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13063                int match, int userId) {
13064            if (!sUserManager.exists(userId)) return null;
13065            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13066            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13067                return null;
13068            }
13069            final PackageParser.Service service = info.service;
13070            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13071            if (ps == null) {
13072                return null;
13073            }
13074            final PackageUserState userState = ps.readUserState(userId);
13075            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13076                    userState, userId);
13077            if (si == null) {
13078                return null;
13079            }
13080            final boolean matchVisibleToInstantApp =
13081                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13082            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13083            // throw out filters that aren't visible to ephemeral apps
13084            if (matchVisibleToInstantApp
13085                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13086                return null;
13087            }
13088            // throw out ephemeral filters if we're not explicitly requesting them
13089            if (!isInstantApp && userState.instantApp) {
13090                return null;
13091            }
13092            // throw out instant app filters if updates are available; will trigger
13093            // instant app resolution
13094            if (userState.instantApp && ps.isUpdateAvailable()) {
13095                return null;
13096            }
13097            final ResolveInfo res = new ResolveInfo();
13098            res.serviceInfo = si;
13099            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13100                res.filter = filter;
13101            }
13102            res.priority = info.getPriority();
13103            res.preferredOrder = service.owner.mPreferredOrder;
13104            res.match = match;
13105            res.isDefault = info.hasDefault;
13106            res.labelRes = info.labelRes;
13107            res.nonLocalizedLabel = info.nonLocalizedLabel;
13108            res.icon = info.icon;
13109            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13110            return res;
13111        }
13112
13113        @Override
13114        protected void sortResults(List<ResolveInfo> results) {
13115            Collections.sort(results, mResolvePrioritySorter);
13116        }
13117
13118        @Override
13119        protected void dumpFilter(PrintWriter out, String prefix,
13120                PackageParser.ServiceIntentInfo filter) {
13121            out.print(prefix); out.print(
13122                    Integer.toHexString(System.identityHashCode(filter.service)));
13123                    out.print(' ');
13124                    filter.service.printComponentShortName(out);
13125                    out.print(" filter ");
13126                    out.print(Integer.toHexString(System.identityHashCode(filter)));
13127                    if (filter.service.info.permission != null) {
13128                        out.print(" permission "); out.println(filter.service.info.permission);
13129                    } else {
13130                        out.println();
13131                    }
13132        }
13133
13134        @Override
13135        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13136            return filter.service;
13137        }
13138
13139        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13140            PackageParser.Service service = (PackageParser.Service)label;
13141            out.print(prefix); out.print(
13142                    Integer.toHexString(System.identityHashCode(service)));
13143                    out.print(' ');
13144                    service.printComponentShortName(out);
13145            if (count > 1) {
13146                out.print(" ("); out.print(count); out.print(" filters)");
13147            }
13148            out.println();
13149        }
13150
13151//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13152//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13153//            final List<ResolveInfo> retList = Lists.newArrayList();
13154//            while (i.hasNext()) {
13155//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13156//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13157//                    retList.add(resolveInfo);
13158//                }
13159//            }
13160//            return retList;
13161//        }
13162
13163        // Keys are String (activity class name), values are Activity.
13164        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13165                = new ArrayMap<ComponentName, PackageParser.Service>();
13166        private int mFlags;
13167    }
13168
13169    private final class ProviderIntentResolver
13170            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13171        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13172                boolean defaultOnly, int userId) {
13173            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13174            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13175        }
13176
13177        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13178                int userId) {
13179            if (!sUserManager.exists(userId))
13180                return null;
13181            mFlags = flags;
13182            return super.queryIntent(intent, resolvedType,
13183                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13184                    userId);
13185        }
13186
13187        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13188                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13189            if (!sUserManager.exists(userId))
13190                return null;
13191            if (packageProviders == null) {
13192                return null;
13193            }
13194            mFlags = flags;
13195            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13196            final int N = packageProviders.size();
13197            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13198                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13199
13200            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13201            for (int i = 0; i < N; ++i) {
13202                intentFilters = packageProviders.get(i).intents;
13203                if (intentFilters != null && intentFilters.size() > 0) {
13204                    PackageParser.ProviderIntentInfo[] array =
13205                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13206                    intentFilters.toArray(array);
13207                    listCut.add(array);
13208                }
13209            }
13210            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13211        }
13212
13213        public final void addProvider(PackageParser.Provider p) {
13214            if (mProviders.containsKey(p.getComponentName())) {
13215                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13216                return;
13217            }
13218
13219            mProviders.put(p.getComponentName(), p);
13220            if (DEBUG_SHOW_INFO) {
13221                Log.v(TAG, "  "
13222                        + (p.info.nonLocalizedLabel != null
13223                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13224                Log.v(TAG, "    Class=" + p.info.name);
13225            }
13226            final int NI = p.intents.size();
13227            int j;
13228            for (j = 0; j < NI; j++) {
13229                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13230                if (DEBUG_SHOW_INFO) {
13231                    Log.v(TAG, "    IntentFilter:");
13232                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13233                }
13234                if (!intent.debugCheck()) {
13235                    Log.w(TAG, "==> For Provider " + p.info.name);
13236                }
13237                addFilter(intent);
13238            }
13239        }
13240
13241        public final void removeProvider(PackageParser.Provider p) {
13242            mProviders.remove(p.getComponentName());
13243            if (DEBUG_SHOW_INFO) {
13244                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13245                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13246                Log.v(TAG, "    Class=" + p.info.name);
13247            }
13248            final int NI = p.intents.size();
13249            int j;
13250            for (j = 0; j < NI; j++) {
13251                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13252                if (DEBUG_SHOW_INFO) {
13253                    Log.v(TAG, "    IntentFilter:");
13254                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13255                }
13256                removeFilter(intent);
13257            }
13258        }
13259
13260        @Override
13261        protected boolean allowFilterResult(
13262                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13263            ProviderInfo filterPi = filter.provider.info;
13264            for (int i = dest.size() - 1; i >= 0; i--) {
13265                ProviderInfo destPi = dest.get(i).providerInfo;
13266                if (destPi.name == filterPi.name
13267                        && destPi.packageName == filterPi.packageName) {
13268                    return false;
13269                }
13270            }
13271            return true;
13272        }
13273
13274        @Override
13275        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13276            return new PackageParser.ProviderIntentInfo[size];
13277        }
13278
13279        @Override
13280        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13281            if (!sUserManager.exists(userId))
13282                return true;
13283            PackageParser.Package p = filter.provider.owner;
13284            if (p != null) {
13285                PackageSetting ps = (PackageSetting) p.mExtras;
13286                if (ps != null) {
13287                    // System apps are never considered stopped for purposes of
13288                    // filtering, because there may be no way for the user to
13289                    // actually re-launch them.
13290                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13291                            && ps.getStopped(userId);
13292                }
13293            }
13294            return false;
13295        }
13296
13297        @Override
13298        protected boolean isPackageForFilter(String packageName,
13299                PackageParser.ProviderIntentInfo info) {
13300            return packageName.equals(info.provider.owner.packageName);
13301        }
13302
13303        @Override
13304        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13305                int match, int userId) {
13306            if (!sUserManager.exists(userId))
13307                return null;
13308            final PackageParser.ProviderIntentInfo info = filter;
13309            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13310                return null;
13311            }
13312            final PackageParser.Provider provider = info.provider;
13313            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13314            if (ps == null) {
13315                return null;
13316            }
13317            final PackageUserState userState = ps.readUserState(userId);
13318            final boolean matchVisibleToInstantApp =
13319                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13320            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13321            // throw out filters that aren't visible to instant applications
13322            if (matchVisibleToInstantApp
13323                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13324                return null;
13325            }
13326            // throw out instant application filters if we're not explicitly requesting them
13327            if (!isInstantApp && userState.instantApp) {
13328                return null;
13329            }
13330            // throw out instant application filters if updates are available; will trigger
13331            // instant application resolution
13332            if (userState.instantApp && ps.isUpdateAvailable()) {
13333                return null;
13334            }
13335            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13336                    userState, userId);
13337            if (pi == null) {
13338                return null;
13339            }
13340            final ResolveInfo res = new ResolveInfo();
13341            res.providerInfo = pi;
13342            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13343                res.filter = filter;
13344            }
13345            res.priority = info.getPriority();
13346            res.preferredOrder = provider.owner.mPreferredOrder;
13347            res.match = match;
13348            res.isDefault = info.hasDefault;
13349            res.labelRes = info.labelRes;
13350            res.nonLocalizedLabel = info.nonLocalizedLabel;
13351            res.icon = info.icon;
13352            res.system = res.providerInfo.applicationInfo.isSystemApp();
13353            return res;
13354        }
13355
13356        @Override
13357        protected void sortResults(List<ResolveInfo> results) {
13358            Collections.sort(results, mResolvePrioritySorter);
13359        }
13360
13361        @Override
13362        protected void dumpFilter(PrintWriter out, String prefix,
13363                PackageParser.ProviderIntentInfo filter) {
13364            out.print(prefix);
13365            out.print(
13366                    Integer.toHexString(System.identityHashCode(filter.provider)));
13367            out.print(' ');
13368            filter.provider.printComponentShortName(out);
13369            out.print(" filter ");
13370            out.println(Integer.toHexString(System.identityHashCode(filter)));
13371        }
13372
13373        @Override
13374        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13375            return filter.provider;
13376        }
13377
13378        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13379            PackageParser.Provider provider = (PackageParser.Provider)label;
13380            out.print(prefix); out.print(
13381                    Integer.toHexString(System.identityHashCode(provider)));
13382                    out.print(' ');
13383                    provider.printComponentShortName(out);
13384            if (count > 1) {
13385                out.print(" ("); out.print(count); out.print(" filters)");
13386            }
13387            out.println();
13388        }
13389
13390        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13391                = new ArrayMap<ComponentName, PackageParser.Provider>();
13392        private int mFlags;
13393    }
13394
13395    static final class InstantAppIntentResolver
13396            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13397            AuxiliaryResolveInfo.AuxiliaryFilter> {
13398        /**
13399         * The result that has the highest defined order. Ordering applies on a
13400         * per-package basis. Mapping is from package name to Pair of order and
13401         * EphemeralResolveInfo.
13402         * <p>
13403         * NOTE: This is implemented as a field variable for convenience and efficiency.
13404         * By having a field variable, we're able to track filter ordering as soon as
13405         * a non-zero order is defined. Otherwise, multiple loops across the result set
13406         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13407         * this needs to be contained entirely within {@link #filterResults}.
13408         */
13409        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13410
13411        @Override
13412        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13413            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13414        }
13415
13416        @Override
13417        protected boolean isPackageForFilter(String packageName,
13418                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13419            return true;
13420        }
13421
13422        @Override
13423        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13424                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13425            if (!sUserManager.exists(userId)) {
13426                return null;
13427            }
13428            final String packageName = responseObj.resolveInfo.getPackageName();
13429            final Integer order = responseObj.getOrder();
13430            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13431                    mOrderResult.get(packageName);
13432            // ordering is enabled and this item's order isn't high enough
13433            if (lastOrderResult != null && lastOrderResult.first >= order) {
13434                return null;
13435            }
13436            final InstantAppResolveInfo res = responseObj.resolveInfo;
13437            if (order > 0) {
13438                // non-zero order, enable ordering
13439                mOrderResult.put(packageName, new Pair<>(order, res));
13440            }
13441            return responseObj;
13442        }
13443
13444        @Override
13445        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13446            // only do work if ordering is enabled [most of the time it won't be]
13447            if (mOrderResult.size() == 0) {
13448                return;
13449            }
13450            int resultSize = results.size();
13451            for (int i = 0; i < resultSize; i++) {
13452                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13453                final String packageName = info.getPackageName();
13454                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13455                if (savedInfo == null) {
13456                    // package doesn't having ordering
13457                    continue;
13458                }
13459                if (savedInfo.second == info) {
13460                    // circled back to the highest ordered item; remove from order list
13461                    mOrderResult.remove(packageName);
13462                    if (mOrderResult.size() == 0) {
13463                        // no more ordered items
13464                        break;
13465                    }
13466                    continue;
13467                }
13468                // item has a worse order, remove it from the result list
13469                results.remove(i);
13470                resultSize--;
13471                i--;
13472            }
13473        }
13474    }
13475
13476    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13477            new Comparator<ResolveInfo>() {
13478        public int compare(ResolveInfo r1, ResolveInfo r2) {
13479            int v1 = r1.priority;
13480            int v2 = r2.priority;
13481            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13482            if (v1 != v2) {
13483                return (v1 > v2) ? -1 : 1;
13484            }
13485            v1 = r1.preferredOrder;
13486            v2 = r2.preferredOrder;
13487            if (v1 != v2) {
13488                return (v1 > v2) ? -1 : 1;
13489            }
13490            if (r1.isDefault != r2.isDefault) {
13491                return r1.isDefault ? -1 : 1;
13492            }
13493            v1 = r1.match;
13494            v2 = r2.match;
13495            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13496            if (v1 != v2) {
13497                return (v1 > v2) ? -1 : 1;
13498            }
13499            if (r1.system != r2.system) {
13500                return r1.system ? -1 : 1;
13501            }
13502            if (r1.activityInfo != null) {
13503                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13504            }
13505            if (r1.serviceInfo != null) {
13506                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13507            }
13508            if (r1.providerInfo != null) {
13509                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13510            }
13511            return 0;
13512        }
13513    };
13514
13515    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13516            new Comparator<ProviderInfo>() {
13517        public int compare(ProviderInfo p1, ProviderInfo p2) {
13518            final int v1 = p1.initOrder;
13519            final int v2 = p2.initOrder;
13520            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13521        }
13522    };
13523
13524    @Override
13525    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13526            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13527            final int[] userIds, int[] instantUserIds) {
13528        mHandler.post(new Runnable() {
13529            @Override
13530            public void run() {
13531                try {
13532                    final IActivityManager am = ActivityManager.getService();
13533                    if (am == null) return;
13534                    final int[] resolvedUserIds;
13535                    if (userIds == null) {
13536                        resolvedUserIds = am.getRunningUserIds();
13537                    } else {
13538                        resolvedUserIds = userIds;
13539                    }
13540                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13541                            resolvedUserIds, false);
13542                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13543                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13544                                instantUserIds, true);
13545                    }
13546                } catch (RemoteException ex) {
13547                }
13548            }
13549        });
13550    }
13551
13552    @Override
13553    public void notifyPackageAdded(String packageName) {
13554        final PackageListObserver[] observers;
13555        synchronized (mPackages) {
13556            if (mPackageListObservers.size() == 0) {
13557                return;
13558            }
13559            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13560        }
13561        for (int i = observers.length - 1; i >= 0; --i) {
13562            observers[i].onPackageAdded(packageName);
13563        }
13564    }
13565
13566    @Override
13567    public void notifyPackageRemoved(String packageName) {
13568        final PackageListObserver[] observers;
13569        synchronized (mPackages) {
13570            if (mPackageListObservers.size() == 0) {
13571                return;
13572            }
13573            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13574        }
13575        for (int i = observers.length - 1; i >= 0; --i) {
13576            observers[i].onPackageRemoved(packageName);
13577        }
13578    }
13579
13580    /**
13581     * Sends a broadcast for the given action.
13582     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13583     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13584     * the system and applications allowed to see instant applications to receive package
13585     * lifecycle events for instant applications.
13586     */
13587    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13588            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13589            int[] userIds, boolean isInstantApp)
13590                    throws RemoteException {
13591        for (int id : userIds) {
13592            final Intent intent = new Intent(action,
13593                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13594            final String[] requiredPermissions =
13595                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13596            if (extras != null) {
13597                intent.putExtras(extras);
13598            }
13599            if (targetPkg != null) {
13600                intent.setPackage(targetPkg);
13601            }
13602            // Modify the UID when posting to other users
13603            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13604            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13605                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13606                intent.putExtra(Intent.EXTRA_UID, uid);
13607            }
13608            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13609            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13610            if (DEBUG_BROADCASTS) {
13611                RuntimeException here = new RuntimeException("here");
13612                here.fillInStackTrace();
13613                Slog.d(TAG, "Sending to user " + id + ": "
13614                        + intent.toShortString(false, true, false, false)
13615                        + " " + intent.getExtras(), here);
13616            }
13617            am.broadcastIntent(null, intent, null, finishedReceiver,
13618                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13619                    null, finishedReceiver != null, false, id);
13620        }
13621    }
13622
13623    /**
13624     * Check if the external storage media is available. This is true if there
13625     * is a mounted external storage medium or if the external storage is
13626     * emulated.
13627     */
13628    private boolean isExternalMediaAvailable() {
13629        return mMediaMounted || Environment.isExternalStorageEmulated();
13630    }
13631
13632    @Override
13633    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13634        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13635            return null;
13636        }
13637        if (!isExternalMediaAvailable()) {
13638                // If the external storage is no longer mounted at this point,
13639                // the caller may not have been able to delete all of this
13640                // packages files and can not delete any more.  Bail.
13641            return null;
13642        }
13643        synchronized (mPackages) {
13644            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13645            if (lastPackage != null) {
13646                pkgs.remove(lastPackage);
13647            }
13648            if (pkgs.size() > 0) {
13649                return pkgs.get(0);
13650            }
13651        }
13652        return null;
13653    }
13654
13655    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13656        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13657                userId, andCode ? 1 : 0, packageName);
13658        if (mSystemReady) {
13659            msg.sendToTarget();
13660        } else {
13661            if (mPostSystemReadyMessages == null) {
13662                mPostSystemReadyMessages = new ArrayList<>();
13663            }
13664            mPostSystemReadyMessages.add(msg);
13665        }
13666    }
13667
13668    void startCleaningPackages() {
13669        // reader
13670        if (!isExternalMediaAvailable()) {
13671            return;
13672        }
13673        synchronized (mPackages) {
13674            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13675                return;
13676            }
13677        }
13678        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13679        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13680        IActivityManager am = ActivityManager.getService();
13681        if (am != null) {
13682            int dcsUid = -1;
13683            synchronized (mPackages) {
13684                if (!mDefaultContainerWhitelisted) {
13685                    mDefaultContainerWhitelisted = true;
13686                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13687                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13688                }
13689            }
13690            try {
13691                if (dcsUid > 0) {
13692                    am.backgroundWhitelistUid(dcsUid);
13693                }
13694                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13695                        UserHandle.USER_SYSTEM);
13696            } catch (RemoteException e) {
13697            }
13698        }
13699    }
13700
13701    /**
13702     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13703     * it is acting on behalf on an enterprise or the user).
13704     *
13705     * Note that the ordering of the conditionals in this method is important. The checks we perform
13706     * are as follows, in this order:
13707     *
13708     * 1) If the install is being performed by a system app, we can trust the app to have set the
13709     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13710     *    what it is.
13711     * 2) If the install is being performed by a device or profile owner app, the install reason
13712     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13713     *    set the install reason correctly. If the app targets an older SDK version where install
13714     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13715     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13716     * 3) In all other cases, the install is being performed by a regular app that is neither part
13717     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13718     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13719     *    set to enterprise policy and if so, change it to unknown instead.
13720     */
13721    private int fixUpInstallReason(String installerPackageName, int installerUid,
13722            int installReason) {
13723        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13724                == PERMISSION_GRANTED) {
13725            // If the install is being performed by a system app, we trust that app to have set the
13726            // install reason correctly.
13727            return installReason;
13728        }
13729        final String ownerPackage = mProtectedPackages.getDeviceOwnerOrProfileOwnerPackage(
13730                UserHandle.getUserId(installerUid));
13731        if (ownerPackage != null && ownerPackage.equals(installerPackageName)) {
13732            // If the install is being performed by a device or profile owner, the install
13733            // reason should be enterprise policy.
13734            return PackageManager.INSTALL_REASON_POLICY;
13735        }
13736
13737
13738        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13739            // If the install is being performed by a regular app (i.e. neither system app nor
13740            // device or profile owner), we have no reason to believe that the app is acting on
13741            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13742            // change it to unknown instead.
13743            return PackageManager.INSTALL_REASON_UNKNOWN;
13744        }
13745
13746        // If the install is being performed by a regular app and the install reason was set to any
13747        // value but enterprise policy, leave the install reason unchanged.
13748        return installReason;
13749    }
13750
13751    /**
13752     * Attempts to bind to the default container service explicitly instead of doing so lazily on
13753     * install commit.
13754     */
13755    void earlyBindToDefContainer() {
13756        mHandler.sendMessage(mHandler.obtainMessage(DEF_CONTAINER_BIND));
13757    }
13758
13759    void installStage(String packageName, File stagedDir,
13760            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13761            String installerPackageName, int installerUid, UserHandle user,
13762            PackageParser.SigningDetails signingDetails) {
13763        if (DEBUG_INSTANT) {
13764            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13765                Slog.d(TAG, "Ephemeral install of " + packageName);
13766            }
13767        }
13768        final VerificationInfo verificationInfo = new VerificationInfo(
13769                sessionParams.originatingUri, sessionParams.referrerUri,
13770                sessionParams.originatingUid, installerUid);
13771
13772        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13773
13774        final Message msg = mHandler.obtainMessage(INIT_COPY);
13775        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13776                sessionParams.installReason);
13777        final InstallParams params = new InstallParams(origin, null, observer,
13778                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13779                verificationInfo, user, sessionParams.abiOverride,
13780                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13781        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13782        msg.obj = params;
13783
13784        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13785                System.identityHashCode(msg.obj));
13786        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13787                System.identityHashCode(msg.obj));
13788
13789        mHandler.sendMessage(msg);
13790    }
13791
13792    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13793            int userId) {
13794        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13795        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13796        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13797        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13798        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13799                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13800
13801        // Send a session commit broadcast
13802        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13803        info.installReason = pkgSetting.getInstallReason(userId);
13804        info.appPackageName = packageName;
13805        sendSessionCommitBroadcast(info, userId);
13806    }
13807
13808    @Override
13809    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13810            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13811        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13812            return;
13813        }
13814        Bundle extras = new Bundle(1);
13815        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13816        final int uid = UserHandle.getUid(
13817                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13818        extras.putInt(Intent.EXTRA_UID, uid);
13819
13820        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13821                packageName, extras, 0, null, null, userIds, instantUserIds);
13822        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13823            mHandler.post(() -> {
13824                        for (int userId : userIds) {
13825                            sendBootCompletedBroadcastToSystemApp(
13826                                    packageName, includeStopped, userId);
13827                        }
13828                    }
13829            );
13830        }
13831    }
13832
13833    /**
13834     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13835     * automatically without needing an explicit launch.
13836     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13837     */
13838    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13839            int userId) {
13840        // If user is not running, the app didn't miss any broadcast
13841        if (!mUserManagerInternal.isUserRunning(userId)) {
13842            return;
13843        }
13844        final IActivityManager am = ActivityManager.getService();
13845        try {
13846            // Deliver LOCKED_BOOT_COMPLETED first
13847            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13848                    .setPackage(packageName);
13849            if (includeStopped) {
13850                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13851            }
13852            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13853            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13854                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13855
13856            // Deliver BOOT_COMPLETED only if user is unlocked
13857            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13858                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13859                if (includeStopped) {
13860                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13861                }
13862                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13863                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13864            }
13865        } catch (RemoteException e) {
13866            throw e.rethrowFromSystemServer();
13867        }
13868    }
13869
13870    @Override
13871    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13872            int userId) {
13873        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13874        PackageSetting pkgSetting;
13875        final int callingUid = Binder.getCallingUid();
13876        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13877                true /* requireFullPermission */, true /* checkShell */,
13878                "setApplicationHiddenSetting for user " + userId);
13879
13880        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13881            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13882            return false;
13883        }
13884
13885        long callingId = Binder.clearCallingIdentity();
13886        try {
13887            boolean sendAdded = false;
13888            boolean sendRemoved = false;
13889            // writer
13890            synchronized (mPackages) {
13891                pkgSetting = mSettings.mPackages.get(packageName);
13892                if (pkgSetting == null) {
13893                    return false;
13894                }
13895                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13896                    return false;
13897                }
13898                // Do not allow "android" is being disabled
13899                if ("android".equals(packageName)) {
13900                    Slog.w(TAG, "Cannot hide package: android");
13901                    return false;
13902                }
13903                // Cannot hide static shared libs as they are considered
13904                // a part of the using app (emulating static linking). Also
13905                // static libs are installed always on internal storage.
13906                PackageParser.Package pkg = mPackages.get(packageName);
13907                if (pkg != null && pkg.staticSharedLibName != null) {
13908                    Slog.w(TAG, "Cannot hide package: " + packageName
13909                            + " providing static shared library: "
13910                            + pkg.staticSharedLibName);
13911                    return false;
13912                }
13913                // Only allow protected packages to hide themselves.
13914                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13915                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13916                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13917                    return false;
13918                }
13919
13920                if (pkgSetting.getHidden(userId) != hidden) {
13921                    pkgSetting.setHidden(hidden, userId);
13922                    mSettings.writePackageRestrictionsLPr(userId);
13923                    if (hidden) {
13924                        sendRemoved = true;
13925                    } else {
13926                        sendAdded = true;
13927                    }
13928                }
13929            }
13930            if (sendAdded) {
13931                sendPackageAddedForUser(packageName, pkgSetting, userId);
13932                return true;
13933            }
13934            if (sendRemoved) {
13935                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13936                        "hiding pkg");
13937                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13938                return true;
13939            }
13940        } finally {
13941            Binder.restoreCallingIdentity(callingId);
13942        }
13943        return false;
13944    }
13945
13946    @Override
13947    public boolean setSystemAppInstallState(String packageName, boolean installed, int userId) {
13948        enforceSystemOrPhoneCaller("setSystemAppInstallState");
13949        PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13950        // The target app should always be in system
13951        if (pkgSetting == null || !pkgSetting.isSystem()) {
13952            return false;
13953        }
13954        // Check if the install state is the same
13955        if (pkgSetting.getInstalled(userId) == installed) {
13956            return false;
13957        }
13958
13959        long callingId = Binder.clearCallingIdentity();
13960        try {
13961            if (installed) {
13962                // install the app from uninstalled state
13963                installExistingPackageAsUser(
13964                        packageName,
13965                        userId,
13966                        0 /*installFlags*/,
13967                        PackageManager.INSTALL_REASON_DEVICE_SETUP);
13968                return true;
13969            }
13970
13971            // uninstall the app from installed state
13972            deletePackageVersioned(
13973                    new VersionedPackage(packageName, PackageManager.VERSION_CODE_HIGHEST),
13974                    new LegacyPackageDeleteObserver(null).getBinder(),
13975                    userId,
13976                    PackageManager.DELETE_SYSTEM_APP);
13977            return true;
13978        } finally {
13979            Binder.restoreCallingIdentity(callingId);
13980        }
13981    }
13982
13983    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13984            int userId) {
13985        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13986        info.removedPackage = packageName;
13987        info.installerPackageName = pkgSetting.installerPackageName;
13988        info.removedUsers = new int[] {userId};
13989        info.broadcastUsers = new int[] {userId};
13990        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13991        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13992    }
13993
13994    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended,
13995            PersistableBundle launcherExtras) {
13996        if (pkgList.length > 0) {
13997            Bundle extras = new Bundle(1);
13998            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13999            if (launcherExtras != null) {
14000                extras.putBundle(Intent.EXTRA_LAUNCHER_EXTRAS,
14001                        new Bundle(launcherExtras.deepCopy()));
14002            }
14003            sendPackageBroadcast(
14004                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14005                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14006                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14007                    new int[] {userId}, null);
14008        }
14009    }
14010
14011    /**
14012     * Returns true if application is not found or there was an error. Otherwise it returns
14013     * the hidden state of the package for the given user.
14014     */
14015    @Override
14016    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14017        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14018        final int callingUid = Binder.getCallingUid();
14019        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14020                true /* requireFullPermission */, false /* checkShell */,
14021                "getApplicationHidden for user " + userId);
14022        PackageSetting ps;
14023        long callingId = Binder.clearCallingIdentity();
14024        try {
14025            // writer
14026            synchronized (mPackages) {
14027                ps = mSettings.mPackages.get(packageName);
14028                if (ps == null) {
14029                    return true;
14030                }
14031                if (filterAppAccessLPr(ps, callingUid, userId)) {
14032                    return true;
14033                }
14034                return ps.getHidden(userId);
14035            }
14036        } finally {
14037            Binder.restoreCallingIdentity(callingId);
14038        }
14039    }
14040
14041    /**
14042     * @hide
14043     */
14044    @Override
14045    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14046            int installReason) {
14047        final int callingUid = Binder.getCallingUid();
14048        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES)
14049                != PackageManager.PERMISSION_GRANTED
14050                && mContext.checkCallingOrSelfPermission(
14051                        android.Manifest.permission.INSTALL_EXISTING_PACKAGES)
14052                != PackageManager.PERMISSION_GRANTED) {
14053            throw new SecurityException("Neither user " + callingUid + " nor current process has "
14054                    + android.Manifest.permission.INSTALL_PACKAGES + ".");
14055        }
14056        PackageSetting pkgSetting;
14057        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14058                true /* requireFullPermission */, true /* checkShell */,
14059                "installExistingPackage for user " + userId);
14060        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14061            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14062        }
14063
14064        long callingId = Binder.clearCallingIdentity();
14065        try {
14066            boolean installed = false;
14067            final boolean instantApp =
14068                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14069            final boolean fullApp =
14070                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14071
14072            // writer
14073            synchronized (mPackages) {
14074                pkgSetting = mSettings.mPackages.get(packageName);
14075                if (pkgSetting == null) {
14076                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14077                }
14078                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14079                    // only allow the existing package to be used if it's installed as a full
14080                    // application for at least one user
14081                    boolean installAllowed = false;
14082                    for (int checkUserId : sUserManager.getUserIds()) {
14083                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14084                        if (installAllowed) {
14085                            break;
14086                        }
14087                    }
14088                    if (!installAllowed) {
14089                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14090                    }
14091                }
14092                if (!pkgSetting.getInstalled(userId)) {
14093                    pkgSetting.setInstalled(true, userId);
14094                    pkgSetting.setHidden(false, userId);
14095                    pkgSetting.setInstallReason(installReason, userId);
14096                    mSettings.writePackageRestrictionsLPr(userId);
14097                    mSettings.writeKernelMappingLPr(pkgSetting);
14098                    installed = true;
14099                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14100                    // upgrade app from instant to full; we don't allow app downgrade
14101                    installed = true;
14102                }
14103                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14104            }
14105
14106            if (installed) {
14107                if (pkgSetting.pkg != null) {
14108                    synchronized (mInstallLock) {
14109                        // We don't need to freeze for a brand new install
14110                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14111                    }
14112                }
14113                sendPackageAddedForUser(packageName, pkgSetting, userId);
14114                synchronized (mPackages) {
14115                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14116                }
14117            }
14118        } finally {
14119            Binder.restoreCallingIdentity(callingId);
14120        }
14121
14122        return PackageManager.INSTALL_SUCCEEDED;
14123    }
14124
14125    static void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14126            boolean instantApp, boolean fullApp) {
14127        // no state specified; do nothing
14128        if (!instantApp && !fullApp) {
14129            return;
14130        }
14131        if (userId != UserHandle.USER_ALL) {
14132            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14133                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14134            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14135                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14136            }
14137        } else {
14138            for (int currentUserId : sUserManager.getUserIds()) {
14139                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14140                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14141                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14142                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14143                }
14144            }
14145        }
14146    }
14147
14148    boolean isUserRestricted(int userId, String restrictionKey) {
14149        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14150        if (restrictions.getBoolean(restrictionKey, false)) {
14151            Log.w(TAG, "User is restricted: " + restrictionKey);
14152            return true;
14153        }
14154        return false;
14155    }
14156
14157    @Override
14158    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14159            PersistableBundle appExtras, PersistableBundle launcherExtras, String dialogMessage,
14160            String callingPackage, int userId) {
14161        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS,
14162                "setPackagesSuspendedAsUser");
14163
14164        final int callingUid = Binder.getCallingUid();
14165        if (callingUid != Process.ROOT_UID && callingUid != Process.SYSTEM_UID
14166                && getPackageUid(callingPackage, 0, userId) != callingUid) {
14167            throw new SecurityException("Calling package " + callingPackage + " in user "
14168                    + userId + " does not belong to calling uid " + callingUid);
14169        }
14170        if (!PLATFORM_PACKAGE_NAME.equals(callingPackage)
14171                && mProtectedPackages.getDeviceOwnerOrProfileOwnerPackage(userId) != null) {
14172            throw new UnsupportedOperationException("Cannot suspend/unsuspend packages. User "
14173                    + userId + " has an active DO or PO");
14174        }
14175        if (ArrayUtils.isEmpty(packageNames)) {
14176            return packageNames;
14177        }
14178
14179        final List<String> changedPackagesList = new ArrayList<>(packageNames.length);
14180        final List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14181        final long callingId = Binder.clearCallingIdentity();
14182        try {
14183            synchronized (mPackages) {
14184                for (int i = 0; i < packageNames.length; i++) {
14185                    final String packageName = packageNames[i];
14186                    if (callingPackage.equals(packageName)) {
14187                        Slog.w(TAG, "Calling package: " + callingPackage + " trying to "
14188                                + (suspended ? "" : "un") + "suspend itself. Ignoring");
14189                        unactionedPackages.add(packageName);
14190                        continue;
14191                    }
14192                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14193                    if (pkgSetting == null
14194                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14195                        Slog.w(TAG, "Could not find package setting for package: " + packageName
14196                                + ". Skipping suspending/un-suspending.");
14197                        unactionedPackages.add(packageName);
14198                        continue;
14199                    }
14200                    if (!canSuspendPackageForUserLocked(packageName, userId)) {
14201                        unactionedPackages.add(packageName);
14202                        continue;
14203                    }
14204                    pkgSetting.setSuspended(suspended, callingPackage, dialogMessage, appExtras,
14205                            launcherExtras, userId);
14206                    changedPackagesList.add(packageName);
14207                }
14208            }
14209        } finally {
14210            Binder.restoreCallingIdentity(callingId);
14211        }
14212        if (!changedPackagesList.isEmpty()) {
14213            final String[] changedPackages = changedPackagesList.toArray(
14214                    new String[changedPackagesList.size()]);
14215            sendPackagesSuspendedForUser(changedPackages, userId, suspended, launcherExtras);
14216            sendMyPackageSuspendedOrUnsuspended(changedPackages, suspended, appExtras, userId);
14217            synchronized (mPackages) {
14218                scheduleWritePackageRestrictionsLocked(userId);
14219            }
14220        }
14221        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14222    }
14223
14224    @Override
14225    public PersistableBundle getSuspendedPackageAppExtras(String packageName, int userId) {
14226        final int callingUid = Binder.getCallingUid();
14227        if (getPackageUid(packageName, 0, userId) != callingUid) {
14228            throw new SecurityException("Calling package " + packageName
14229                    + " does not belong to calling uid " + callingUid);
14230        }
14231        synchronized (mPackages) {
14232            final PackageSetting ps = mSettings.mPackages.get(packageName);
14233            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14234                throw new IllegalArgumentException("Unknown target package: " + packageName);
14235            }
14236            final PackageUserState packageUserState = ps.readUserState(userId);
14237            if (packageUserState.suspended) {
14238                return packageUserState.suspendedAppExtras;
14239            }
14240            return null;
14241        }
14242    }
14243
14244    private void sendMyPackageSuspendedOrUnsuspended(String[] affectedPackages, boolean suspended,
14245            PersistableBundle appExtras, int userId) {
14246        final String action;
14247        final Bundle intentExtras = new Bundle();
14248        if (suspended) {
14249            action = Intent.ACTION_MY_PACKAGE_SUSPENDED;
14250            if (appExtras != null) {
14251                final Bundle bundledAppExtras = new Bundle(appExtras.deepCopy());
14252                intentExtras.putBundle(Intent.EXTRA_SUSPENDED_PACKAGE_EXTRAS, bundledAppExtras);
14253            }
14254        } else {
14255            action = Intent.ACTION_MY_PACKAGE_UNSUSPENDED;
14256        }
14257        mHandler.post(new Runnable() {
14258            @Override
14259            public void run() {
14260                try {
14261                    final IActivityManager am = ActivityManager.getService();
14262                    if (am == null) {
14263                        Slog.wtf(TAG, "IActivityManager null. Cannot send MY_PACKAGE_ "
14264                                + (suspended ? "" : "UN") + "SUSPENDED broadcasts");
14265                        return;
14266                    }
14267                    final int[] targetUserIds = new int[] {userId};
14268                    for (String packageName : affectedPackages) {
14269                        doSendBroadcast(am, action, null, intentExtras,
14270                                Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, packageName, null,
14271                                targetUserIds, false);
14272                    }
14273                } catch (RemoteException ex) {
14274                    // Shouldn't happen as AMS is in the same process.
14275                }
14276            }
14277        });
14278    }
14279
14280    @Override
14281    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14282        final int callingUid = Binder.getCallingUid();
14283        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14284                true /* requireFullPermission */, false /* checkShell */,
14285                "isPackageSuspendedForUser for user " + userId);
14286        synchronized (mPackages) {
14287            final PackageSetting ps = mSettings.mPackages.get(packageName);
14288            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14289                throw new IllegalArgumentException("Unknown target package: " + packageName);
14290            }
14291            return ps.getSuspended(userId);
14292        }
14293    }
14294
14295    /**
14296     * Immediately unsuspends any packages suspended by the given package. To be called
14297     * when such a package's data is cleared or it is removed from the device.
14298     *
14299     * <p><b>Should not be used on a frequent code path</b> as it flushes state to disk
14300     * synchronously
14301     *
14302     * @param packageName The package holding {@link Manifest.permission#SUSPEND_APPS} permission
14303     * @param affectedUser The user for which the changes are taking place.
14304     */
14305    void unsuspendForSuspendingPackage(final String packageName, int affectedUser) {
14306        final int[] userIds = (affectedUser == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14307                : new int[] {affectedUser};
14308        for (int userId : userIds) {
14309            unsuspendForSuspendingPackages(packageName::equals, userId);
14310        }
14311    }
14312
14313    /**
14314     * Immediately unsuspends any packages in the given users not suspended by the platform or root.
14315     * To be called when a profile owner or a device owner is added.
14316     *
14317     * <p><b>Should not be used on a frequent code path</b> as it flushes state to disk
14318     * synchronously
14319     *
14320     * @param userIds The users for which to unsuspend packages
14321     */
14322    void unsuspendForNonSystemSuspendingPackages(ArraySet<Integer> userIds) {
14323        final int sz = userIds.size();
14324        for (int i = 0; i < sz; i++) {
14325            unsuspendForSuspendingPackages(
14326                    (suspendingPackage) -> !PLATFORM_PACKAGE_NAME.equals(suspendingPackage),
14327                    userIds.valueAt(i));
14328        }
14329    }
14330
14331    private void unsuspendForSuspendingPackages(Predicate<String> packagePredicate, int userId) {
14332        final List<String> affectedPackages = new ArrayList<>();
14333        synchronized (mPackages) {
14334            for (PackageSetting ps : mSettings.mPackages.values()) {
14335                final PackageUserState pus = ps.readUserState(userId);
14336                if (pus.suspended && packagePredicate.test(pus.suspendingPackage)) {
14337                    ps.setSuspended(false, null, null, null, null, userId);
14338                    affectedPackages.add(ps.name);
14339                }
14340            }
14341        }
14342        if (!affectedPackages.isEmpty()) {
14343            final String[] packageArray = affectedPackages.toArray(
14344                    new String[affectedPackages.size()]);
14345            sendMyPackageSuspendedOrUnsuspended(packageArray, false, null, userId);
14346            sendPackagesSuspendedForUser(packageArray, userId, false, null);
14347            // Write package restrictions immediately to avoid an inconsistent state.
14348            mSettings.writePackageRestrictionsLPr(userId);
14349        }
14350    }
14351
14352    @GuardedBy("mPackages")
14353    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14354        if (isPackageDeviceAdmin(packageName, userId)) {
14355            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14356                    + "\": has an active device admin");
14357            return false;
14358        }
14359
14360        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14361        if (packageName.equals(activeLauncherPackageName)) {
14362            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14363                    + "\": contains the active launcher");
14364            return false;
14365        }
14366
14367        if (packageName.equals(mRequiredInstallerPackage)) {
14368            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14369                    + "\": required for package installation");
14370            return false;
14371        }
14372
14373        if (packageName.equals(mRequiredUninstallerPackage)) {
14374            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14375                    + "\": required for package uninstallation");
14376            return false;
14377        }
14378
14379        if (packageName.equals(mRequiredVerifierPackage)) {
14380            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14381                    + "\": required for package verification");
14382            return false;
14383        }
14384
14385        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14386            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14387                    + "\": is the default dialer");
14388            return false;
14389        }
14390
14391        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14392            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14393                    + "\": protected package");
14394            return false;
14395        }
14396
14397        // Cannot suspend static shared libs as they are considered
14398        // a part of the using app (emulating static linking). Also
14399        // static libs are installed always on internal storage.
14400        PackageParser.Package pkg = mPackages.get(packageName);
14401        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14402            Slog.w(TAG, "Cannot suspend package: " + packageName
14403                    + " providing static shared library: "
14404                    + pkg.staticSharedLibName);
14405            return false;
14406        }
14407
14408        if (PLATFORM_PACKAGE_NAME.equals(packageName)) {
14409            Slog.w(TAG, "Cannot suspend package: " + packageName);
14410            return false;
14411        }
14412
14413        return true;
14414    }
14415
14416    private String getActiveLauncherPackageName(int userId) {
14417        Intent intent = new Intent(Intent.ACTION_MAIN);
14418        intent.addCategory(Intent.CATEGORY_HOME);
14419        ResolveInfo resolveInfo = resolveIntent(
14420                intent,
14421                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14422                PackageManager.MATCH_DEFAULT_ONLY,
14423                userId);
14424
14425        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14426    }
14427
14428    private String getDefaultDialerPackageName(int userId) {
14429        synchronized (mPackages) {
14430            return mSettings.getDefaultDialerPackageNameLPw(userId);
14431        }
14432    }
14433
14434    @Override
14435    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14436        mContext.enforceCallingOrSelfPermission(
14437                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14438                "Only package verification agents can verify applications");
14439
14440        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14441        final PackageVerificationResponse response = new PackageVerificationResponse(
14442                verificationCode, Binder.getCallingUid());
14443        msg.arg1 = id;
14444        msg.obj = response;
14445        mHandler.sendMessage(msg);
14446    }
14447
14448    @Override
14449    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14450            long millisecondsToDelay) {
14451        mContext.enforceCallingOrSelfPermission(
14452                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14453                "Only package verification agents can extend verification timeouts");
14454
14455        final PackageVerificationState state = mPendingVerification.get(id);
14456        final PackageVerificationResponse response = new PackageVerificationResponse(
14457                verificationCodeAtTimeout, Binder.getCallingUid());
14458
14459        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14460            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14461        }
14462        if (millisecondsToDelay < 0) {
14463            millisecondsToDelay = 0;
14464        }
14465        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14466                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14467            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14468        }
14469
14470        if ((state != null) && !state.timeoutExtended()) {
14471            state.extendTimeout();
14472
14473            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14474            msg.arg1 = id;
14475            msg.obj = response;
14476            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14477        }
14478    }
14479
14480    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14481            int verificationCode, UserHandle user) {
14482        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14483        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14484        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14485        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14486        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14487
14488        mContext.sendBroadcastAsUser(intent, user,
14489                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14490    }
14491
14492    private ComponentName matchComponentForVerifier(String packageName,
14493            List<ResolveInfo> receivers) {
14494        ActivityInfo targetReceiver = null;
14495
14496        final int NR = receivers.size();
14497        for (int i = 0; i < NR; i++) {
14498            final ResolveInfo info = receivers.get(i);
14499            if (info.activityInfo == null) {
14500                continue;
14501            }
14502
14503            if (packageName.equals(info.activityInfo.packageName)) {
14504                targetReceiver = info.activityInfo;
14505                break;
14506            }
14507        }
14508
14509        if (targetReceiver == null) {
14510            return null;
14511        }
14512
14513        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14514    }
14515
14516    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14517            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14518        if (pkgInfo.verifiers.length == 0) {
14519            return null;
14520        }
14521
14522        final int N = pkgInfo.verifiers.length;
14523        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14524        for (int i = 0; i < N; i++) {
14525            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14526
14527            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14528                    receivers);
14529            if (comp == null) {
14530                continue;
14531            }
14532
14533            final int verifierUid = getUidForVerifier(verifierInfo);
14534            if (verifierUid == -1) {
14535                continue;
14536            }
14537
14538            if (DEBUG_VERIFY) {
14539                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14540                        + " with the correct signature");
14541            }
14542            sufficientVerifiers.add(comp);
14543            verificationState.addSufficientVerifier(verifierUid);
14544        }
14545
14546        return sufficientVerifiers;
14547    }
14548
14549    private int getUidForVerifier(VerifierInfo verifierInfo) {
14550        synchronized (mPackages) {
14551            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14552            if (pkg == null) {
14553                return -1;
14554            } else if (pkg.mSigningDetails.signatures.length != 1) {
14555                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14556                        + " has more than one signature; ignoring");
14557                return -1;
14558            }
14559
14560            /*
14561             * If the public key of the package's signature does not match
14562             * our expected public key, then this is a different package and
14563             * we should skip.
14564             */
14565
14566            final byte[] expectedPublicKey;
14567            try {
14568                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14569                final PublicKey publicKey = verifierSig.getPublicKey();
14570                expectedPublicKey = publicKey.getEncoded();
14571            } catch (CertificateException e) {
14572                return -1;
14573            }
14574
14575            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14576
14577            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14578                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14579                        + " does not have the expected public key; ignoring");
14580                return -1;
14581            }
14582
14583            return pkg.applicationInfo.uid;
14584        }
14585    }
14586
14587    @Override
14588    public void finishPackageInstall(int token, boolean didLaunch) {
14589        enforceSystemOrRoot("Only the system is allowed to finish installs");
14590
14591        if (DEBUG_INSTALL) {
14592            Slog.v(TAG, "BM finishing package install for " + token);
14593        }
14594        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14595
14596        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14597        mHandler.sendMessage(msg);
14598    }
14599
14600    /**
14601     * Get the verification agent timeout.  Used for both the APK verifier and the
14602     * intent filter verifier.
14603     *
14604     * @return verification timeout in milliseconds
14605     */
14606    private long getVerificationTimeout() {
14607        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14608                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14609                DEFAULT_VERIFICATION_TIMEOUT);
14610    }
14611
14612    /**
14613     * Get the default verification agent response code.
14614     *
14615     * @return default verification response code
14616     */
14617    private int getDefaultVerificationResponse(UserHandle user) {
14618        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14619            return PackageManager.VERIFICATION_REJECT;
14620        }
14621        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14622                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14623                DEFAULT_VERIFICATION_RESPONSE);
14624    }
14625
14626    /**
14627     * Check whether or not package verification has been enabled.
14628     *
14629     * @return true if verification should be performed
14630     */
14631    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14632        if (!DEFAULT_VERIFY_ENABLE) {
14633            return false;
14634        }
14635
14636        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14637
14638        // Check if installing from ADB
14639        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14640            // Do not run verification in a test harness environment
14641            if (ActivityManager.isRunningInTestHarness()) {
14642                return false;
14643            }
14644            if (ensureVerifyAppsEnabled) {
14645                return true;
14646            }
14647            // Check if the developer does not want package verification for ADB installs
14648            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14649                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14650                return false;
14651            }
14652        } else {
14653            // only when not installed from ADB, skip verification for instant apps when
14654            // the installer and verifier are the same.
14655            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14656                if (mInstantAppInstallerActivity != null
14657                        && mInstantAppInstallerActivity.packageName.equals(
14658                                mRequiredVerifierPackage)) {
14659                    try {
14660                        mContext.getSystemService(AppOpsManager.class)
14661                                .checkPackage(installerUid, mRequiredVerifierPackage);
14662                        if (DEBUG_VERIFY) {
14663                            Slog.i(TAG, "disable verification for instant app");
14664                        }
14665                        return false;
14666                    } catch (SecurityException ignore) { }
14667                }
14668            }
14669        }
14670
14671        if (ensureVerifyAppsEnabled) {
14672            return true;
14673        }
14674
14675        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14676                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14677    }
14678
14679    @Override
14680    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14681            throws RemoteException {
14682        mContext.enforceCallingOrSelfPermission(
14683                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14684                "Only intentfilter verification agents can verify applications");
14685
14686        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14687        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14688                Binder.getCallingUid(), verificationCode, failedDomains);
14689        msg.arg1 = id;
14690        msg.obj = response;
14691        mHandler.sendMessage(msg);
14692    }
14693
14694    @Override
14695    public int getIntentVerificationStatus(String packageName, int userId) {
14696        final int callingUid = Binder.getCallingUid();
14697        if (UserHandle.getUserId(callingUid) != userId) {
14698            mContext.enforceCallingOrSelfPermission(
14699                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14700                    "getIntentVerificationStatus" + userId);
14701        }
14702        if (getInstantAppPackageName(callingUid) != null) {
14703            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14704        }
14705        synchronized (mPackages) {
14706            final PackageSetting ps = mSettings.mPackages.get(packageName);
14707            if (ps == null
14708                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14709                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14710            }
14711            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14712        }
14713    }
14714
14715    @Override
14716    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14717        mContext.enforceCallingOrSelfPermission(
14718                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14719
14720        boolean result = false;
14721        synchronized (mPackages) {
14722            final PackageSetting ps = mSettings.mPackages.get(packageName);
14723            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14724                return false;
14725            }
14726            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14727        }
14728        if (result) {
14729            scheduleWritePackageRestrictionsLocked(userId);
14730        }
14731        return result;
14732    }
14733
14734    @Override
14735    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14736            String packageName) {
14737        final int callingUid = Binder.getCallingUid();
14738        if (getInstantAppPackageName(callingUid) != null) {
14739            return ParceledListSlice.emptyList();
14740        }
14741        synchronized (mPackages) {
14742            final PackageSetting ps = mSettings.mPackages.get(packageName);
14743            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14744                return ParceledListSlice.emptyList();
14745            }
14746            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14747        }
14748    }
14749
14750    @Override
14751    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14752        if (TextUtils.isEmpty(packageName)) {
14753            return ParceledListSlice.emptyList();
14754        }
14755        final int callingUid = Binder.getCallingUid();
14756        final int callingUserId = UserHandle.getUserId(callingUid);
14757        synchronized (mPackages) {
14758            PackageParser.Package pkg = mPackages.get(packageName);
14759            if (pkg == null || pkg.activities == null) {
14760                return ParceledListSlice.emptyList();
14761            }
14762            if (pkg.mExtras == null) {
14763                return ParceledListSlice.emptyList();
14764            }
14765            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14766            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14767                return ParceledListSlice.emptyList();
14768            }
14769            final int count = pkg.activities.size();
14770            ArrayList<IntentFilter> result = new ArrayList<>();
14771            for (int n=0; n<count; n++) {
14772                PackageParser.Activity activity = pkg.activities.get(n);
14773                if (activity.intents != null && activity.intents.size() > 0) {
14774                    result.addAll(activity.intents);
14775                }
14776            }
14777            return new ParceledListSlice<>(result);
14778        }
14779    }
14780
14781    @Override
14782    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14783        mContext.enforceCallingOrSelfPermission(
14784                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14785        if (UserHandle.getCallingUserId() != userId) {
14786            mContext.enforceCallingOrSelfPermission(
14787                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14788        }
14789
14790        synchronized (mPackages) {
14791            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14792            if (packageName != null) {
14793                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14794                        packageName, userId);
14795            }
14796            return result;
14797        }
14798    }
14799
14800    @Override
14801    public String getDefaultBrowserPackageName(int userId) {
14802        if (UserHandle.getCallingUserId() != userId) {
14803            mContext.enforceCallingOrSelfPermission(
14804                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14805        }
14806        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14807            return null;
14808        }
14809        synchronized (mPackages) {
14810            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14811        }
14812    }
14813
14814    /**
14815     * Get the "allow unknown sources" setting.
14816     *
14817     * @return the current "allow unknown sources" setting
14818     */
14819    private int getUnknownSourcesSettings() {
14820        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14821                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14822                -1);
14823    }
14824
14825    @Override
14826    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14827        final int callingUid = Binder.getCallingUid();
14828        if (getInstantAppPackageName(callingUid) != null) {
14829            return;
14830        }
14831        // writer
14832        synchronized (mPackages) {
14833            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14834            if (targetPackageSetting == null
14835                    || filterAppAccessLPr(
14836                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14837                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14838            }
14839
14840            PackageSetting installerPackageSetting;
14841            if (installerPackageName != null) {
14842                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14843                if (installerPackageSetting == null) {
14844                    throw new IllegalArgumentException("Unknown installer package: "
14845                            + installerPackageName);
14846                }
14847            } else {
14848                installerPackageSetting = null;
14849            }
14850
14851            Signature[] callerSignature;
14852            Object obj = mSettings.getUserIdLPr(callingUid);
14853            if (obj != null) {
14854                if (obj instanceof SharedUserSetting) {
14855                    callerSignature =
14856                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14857                } else if (obj instanceof PackageSetting) {
14858                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14859                } else {
14860                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14861                }
14862            } else {
14863                throw new SecurityException("Unknown calling UID: " + callingUid);
14864            }
14865
14866            // Verify: can't set installerPackageName to a package that is
14867            // not signed with the same cert as the caller.
14868            if (installerPackageSetting != null) {
14869                if (compareSignatures(callerSignature,
14870                        installerPackageSetting.signatures.mSigningDetails.signatures)
14871                        != PackageManager.SIGNATURE_MATCH) {
14872                    throw new SecurityException(
14873                            "Caller does not have same cert as new installer package "
14874                            + installerPackageName);
14875                }
14876            }
14877
14878            // Verify: if target already has an installer package, it must
14879            // be signed with the same cert as the caller.
14880            if (targetPackageSetting.installerPackageName != null) {
14881                PackageSetting setting = mSettings.mPackages.get(
14882                        targetPackageSetting.installerPackageName);
14883                // If the currently set package isn't valid, then it's always
14884                // okay to change it.
14885                if (setting != null) {
14886                    if (compareSignatures(callerSignature,
14887                            setting.signatures.mSigningDetails.signatures)
14888                            != PackageManager.SIGNATURE_MATCH) {
14889                        throw new SecurityException(
14890                                "Caller does not have same cert as old installer package "
14891                                + targetPackageSetting.installerPackageName);
14892                    }
14893                }
14894            }
14895
14896            // Okay!
14897            targetPackageSetting.installerPackageName = installerPackageName;
14898            if (installerPackageName != null) {
14899                mSettings.mInstallerPackages.add(installerPackageName);
14900            }
14901            scheduleWriteSettingsLocked();
14902        }
14903    }
14904
14905    @Override
14906    public void setApplicationCategoryHint(String packageName, int categoryHint,
14907            String callerPackageName) {
14908        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14909            throw new SecurityException("Instant applications don't have access to this method");
14910        }
14911        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14912                callerPackageName);
14913        synchronized (mPackages) {
14914            PackageSetting ps = mSettings.mPackages.get(packageName);
14915            if (ps == null) {
14916                throw new IllegalArgumentException("Unknown target package " + packageName);
14917            }
14918            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14919                throw new IllegalArgumentException("Unknown target package " + packageName);
14920            }
14921            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14922                throw new IllegalArgumentException("Calling package " + callerPackageName
14923                        + " is not installer for " + packageName);
14924            }
14925
14926            if (ps.categoryHint != categoryHint) {
14927                ps.categoryHint = categoryHint;
14928                scheduleWriteSettingsLocked();
14929            }
14930        }
14931    }
14932
14933    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14934        // Queue up an async operation since the package installation may take a little while.
14935        mHandler.post(new Runnable() {
14936            public void run() {
14937                mHandler.removeCallbacks(this);
14938                 // Result object to be returned
14939                PackageInstalledInfo res = new PackageInstalledInfo();
14940                res.setReturnCode(currentStatus);
14941                res.uid = -1;
14942                res.pkg = null;
14943                res.removedInfo = null;
14944                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14945                    args.doPreInstall(res.returnCode);
14946                    synchronized (mInstallLock) {
14947                        installPackageTracedLI(args, res);
14948                    }
14949                    args.doPostInstall(res.returnCode, res.uid);
14950                }
14951
14952                // A restore should be performed at this point if (a) the install
14953                // succeeded, (b) the operation is not an update, and (c) the new
14954                // package has not opted out of backup participation.
14955                final boolean update = res.removedInfo != null
14956                        && res.removedInfo.removedPackage != null;
14957                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14958                boolean doRestore = !update
14959                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14960
14961                // Set up the post-install work request bookkeeping.  This will be used
14962                // and cleaned up by the post-install event handling regardless of whether
14963                // there's a restore pass performed.  Token values are >= 1.
14964                int token;
14965                if (mNextInstallToken < 0) mNextInstallToken = 1;
14966                token = mNextInstallToken++;
14967
14968                PostInstallData data = new PostInstallData(args, res);
14969                mRunningInstalls.put(token, data);
14970                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14971
14972                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14973                    // Pass responsibility to the Backup Manager.  It will perform a
14974                    // restore if appropriate, then pass responsibility back to the
14975                    // Package Manager to run the post-install observer callbacks
14976                    // and broadcasts.
14977                    IBackupManager bm = IBackupManager.Stub.asInterface(
14978                            ServiceManager.getService(Context.BACKUP_SERVICE));
14979                    if (bm != null) {
14980                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14981                                + " to BM for possible restore");
14982                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14983                        try {
14984                            // TODO: http://b/22388012
14985                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14986                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14987                            } else {
14988                                doRestore = false;
14989                            }
14990                        } catch (RemoteException e) {
14991                            // can't happen; the backup manager is local
14992                        } catch (Exception e) {
14993                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14994                            doRestore = false;
14995                        }
14996                    } else {
14997                        Slog.e(TAG, "Backup Manager not found!");
14998                        doRestore = false;
14999                    }
15000                }
15001
15002                if (!doRestore) {
15003                    // No restore possible, or the Backup Manager was mysteriously not
15004                    // available -- just fire the post-install work request directly.
15005                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15006
15007                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15008
15009                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15010                    mHandler.sendMessage(msg);
15011                }
15012            }
15013        });
15014    }
15015
15016    /**
15017     * Callback from PackageSettings whenever an app is first transitioned out of the
15018     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15019     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15020     * here whether the app is the target of an ongoing install, and only send the
15021     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15022     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15023     * handling.
15024     */
15025    void notifyFirstLaunch(final String packageName, final String installerPackage,
15026            final int userId) {
15027        // Serialize this with the rest of the install-process message chain.  In the
15028        // restore-at-install case, this Runnable will necessarily run before the
15029        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15030        // are coherent.  In the non-restore case, the app has already completed install
15031        // and been launched through some other means, so it is not in a problematic
15032        // state for observers to see the FIRST_LAUNCH signal.
15033        mHandler.post(new Runnable() {
15034            @Override
15035            public void run() {
15036                for (int i = 0; i < mRunningInstalls.size(); i++) {
15037                    final PostInstallData data = mRunningInstalls.valueAt(i);
15038                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15039                        continue;
15040                    }
15041                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
15042                        // right package; but is it for the right user?
15043                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15044                            if (userId == data.res.newUsers[uIndex]) {
15045                                if (DEBUG_BACKUP) {
15046                                    Slog.i(TAG, "Package " + packageName
15047                                            + " being restored so deferring FIRST_LAUNCH");
15048                                }
15049                                return;
15050                            }
15051                        }
15052                    }
15053                }
15054                // didn't find it, so not being restored
15055                if (DEBUG_BACKUP) {
15056                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
15057                }
15058                final boolean isInstantApp = isInstantApp(packageName, userId);
15059                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
15060                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
15061                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
15062            }
15063        });
15064    }
15065
15066    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
15067            int[] userIds, int[] instantUserIds) {
15068        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15069                installerPkg, null, userIds, instantUserIds);
15070    }
15071
15072    private abstract class HandlerParams {
15073        private static final int MAX_RETRIES = 4;
15074
15075        /**
15076         * Number of times startCopy() has been attempted and had a non-fatal
15077         * error.
15078         */
15079        private int mRetries = 0;
15080
15081        /** User handle for the user requesting the information or installation. */
15082        private final UserHandle mUser;
15083        String traceMethod;
15084        int traceCookie;
15085
15086        HandlerParams(UserHandle user) {
15087            mUser = user;
15088        }
15089
15090        UserHandle getUser() {
15091            return mUser;
15092        }
15093
15094        HandlerParams setTraceMethod(String traceMethod) {
15095            this.traceMethod = traceMethod;
15096            return this;
15097        }
15098
15099        HandlerParams setTraceCookie(int traceCookie) {
15100            this.traceCookie = traceCookie;
15101            return this;
15102        }
15103
15104        final boolean startCopy() {
15105            boolean res;
15106            try {
15107                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15108
15109                if (++mRetries > MAX_RETRIES) {
15110                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15111                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15112                    handleServiceError();
15113                    return false;
15114                } else {
15115                    handleStartCopy();
15116                    res = true;
15117                }
15118            } catch (RemoteException e) {
15119                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15120                mHandler.sendEmptyMessage(MCS_RECONNECT);
15121                res = false;
15122            }
15123            handleReturnCode();
15124            return res;
15125        }
15126
15127        final void serviceError() {
15128            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15129            handleServiceError();
15130            handleReturnCode();
15131        }
15132
15133        abstract void handleStartCopy() throws RemoteException;
15134        abstract void handleServiceError();
15135        abstract void handleReturnCode();
15136    }
15137
15138    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15139        for (File path : paths) {
15140            try {
15141                mcs.clearDirectory(path.getAbsolutePath());
15142            } catch (RemoteException e) {
15143            }
15144        }
15145    }
15146
15147    static class OriginInfo {
15148        /**
15149         * Location where install is coming from, before it has been
15150         * copied/renamed into place. This could be a single monolithic APK
15151         * file, or a cluster directory. This location may be untrusted.
15152         */
15153        final File file;
15154
15155        /**
15156         * Flag indicating that {@link #file} or {@link #cid} has already been
15157         * staged, meaning downstream users don't need to defensively copy the
15158         * contents.
15159         */
15160        final boolean staged;
15161
15162        /**
15163         * Flag indicating that {@link #file} or {@link #cid} is an already
15164         * installed app that is being moved.
15165         */
15166        final boolean existing;
15167
15168        final String resolvedPath;
15169        final File resolvedFile;
15170
15171        static OriginInfo fromNothing() {
15172            return new OriginInfo(null, false, false);
15173        }
15174
15175        static OriginInfo fromUntrustedFile(File file) {
15176            return new OriginInfo(file, false, false);
15177        }
15178
15179        static OriginInfo fromExistingFile(File file) {
15180            return new OriginInfo(file, false, true);
15181        }
15182
15183        static OriginInfo fromStagedFile(File file) {
15184            return new OriginInfo(file, true, false);
15185        }
15186
15187        private OriginInfo(File file, boolean staged, boolean existing) {
15188            this.file = file;
15189            this.staged = staged;
15190            this.existing = existing;
15191
15192            if (file != null) {
15193                resolvedPath = file.getAbsolutePath();
15194                resolvedFile = file;
15195            } else {
15196                resolvedPath = null;
15197                resolvedFile = null;
15198            }
15199        }
15200    }
15201
15202    static class MoveInfo {
15203        final int moveId;
15204        final String fromUuid;
15205        final String toUuid;
15206        final String packageName;
15207        final String dataAppName;
15208        final int appId;
15209        final String seinfo;
15210        final int targetSdkVersion;
15211
15212        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15213                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15214            this.moveId = moveId;
15215            this.fromUuid = fromUuid;
15216            this.toUuid = toUuid;
15217            this.packageName = packageName;
15218            this.dataAppName = dataAppName;
15219            this.appId = appId;
15220            this.seinfo = seinfo;
15221            this.targetSdkVersion = targetSdkVersion;
15222        }
15223    }
15224
15225    static class VerificationInfo {
15226        /** A constant used to indicate that a uid value is not present. */
15227        public static final int NO_UID = -1;
15228
15229        /** URI referencing where the package was downloaded from. */
15230        final Uri originatingUri;
15231
15232        /** HTTP referrer URI associated with the originatingURI. */
15233        final Uri referrer;
15234
15235        /** UID of the application that the install request originated from. */
15236        final int originatingUid;
15237
15238        /** UID of application requesting the install */
15239        final int installerUid;
15240
15241        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15242            this.originatingUri = originatingUri;
15243            this.referrer = referrer;
15244            this.originatingUid = originatingUid;
15245            this.installerUid = installerUid;
15246        }
15247    }
15248
15249    class InstallParams extends HandlerParams {
15250        final OriginInfo origin;
15251        final MoveInfo move;
15252        final IPackageInstallObserver2 observer;
15253        int installFlags;
15254        final String installerPackageName;
15255        final String volumeUuid;
15256        private InstallArgs mArgs;
15257        private int mRet;
15258        final String packageAbiOverride;
15259        final String[] grantedRuntimePermissions;
15260        final VerificationInfo verificationInfo;
15261        final PackageParser.SigningDetails signingDetails;
15262        final int installReason;
15263
15264        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15265                int installFlags, String installerPackageName, String volumeUuid,
15266                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15267                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
15268            super(user);
15269            this.origin = origin;
15270            this.move = move;
15271            this.observer = observer;
15272            this.installFlags = installFlags;
15273            this.installerPackageName = installerPackageName;
15274            this.volumeUuid = volumeUuid;
15275            this.verificationInfo = verificationInfo;
15276            this.packageAbiOverride = packageAbiOverride;
15277            this.grantedRuntimePermissions = grantedPermissions;
15278            this.signingDetails = signingDetails;
15279            this.installReason = installReason;
15280        }
15281
15282        @Override
15283        public String toString() {
15284            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15285                    + " file=" + origin.file + "}";
15286        }
15287
15288        private int installLocationPolicy(PackageInfoLite pkgLite) {
15289            String packageName = pkgLite.packageName;
15290            int installLocation = pkgLite.installLocation;
15291            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15292            // reader
15293            synchronized (mPackages) {
15294                // Currently installed package which the new package is attempting to replace or
15295                // null if no such package is installed.
15296                PackageParser.Package installedPkg = mPackages.get(packageName);
15297                // Package which currently owns the data which the new package will own if installed.
15298                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15299                // will be null whereas dataOwnerPkg will contain information about the package
15300                // which was uninstalled while keeping its data.
15301                PackageParser.Package dataOwnerPkg = installedPkg;
15302                if (dataOwnerPkg  == null) {
15303                    PackageSetting ps = mSettings.mPackages.get(packageName);
15304                    if (ps != null) {
15305                        dataOwnerPkg = ps.pkg;
15306                    }
15307                }
15308
15309                if (dataOwnerPkg != null) {
15310                    // If installed, the package will get access to data left on the device by its
15311                    // predecessor. As a security measure, this is permited only if this is not a
15312                    // version downgrade or if the predecessor package is marked as debuggable and
15313                    // a downgrade is explicitly requested.
15314                    //
15315                    // On debuggable platform builds, downgrades are permitted even for
15316                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15317                    // not offer security guarantees and thus it's OK to disable some security
15318                    // mechanisms to make debugging/testing easier on those builds. However, even on
15319                    // debuggable builds downgrades of packages are permitted only if requested via
15320                    // installFlags. This is because we aim to keep the behavior of debuggable
15321                    // platform builds as close as possible to the behavior of non-debuggable
15322                    // platform builds.
15323                    final boolean downgradeRequested =
15324                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15325                    final boolean packageDebuggable =
15326                                (dataOwnerPkg.applicationInfo.flags
15327                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15328                    final boolean downgradePermitted =
15329                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15330                    if (!downgradePermitted) {
15331                        try {
15332                            checkDowngrade(dataOwnerPkg, pkgLite);
15333                        } catch (PackageManagerException e) {
15334                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15335                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15336                        }
15337                    }
15338                }
15339
15340                if (installedPkg != null) {
15341                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15342                        // Check for updated system application.
15343                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15344                            if (onSd) {
15345                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15346                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15347                            }
15348                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15349                        } else {
15350                            if (onSd) {
15351                                // Install flag overrides everything.
15352                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15353                            }
15354                            // If current upgrade specifies particular preference
15355                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15356                                // Application explicitly specified internal.
15357                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15358                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15359                                // App explictly prefers external. Let policy decide
15360                            } else {
15361                                // Prefer previous location
15362                                if (isExternal(installedPkg)) {
15363                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15364                                }
15365                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15366                            }
15367                        }
15368                    } else {
15369                        // Invalid install. Return error code
15370                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15371                    }
15372                }
15373            }
15374            // All the special cases have been taken care of.
15375            // Return result based on recommended install location.
15376            if (onSd) {
15377                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15378            }
15379            return pkgLite.recommendedInstallLocation;
15380        }
15381
15382        /*
15383         * Invoke remote method to get package information and install
15384         * location values. Override install location based on default
15385         * policy if needed and then create install arguments based
15386         * on the install location.
15387         */
15388        public void handleStartCopy() throws RemoteException {
15389            int ret = PackageManager.INSTALL_SUCCEEDED;
15390
15391            // If we're already staged, we've firmly committed to an install location
15392            if (origin.staged) {
15393                if (origin.file != null) {
15394                    installFlags |= PackageManager.INSTALL_INTERNAL;
15395                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15396                } else {
15397                    throw new IllegalStateException("Invalid stage location");
15398                }
15399            }
15400
15401            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15402            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15403            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15404            PackageInfoLite pkgLite = null;
15405
15406            if (onInt && onSd) {
15407                // Check if both bits are set.
15408                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15409                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15410            } else if (onSd && ephemeral) {
15411                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15412                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15413            } else {
15414                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15415                        packageAbiOverride);
15416
15417                if (DEBUG_INSTANT && ephemeral) {
15418                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15419                }
15420
15421                /*
15422                 * If we have too little free space, try to free cache
15423                 * before giving up.
15424                 */
15425                if (!origin.staged && pkgLite.recommendedInstallLocation
15426                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15427                    // TODO: focus freeing disk space on the target device
15428                    final StorageManager storage = StorageManager.from(mContext);
15429                    final long lowThreshold = storage.getStorageLowBytes(
15430                            Environment.getDataDirectory());
15431
15432                    final long sizeBytes = mContainerService.calculateInstalledSize(
15433                            origin.resolvedPath, packageAbiOverride);
15434
15435                    try {
15436                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15437                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15438                                installFlags, packageAbiOverride);
15439                    } catch (InstallerException e) {
15440                        Slog.w(TAG, "Failed to free cache", e);
15441                    }
15442
15443                    /*
15444                     * The cache free must have deleted the file we
15445                     * downloaded to install.
15446                     *
15447                     * TODO: fix the "freeCache" call to not delete
15448                     *       the file we care about.
15449                     */
15450                    if (pkgLite.recommendedInstallLocation
15451                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15452                        pkgLite.recommendedInstallLocation
15453                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15454                    }
15455                }
15456            }
15457
15458            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15459                int loc = pkgLite.recommendedInstallLocation;
15460                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15461                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15462                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15463                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15464                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15465                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15466                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15467                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15468                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15469                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15470                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15471                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15472                } else {
15473                    // Override with defaults if needed.
15474                    loc = installLocationPolicy(pkgLite);
15475                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15476                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15477                    } else if (!onSd && !onInt) {
15478                        // Override install location with flags
15479                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15480                            // Set the flag to install on external media.
15481                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15482                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15483                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15484                            if (DEBUG_INSTANT) {
15485                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15486                            }
15487                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15488                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15489                                    |PackageManager.INSTALL_INTERNAL);
15490                        } else {
15491                            // Make sure the flag for installing on external
15492                            // media is unset
15493                            installFlags |= PackageManager.INSTALL_INTERNAL;
15494                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15495                        }
15496                    }
15497                }
15498            }
15499
15500            final InstallArgs args = createInstallArgs(this);
15501            mArgs = args;
15502
15503            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15504                // TODO: http://b/22976637
15505                // Apps installed for "all" users use the device owner to verify the app
15506                UserHandle verifierUser = getUser();
15507                if (verifierUser == UserHandle.ALL) {
15508                    verifierUser = UserHandle.SYSTEM;
15509                }
15510
15511                /*
15512                 * Determine if we have any installed package verifiers. If we
15513                 * do, then we'll defer to them to verify the packages.
15514                 */
15515                final int requiredUid = mRequiredVerifierPackage == null ? -1
15516                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15517                                verifierUser.getIdentifier());
15518                final int installerUid =
15519                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15520                if (!origin.existing && requiredUid != -1
15521                        && isVerificationEnabled(
15522                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15523                    final Intent verification = new Intent(
15524                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15525                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15526                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15527                            PACKAGE_MIME_TYPE);
15528                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15529
15530                    // Query all live verifiers based on current user state
15531                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15532                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15533                            false /*allowDynamicSplits*/);
15534
15535                    if (DEBUG_VERIFY) {
15536                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15537                                + verification.toString() + " with " + pkgLite.verifiers.length
15538                                + " optional verifiers");
15539                    }
15540
15541                    final int verificationId = mPendingVerificationToken++;
15542
15543                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15544
15545                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15546                            installerPackageName);
15547
15548                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15549                            installFlags);
15550
15551                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15552                            pkgLite.packageName);
15553
15554                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15555                            pkgLite.versionCode);
15556
15557                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15558                            pkgLite.getLongVersionCode());
15559
15560                    if (verificationInfo != null) {
15561                        if (verificationInfo.originatingUri != null) {
15562                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15563                                    verificationInfo.originatingUri);
15564                        }
15565                        if (verificationInfo.referrer != null) {
15566                            verification.putExtra(Intent.EXTRA_REFERRER,
15567                                    verificationInfo.referrer);
15568                        }
15569                        if (verificationInfo.originatingUid >= 0) {
15570                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15571                                    verificationInfo.originatingUid);
15572                        }
15573                        if (verificationInfo.installerUid >= 0) {
15574                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15575                                    verificationInfo.installerUid);
15576                        }
15577                    }
15578
15579                    final PackageVerificationState verificationState = new PackageVerificationState(
15580                            requiredUid, args);
15581
15582                    mPendingVerification.append(verificationId, verificationState);
15583
15584                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15585                            receivers, verificationState);
15586
15587                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15588                    final long idleDuration = getVerificationTimeout();
15589
15590                    /*
15591                     * If any sufficient verifiers were listed in the package
15592                     * manifest, attempt to ask them.
15593                     */
15594                    if (sufficientVerifiers != null) {
15595                        final int N = sufficientVerifiers.size();
15596                        if (N == 0) {
15597                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15598                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15599                        } else {
15600                            for (int i = 0; i < N; i++) {
15601                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15602                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15603                                        verifierComponent.getPackageName(), idleDuration,
15604                                        verifierUser.getIdentifier(), false, "package verifier");
15605
15606                                final Intent sufficientIntent = new Intent(verification);
15607                                sufficientIntent.setComponent(verifierComponent);
15608                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15609                            }
15610                        }
15611                    }
15612
15613                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15614                            mRequiredVerifierPackage, receivers);
15615                    if (ret == PackageManager.INSTALL_SUCCEEDED
15616                            && mRequiredVerifierPackage != null) {
15617                        Trace.asyncTraceBegin(
15618                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15619                        /*
15620                         * Send the intent to the required verification agent,
15621                         * but only start the verification timeout after the
15622                         * target BroadcastReceivers have run.
15623                         */
15624                        verification.setComponent(requiredVerifierComponent);
15625                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15626                                mRequiredVerifierPackage, idleDuration,
15627                                verifierUser.getIdentifier(), false, "package verifier");
15628                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15629                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15630                                new BroadcastReceiver() {
15631                                    @Override
15632                                    public void onReceive(Context context, Intent intent) {
15633                                        final Message msg = mHandler
15634                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15635                                        msg.arg1 = verificationId;
15636                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15637                                    }
15638                                }, null, 0, null, null);
15639
15640                        /*
15641                         * We don't want the copy to proceed until verification
15642                         * succeeds, so null out this field.
15643                         */
15644                        mArgs = null;
15645                    }
15646                } else {
15647                    /*
15648                     * No package verification is enabled, so immediately start
15649                     * the remote call to initiate copy using temporary file.
15650                     */
15651                    ret = args.copyApk(mContainerService, true);
15652                }
15653            }
15654
15655            mRet = ret;
15656        }
15657
15658        @Override
15659        void handleReturnCode() {
15660            // If mArgs is null, then MCS couldn't be reached. When it
15661            // reconnects, it will try again to install. At that point, this
15662            // will succeed.
15663            if (mArgs != null) {
15664                processPendingInstall(mArgs, mRet);
15665            }
15666        }
15667
15668        @Override
15669        void handleServiceError() {
15670            mArgs = createInstallArgs(this);
15671            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15672        }
15673    }
15674
15675    private InstallArgs createInstallArgs(InstallParams params) {
15676        if (params.move != null) {
15677            return new MoveInstallArgs(params);
15678        } else {
15679            return new FileInstallArgs(params);
15680        }
15681    }
15682
15683    /**
15684     * Create args that describe an existing installed package. Typically used
15685     * when cleaning up old installs, or used as a move source.
15686     */
15687    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15688            String resourcePath, String[] instructionSets) {
15689        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15690    }
15691
15692    static abstract class InstallArgs {
15693        /** @see InstallParams#origin */
15694        final OriginInfo origin;
15695        /** @see InstallParams#move */
15696        final MoveInfo move;
15697
15698        final IPackageInstallObserver2 observer;
15699        // Always refers to PackageManager flags only
15700        final int installFlags;
15701        final String installerPackageName;
15702        final String volumeUuid;
15703        final UserHandle user;
15704        final String abiOverride;
15705        final String[] installGrantPermissions;
15706        /** If non-null, drop an async trace when the install completes */
15707        final String traceMethod;
15708        final int traceCookie;
15709        final PackageParser.SigningDetails signingDetails;
15710        final int installReason;
15711
15712        // The list of instruction sets supported by this app. This is currently
15713        // only used during the rmdex() phase to clean up resources. We can get rid of this
15714        // if we move dex files under the common app path.
15715        /* nullable */ String[] instructionSets;
15716
15717        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15718                int installFlags, String installerPackageName, String volumeUuid,
15719                UserHandle user, String[] instructionSets,
15720                String abiOverride, String[] installGrantPermissions,
15721                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15722                int installReason) {
15723            this.origin = origin;
15724            this.move = move;
15725            this.installFlags = installFlags;
15726            this.observer = observer;
15727            this.installerPackageName = installerPackageName;
15728            this.volumeUuid = volumeUuid;
15729            this.user = user;
15730            this.instructionSets = instructionSets;
15731            this.abiOverride = abiOverride;
15732            this.installGrantPermissions = installGrantPermissions;
15733            this.traceMethod = traceMethod;
15734            this.traceCookie = traceCookie;
15735            this.signingDetails = signingDetails;
15736            this.installReason = installReason;
15737        }
15738
15739        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15740        abstract int doPreInstall(int status);
15741
15742        /**
15743         * Rename package into final resting place. All paths on the given
15744         * scanned package should be updated to reflect the rename.
15745         */
15746        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15747        abstract int doPostInstall(int status, int uid);
15748
15749        /** @see PackageSettingBase#codePathString */
15750        abstract String getCodePath();
15751        /** @see PackageSettingBase#resourcePathString */
15752        abstract String getResourcePath();
15753
15754        // Need installer lock especially for dex file removal.
15755        abstract void cleanUpResourcesLI();
15756        abstract boolean doPostDeleteLI(boolean delete);
15757
15758        /**
15759         * Called before the source arguments are copied. This is used mostly
15760         * for MoveParams when it needs to read the source file to put it in the
15761         * destination.
15762         */
15763        int doPreCopy() {
15764            return PackageManager.INSTALL_SUCCEEDED;
15765        }
15766
15767        /**
15768         * Called after the source arguments are copied. This is used mostly for
15769         * MoveParams when it needs to read the source file to put it in the
15770         * destination.
15771         */
15772        int doPostCopy(int uid) {
15773            return PackageManager.INSTALL_SUCCEEDED;
15774        }
15775
15776        protected boolean isFwdLocked() {
15777            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15778        }
15779
15780        protected boolean isExternalAsec() {
15781            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15782        }
15783
15784        protected boolean isEphemeral() {
15785            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15786        }
15787
15788        UserHandle getUser() {
15789            return user;
15790        }
15791    }
15792
15793    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15794        if (!allCodePaths.isEmpty()) {
15795            if (instructionSets == null) {
15796                throw new IllegalStateException("instructionSet == null");
15797            }
15798            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15799            for (String codePath : allCodePaths) {
15800                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15801                    try {
15802                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15803                    } catch (InstallerException ignored) {
15804                    }
15805                }
15806            }
15807        }
15808    }
15809
15810    /**
15811     * Logic to handle installation of non-ASEC applications, including copying
15812     * and renaming logic.
15813     */
15814    class FileInstallArgs extends InstallArgs {
15815        private File codeFile;
15816        private File resourceFile;
15817
15818        // Example topology:
15819        // /data/app/com.example/base.apk
15820        // /data/app/com.example/split_foo.apk
15821        // /data/app/com.example/lib/arm/libfoo.so
15822        // /data/app/com.example/lib/arm64/libfoo.so
15823        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15824
15825        /** New install */
15826        FileInstallArgs(InstallParams params) {
15827            super(params.origin, params.move, params.observer, params.installFlags,
15828                    params.installerPackageName, params.volumeUuid,
15829                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15830                    params.grantedRuntimePermissions,
15831                    params.traceMethod, params.traceCookie, params.signingDetails,
15832                    params.installReason);
15833            if (isFwdLocked()) {
15834                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15835            }
15836        }
15837
15838        /** Existing install */
15839        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15840            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15841                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15842                    PackageManager.INSTALL_REASON_UNKNOWN);
15843            this.codeFile = (codePath != null) ? new File(codePath) : null;
15844            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15845        }
15846
15847        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15848            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15849            try {
15850                return doCopyApk(imcs, temp);
15851            } finally {
15852                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15853            }
15854        }
15855
15856        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15857            if (origin.staged) {
15858                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15859                codeFile = origin.file;
15860                resourceFile = origin.file;
15861                return PackageManager.INSTALL_SUCCEEDED;
15862            }
15863
15864            try {
15865                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15866                final File tempDir =
15867                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15868                codeFile = tempDir;
15869                resourceFile = tempDir;
15870            } catch (IOException e) {
15871                Slog.w(TAG, "Failed to create copy file: " + e);
15872                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15873            }
15874
15875            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15876                @Override
15877                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15878                    if (!FileUtils.isValidExtFilename(name)) {
15879                        throw new IllegalArgumentException("Invalid filename: " + name);
15880                    }
15881                    try {
15882                        final File file = new File(codeFile, name);
15883                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15884                                O_RDWR | O_CREAT, 0644);
15885                        Os.chmod(file.getAbsolutePath(), 0644);
15886                        return new ParcelFileDescriptor(fd);
15887                    } catch (ErrnoException e) {
15888                        throw new RemoteException("Failed to open: " + e.getMessage());
15889                    }
15890                }
15891            };
15892
15893            int ret = PackageManager.INSTALL_SUCCEEDED;
15894            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15895            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15896                Slog.e(TAG, "Failed to copy package");
15897                return ret;
15898            }
15899
15900            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15901            NativeLibraryHelper.Handle handle = null;
15902            try {
15903                handle = NativeLibraryHelper.Handle.create(codeFile);
15904                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15905                        abiOverride);
15906            } catch (IOException e) {
15907                Slog.e(TAG, "Copying native libraries failed", e);
15908                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15909            } finally {
15910                IoUtils.closeQuietly(handle);
15911            }
15912
15913            return ret;
15914        }
15915
15916        int doPreInstall(int status) {
15917            if (status != PackageManager.INSTALL_SUCCEEDED) {
15918                cleanUp();
15919            }
15920            return status;
15921        }
15922
15923        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15924            if (status != PackageManager.INSTALL_SUCCEEDED) {
15925                cleanUp();
15926                return false;
15927            }
15928
15929            final File targetDir = codeFile.getParentFile();
15930            final File beforeCodeFile = codeFile;
15931            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15932
15933            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15934            try {
15935                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15936            } catch (ErrnoException e) {
15937                Slog.w(TAG, "Failed to rename", e);
15938                return false;
15939            }
15940
15941            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15942                Slog.w(TAG, "Failed to restorecon");
15943                return false;
15944            }
15945
15946            // Reflect the rename internally
15947            codeFile = afterCodeFile;
15948            resourceFile = afterCodeFile;
15949
15950            // Reflect the rename in scanned details
15951            try {
15952                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15953            } catch (IOException e) {
15954                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15955                return false;
15956            }
15957            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15958                    afterCodeFile, pkg.baseCodePath));
15959            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15960                    afterCodeFile, pkg.splitCodePaths));
15961
15962            // Reflect the rename in app info
15963            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15964            pkg.setApplicationInfoCodePath(pkg.codePath);
15965            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15966            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15967            pkg.setApplicationInfoResourcePath(pkg.codePath);
15968            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15969            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15970
15971            return true;
15972        }
15973
15974        int doPostInstall(int status, int uid) {
15975            if (status != PackageManager.INSTALL_SUCCEEDED) {
15976                cleanUp();
15977            }
15978            return status;
15979        }
15980
15981        @Override
15982        String getCodePath() {
15983            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15984        }
15985
15986        @Override
15987        String getResourcePath() {
15988            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15989        }
15990
15991        private boolean cleanUp() {
15992            if (codeFile == null || !codeFile.exists()) {
15993                return false;
15994            }
15995
15996            removeCodePathLI(codeFile);
15997
15998            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15999                resourceFile.delete();
16000            }
16001
16002            return true;
16003        }
16004
16005        void cleanUpResourcesLI() {
16006            // Try enumerating all code paths before deleting
16007            List<String> allCodePaths = Collections.EMPTY_LIST;
16008            if (codeFile != null && codeFile.exists()) {
16009                try {
16010                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16011                    allCodePaths = pkg.getAllCodePaths();
16012                } catch (PackageParserException e) {
16013                    // Ignored; we tried our best
16014                }
16015            }
16016
16017            cleanUp();
16018            removeDexFiles(allCodePaths, instructionSets);
16019        }
16020
16021        boolean doPostDeleteLI(boolean delete) {
16022            // XXX err, shouldn't we respect the delete flag?
16023            cleanUpResourcesLI();
16024            return true;
16025        }
16026    }
16027
16028    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16029            PackageManagerException {
16030        if (copyRet < 0) {
16031            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16032                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16033                throw new PackageManagerException(copyRet, message);
16034            }
16035        }
16036    }
16037
16038    /**
16039     * Extract the StorageManagerService "container ID" from the full code path of an
16040     * .apk.
16041     */
16042    static String cidFromCodePath(String fullCodePath) {
16043        int eidx = fullCodePath.lastIndexOf("/");
16044        String subStr1 = fullCodePath.substring(0, eidx);
16045        int sidx = subStr1.lastIndexOf("/");
16046        return subStr1.substring(sidx+1, eidx);
16047    }
16048
16049    /**
16050     * Logic to handle movement of existing installed applications.
16051     */
16052    class MoveInstallArgs extends InstallArgs {
16053        private File codeFile;
16054        private File resourceFile;
16055
16056        /** New install */
16057        MoveInstallArgs(InstallParams params) {
16058            super(params.origin, params.move, params.observer, params.installFlags,
16059                    params.installerPackageName, params.volumeUuid,
16060                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16061                    params.grantedRuntimePermissions,
16062                    params.traceMethod, params.traceCookie, params.signingDetails,
16063                    params.installReason);
16064        }
16065
16066        int copyApk(IMediaContainerService imcs, boolean temp) {
16067            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16068                    + move.fromUuid + " to " + move.toUuid);
16069            synchronized (mInstaller) {
16070                try {
16071                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16072                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16073                } catch (InstallerException e) {
16074                    Slog.w(TAG, "Failed to move app", e);
16075                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16076                }
16077            }
16078
16079            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16080            resourceFile = codeFile;
16081            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16082
16083            return PackageManager.INSTALL_SUCCEEDED;
16084        }
16085
16086        int doPreInstall(int status) {
16087            if (status != PackageManager.INSTALL_SUCCEEDED) {
16088                cleanUp(move.toUuid);
16089            }
16090            return status;
16091        }
16092
16093        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16094            if (status != PackageManager.INSTALL_SUCCEEDED) {
16095                cleanUp(move.toUuid);
16096                return false;
16097            }
16098
16099            // Reflect the move in app info
16100            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16101            pkg.setApplicationInfoCodePath(pkg.codePath);
16102            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16103            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16104            pkg.setApplicationInfoResourcePath(pkg.codePath);
16105            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16106            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16107
16108            return true;
16109        }
16110
16111        int doPostInstall(int status, int uid) {
16112            if (status == PackageManager.INSTALL_SUCCEEDED) {
16113                cleanUp(move.fromUuid);
16114            } else {
16115                cleanUp(move.toUuid);
16116            }
16117            return status;
16118        }
16119
16120        @Override
16121        String getCodePath() {
16122            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16123        }
16124
16125        @Override
16126        String getResourcePath() {
16127            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16128        }
16129
16130        private boolean cleanUp(String volumeUuid) {
16131            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16132                    move.dataAppName);
16133            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16134            final int[] userIds = sUserManager.getUserIds();
16135            synchronized (mInstallLock) {
16136                // Clean up both app data and code
16137                // All package moves are frozen until finished
16138                for (int userId : userIds) {
16139                    try {
16140                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16141                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16142                    } catch (InstallerException e) {
16143                        Slog.w(TAG, String.valueOf(e));
16144                    }
16145                }
16146                removeCodePathLI(codeFile);
16147            }
16148            return true;
16149        }
16150
16151        void cleanUpResourcesLI() {
16152            throw new UnsupportedOperationException();
16153        }
16154
16155        boolean doPostDeleteLI(boolean delete) {
16156            throw new UnsupportedOperationException();
16157        }
16158    }
16159
16160    static String getAsecPackageName(String packageCid) {
16161        int idx = packageCid.lastIndexOf("-");
16162        if (idx == -1) {
16163            return packageCid;
16164        }
16165        return packageCid.substring(0, idx);
16166    }
16167
16168    // Utility method used to create code paths based on package name and available index.
16169    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16170        String idxStr = "";
16171        int idx = 1;
16172        // Fall back to default value of idx=1 if prefix is not
16173        // part of oldCodePath
16174        if (oldCodePath != null) {
16175            String subStr = oldCodePath;
16176            // Drop the suffix right away
16177            if (suffix != null && subStr.endsWith(suffix)) {
16178                subStr = subStr.substring(0, subStr.length() - suffix.length());
16179            }
16180            // If oldCodePath already contains prefix find out the
16181            // ending index to either increment or decrement.
16182            int sidx = subStr.lastIndexOf(prefix);
16183            if (sidx != -1) {
16184                subStr = subStr.substring(sidx + prefix.length());
16185                if (subStr != null) {
16186                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16187                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16188                    }
16189                    try {
16190                        idx = Integer.parseInt(subStr);
16191                        if (idx <= 1) {
16192                            idx++;
16193                        } else {
16194                            idx--;
16195                        }
16196                    } catch(NumberFormatException e) {
16197                    }
16198                }
16199            }
16200        }
16201        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16202        return prefix + idxStr;
16203    }
16204
16205    private File getNextCodePath(File targetDir, String packageName) {
16206        File result;
16207        SecureRandom random = new SecureRandom();
16208        byte[] bytes = new byte[16];
16209        do {
16210            random.nextBytes(bytes);
16211            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16212            result = new File(targetDir, packageName + "-" + suffix);
16213        } while (result.exists());
16214        return result;
16215    }
16216
16217    // Utility method that returns the relative package path with respect
16218    // to the installation directory. Like say for /data/data/com.test-1.apk
16219    // string com.test-1 is returned.
16220    static String deriveCodePathName(String codePath) {
16221        if (codePath == null) {
16222            return null;
16223        }
16224        final File codeFile = new File(codePath);
16225        final String name = codeFile.getName();
16226        if (codeFile.isDirectory()) {
16227            return name;
16228        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16229            final int lastDot = name.lastIndexOf('.');
16230            return name.substring(0, lastDot);
16231        } else {
16232            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16233            return null;
16234        }
16235    }
16236
16237    static class PackageInstalledInfo {
16238        String name;
16239        int uid;
16240        // The set of users that originally had this package installed.
16241        int[] origUsers;
16242        // The set of users that now have this package installed.
16243        int[] newUsers;
16244        PackageParser.Package pkg;
16245        int returnCode;
16246        String returnMsg;
16247        String installerPackageName;
16248        PackageRemovedInfo removedInfo;
16249        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16250
16251        public void setError(int code, String msg) {
16252            setReturnCode(code);
16253            setReturnMessage(msg);
16254            Slog.w(TAG, msg);
16255        }
16256
16257        public void setError(String msg, PackageParserException e) {
16258            setReturnCode(e.error);
16259            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16260            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16261            for (int i = 0; i < childCount; i++) {
16262                addedChildPackages.valueAt(i).setError(msg, e);
16263            }
16264            Slog.w(TAG, msg, e);
16265        }
16266
16267        public void setError(String msg, PackageManagerException e) {
16268            returnCode = e.error;
16269            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16270            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16271            for (int i = 0; i < childCount; i++) {
16272                addedChildPackages.valueAt(i).setError(msg, e);
16273            }
16274            Slog.w(TAG, msg, e);
16275        }
16276
16277        public void setReturnCode(int returnCode) {
16278            this.returnCode = returnCode;
16279            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16280            for (int i = 0; i < childCount; i++) {
16281                addedChildPackages.valueAt(i).returnCode = returnCode;
16282            }
16283        }
16284
16285        private void setReturnMessage(String returnMsg) {
16286            this.returnMsg = returnMsg;
16287            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16288            for (int i = 0; i < childCount; i++) {
16289                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16290            }
16291        }
16292
16293        // In some error cases we want to convey more info back to the observer
16294        String origPackage;
16295        String origPermission;
16296    }
16297
16298    /*
16299     * Install a non-existing package.
16300     */
16301    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16302            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16303            String volumeUuid, PackageInstalledInfo res, int installReason) {
16304        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16305
16306        // Remember this for later, in case we need to rollback this install
16307        String pkgName = pkg.packageName;
16308
16309        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16310
16311        synchronized(mPackages) {
16312            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16313            if (renamedPackage != null) {
16314                // A package with the same name is already installed, though
16315                // it has been renamed to an older name.  The package we
16316                // are trying to install should be installed as an update to
16317                // the existing one, but that has not been requested, so bail.
16318                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16319                        + " without first uninstalling package running as "
16320                        + renamedPackage);
16321                return;
16322            }
16323            if (mPackages.containsKey(pkgName)) {
16324                // Don't allow installation over an existing package with the same name.
16325                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16326                        + " without first uninstalling.");
16327                return;
16328            }
16329        }
16330
16331        try {
16332            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
16333                    System.currentTimeMillis(), user);
16334
16335            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16336
16337            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16338                prepareAppDataAfterInstallLIF(newPackage);
16339
16340            } else {
16341                // Remove package from internal structures, but keep around any
16342                // data that might have already existed
16343                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16344                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16345            }
16346        } catch (PackageManagerException e) {
16347            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16348        }
16349
16350        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16351    }
16352
16353    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16354        try (DigestInputStream digestStream =
16355                new DigestInputStream(new FileInputStream(file), digest)) {
16356            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16357        }
16358    }
16359
16360    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16361            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16362            PackageInstalledInfo res, int installReason) {
16363        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16364
16365        final PackageParser.Package oldPackage;
16366        final PackageSetting ps;
16367        final String pkgName = pkg.packageName;
16368        final int[] allUsers;
16369        final int[] installedUsers;
16370
16371        synchronized(mPackages) {
16372            oldPackage = mPackages.get(pkgName);
16373            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16374
16375            // don't allow upgrade to target a release SDK from a pre-release SDK
16376            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16377                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16378            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16379                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16380            if (oldTargetsPreRelease
16381                    && !newTargetsPreRelease
16382                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16383                Slog.w(TAG, "Can't install package targeting released sdk");
16384                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16385                return;
16386            }
16387
16388            ps = mSettings.mPackages.get(pkgName);
16389
16390            // verify signatures are valid
16391            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16392            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16393                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16394                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16395                            "New package not signed by keys specified by upgrade-keysets: "
16396                                    + pkgName);
16397                    return;
16398                }
16399            } else {
16400
16401                // default to original signature matching
16402                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16403                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
16404                                && !oldPackage.mSigningDetails.checkCapability(
16405                                        pkg.mSigningDetails,
16406                                        PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
16407                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16408                            "New package has a different signature: " + pkgName);
16409                    return;
16410                }
16411            }
16412
16413            // don't allow a system upgrade unless the upgrade hash matches
16414            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16415                byte[] digestBytes = null;
16416                try {
16417                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16418                    updateDigest(digest, new File(pkg.baseCodePath));
16419                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16420                        for (String path : pkg.splitCodePaths) {
16421                            updateDigest(digest, new File(path));
16422                        }
16423                    }
16424                    digestBytes = digest.digest();
16425                } catch (NoSuchAlgorithmException | IOException e) {
16426                    res.setError(INSTALL_FAILED_INVALID_APK,
16427                            "Could not compute hash: " + pkgName);
16428                    return;
16429                }
16430                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16431                    res.setError(INSTALL_FAILED_INVALID_APK,
16432                            "New package fails restrict-update check: " + pkgName);
16433                    return;
16434                }
16435                // retain upgrade restriction
16436                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16437            }
16438
16439            // Check for shared user id changes
16440            String invalidPackageName =
16441                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16442            if (invalidPackageName != null) {
16443                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16444                        "Package " + invalidPackageName + " tried to change user "
16445                                + oldPackage.mSharedUserId);
16446                return;
16447            }
16448
16449            // check if the new package supports all of the abis which the old package supports
16450            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16451            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16452            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16453                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16454                        "Update to package " + pkgName + " doesn't support multi arch");
16455                return;
16456            }
16457
16458            // In case of rollback, remember per-user/profile install state
16459            allUsers = sUserManager.getUserIds();
16460            installedUsers = ps.queryInstalledUsers(allUsers, true);
16461
16462            // don't allow an upgrade from full to ephemeral
16463            if (isInstantApp) {
16464                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16465                    for (int currentUser : allUsers) {
16466                        if (!ps.getInstantApp(currentUser)) {
16467                            // can't downgrade from full to instant
16468                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16469                                    + " for user: " + currentUser);
16470                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16471                            return;
16472                        }
16473                    }
16474                } else if (!ps.getInstantApp(user.getIdentifier())) {
16475                    // can't downgrade from full to instant
16476                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16477                            + " for user: " + user.getIdentifier());
16478                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16479                    return;
16480                }
16481            }
16482        }
16483
16484        // Update what is removed
16485        res.removedInfo = new PackageRemovedInfo(this);
16486        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16487        res.removedInfo.removedPackage = oldPackage.packageName;
16488        res.removedInfo.installerPackageName = ps.installerPackageName;
16489        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16490        res.removedInfo.isUpdate = true;
16491        res.removedInfo.origUsers = installedUsers;
16492        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16493        for (int i = 0; i < installedUsers.length; i++) {
16494            final int userId = installedUsers[i];
16495            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16496        }
16497
16498        final int childCount = (oldPackage.childPackages != null)
16499                ? oldPackage.childPackages.size() : 0;
16500        for (int i = 0; i < childCount; i++) {
16501            boolean childPackageUpdated = false;
16502            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16503            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16504            if (res.addedChildPackages != null) {
16505                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16506                if (childRes != null) {
16507                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16508                    childRes.removedInfo.removedPackage = childPkg.packageName;
16509                    if (childPs != null) {
16510                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16511                    }
16512                    childRes.removedInfo.isUpdate = true;
16513                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16514                    childPackageUpdated = true;
16515                }
16516            }
16517            if (!childPackageUpdated) {
16518                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16519                childRemovedRes.removedPackage = childPkg.packageName;
16520                if (childPs != null) {
16521                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16522                }
16523                childRemovedRes.isUpdate = false;
16524                childRemovedRes.dataRemoved = true;
16525                synchronized (mPackages) {
16526                    if (childPs != null) {
16527                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16528                    }
16529                }
16530                if (res.removedInfo.removedChildPackages == null) {
16531                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16532                }
16533                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16534            }
16535        }
16536
16537        boolean sysPkg = (isSystemApp(oldPackage));
16538        if (sysPkg) {
16539            // Set the system/privileged/oem/vendor/product flags as needed
16540            final boolean privileged =
16541                    (oldPackage.applicationInfo.privateFlags
16542                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16543            final boolean oem =
16544                    (oldPackage.applicationInfo.privateFlags
16545                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16546            final boolean vendor =
16547                    (oldPackage.applicationInfo.privateFlags
16548                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16549            final boolean product =
16550                    (oldPackage.applicationInfo.privateFlags
16551                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16552            final @ParseFlags int systemParseFlags = parseFlags;
16553            final @ScanFlags int systemScanFlags = scanFlags
16554                    | SCAN_AS_SYSTEM
16555                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16556                    | (oem ? SCAN_AS_OEM : 0)
16557                    | (vendor ? SCAN_AS_VENDOR : 0)
16558                    | (product ? SCAN_AS_PRODUCT : 0);
16559
16560            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16561                    user, allUsers, installerPackageName, res, installReason);
16562        } else {
16563            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16564                    user, allUsers, installerPackageName, res, installReason);
16565        }
16566    }
16567
16568    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16569            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16570            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16571            String installerPackageName, PackageInstalledInfo res, int installReason) {
16572        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16573                + deletedPackage);
16574
16575        String pkgName = deletedPackage.packageName;
16576        boolean deletedPkg = true;
16577        boolean addedPkg = false;
16578        boolean updatedSettings = false;
16579        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16580        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16581                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16582
16583        final long origUpdateTime = (pkg.mExtras != null)
16584                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16585
16586        // First delete the existing package while retaining the data directory
16587        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16588                res.removedInfo, true, pkg)) {
16589            // If the existing package wasn't successfully deleted
16590            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16591            deletedPkg = false;
16592        } else {
16593            // Successfully deleted the old package; proceed with replace.
16594
16595            // If deleted package lived in a container, give users a chance to
16596            // relinquish resources before killing.
16597            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16598                if (DEBUG_INSTALL) {
16599                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16600                }
16601                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16602                final ArrayList<String> pkgList = new ArrayList<String>(1);
16603                pkgList.add(deletedPackage.applicationInfo.packageName);
16604                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16605            }
16606
16607            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16608                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16609
16610            try {
16611                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16612                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16613                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16614                        installReason);
16615
16616                // Update the in-memory copy of the previous code paths.
16617                PackageSetting ps = mSettings.mPackages.get(pkgName);
16618                if (!killApp) {
16619                    if (ps.oldCodePaths == null) {
16620                        ps.oldCodePaths = new ArraySet<>();
16621                    }
16622                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16623                    if (deletedPackage.splitCodePaths != null) {
16624                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16625                    }
16626                } else {
16627                    ps.oldCodePaths = null;
16628                }
16629                if (ps.childPackageNames != null) {
16630                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16631                        final String childPkgName = ps.childPackageNames.get(i);
16632                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16633                        childPs.oldCodePaths = ps.oldCodePaths;
16634                    }
16635                }
16636                prepareAppDataAfterInstallLIF(newPackage);
16637                addedPkg = true;
16638                mDexManager.notifyPackageUpdated(newPackage.packageName,
16639                        newPackage.baseCodePath, newPackage.splitCodePaths);
16640            } catch (PackageManagerException e) {
16641                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16642            }
16643        }
16644
16645        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16646            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16647
16648            // Revert all internal state mutations and added folders for the failed install
16649            if (addedPkg) {
16650                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16651                        res.removedInfo, true, null);
16652            }
16653
16654            // Restore the old package
16655            if (deletedPkg) {
16656                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16657                File restoreFile = new File(deletedPackage.codePath);
16658                // Parse old package
16659                boolean oldExternal = isExternal(deletedPackage);
16660                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16661                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16662                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16663                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16664                try {
16665                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16666                            null);
16667                } catch (PackageManagerException e) {
16668                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16669                            + e.getMessage());
16670                    return;
16671                }
16672
16673                synchronized (mPackages) {
16674                    // Ensure the installer package name up to date
16675                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16676
16677                    // Update permissions for restored package
16678                    mPermissionManager.updatePermissions(
16679                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16680                            mPermissionCallback);
16681
16682                    mSettings.writeLPr();
16683                }
16684
16685                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16686            }
16687        } else {
16688            synchronized (mPackages) {
16689                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16690                if (ps != null) {
16691                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16692                    if (res.removedInfo.removedChildPackages != null) {
16693                        final int childCount = res.removedInfo.removedChildPackages.size();
16694                        // Iterate in reverse as we may modify the collection
16695                        for (int i = childCount - 1; i >= 0; i--) {
16696                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16697                            if (res.addedChildPackages.containsKey(childPackageName)) {
16698                                res.removedInfo.removedChildPackages.removeAt(i);
16699                            } else {
16700                                PackageRemovedInfo childInfo = res.removedInfo
16701                                        .removedChildPackages.valueAt(i);
16702                                childInfo.removedForAllUsers = mPackages.get(
16703                                        childInfo.removedPackage) == null;
16704                            }
16705                        }
16706                    }
16707                }
16708            }
16709        }
16710    }
16711
16712    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16713            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16714            final @ScanFlags int scanFlags, UserHandle user,
16715            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16716            int installReason) {
16717        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16718                + ", old=" + deletedPackage);
16719
16720        final boolean disabledSystem;
16721
16722        // Remove existing system package
16723        removePackageLI(deletedPackage, true);
16724
16725        synchronized (mPackages) {
16726            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16727        }
16728        if (!disabledSystem) {
16729            // We didn't need to disable the .apk as a current system package,
16730            // which means we are replacing another update that is already
16731            // installed.  We need to make sure to delete the older one's .apk.
16732            res.removedInfo.args = createInstallArgsForExisting(0,
16733                    deletedPackage.applicationInfo.getCodePath(),
16734                    deletedPackage.applicationInfo.getResourcePath(),
16735                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16736        } else {
16737            res.removedInfo.args = null;
16738        }
16739
16740        // Successfully disabled the old package. Now proceed with re-installation
16741        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16742                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16743
16744        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16745        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16746                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16747
16748        PackageParser.Package newPackage = null;
16749        try {
16750            // Add the package to the internal data structures
16751            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16752
16753            // Set the update and install times
16754            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16755            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16756                    System.currentTimeMillis());
16757
16758            // Update the package dynamic state if succeeded
16759            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16760                // Now that the install succeeded make sure we remove data
16761                // directories for any child package the update removed.
16762                final int deletedChildCount = (deletedPackage.childPackages != null)
16763                        ? deletedPackage.childPackages.size() : 0;
16764                final int newChildCount = (newPackage.childPackages != null)
16765                        ? newPackage.childPackages.size() : 0;
16766                for (int i = 0; i < deletedChildCount; i++) {
16767                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16768                    boolean childPackageDeleted = true;
16769                    for (int j = 0; j < newChildCount; j++) {
16770                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16771                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16772                            childPackageDeleted = false;
16773                            break;
16774                        }
16775                    }
16776                    if (childPackageDeleted) {
16777                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16778                                deletedChildPkg.packageName);
16779                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16780                            PackageRemovedInfo removedChildRes = res.removedInfo
16781                                    .removedChildPackages.get(deletedChildPkg.packageName);
16782                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16783                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16784                        }
16785                    }
16786                }
16787
16788                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16789                        installReason);
16790                prepareAppDataAfterInstallLIF(newPackage);
16791
16792                mDexManager.notifyPackageUpdated(newPackage.packageName,
16793                            newPackage.baseCodePath, newPackage.splitCodePaths);
16794            }
16795        } catch (PackageManagerException e) {
16796            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16797            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16798        }
16799
16800        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16801            // Re installation failed. Restore old information
16802            // Remove new pkg information
16803            if (newPackage != null) {
16804                removeInstalledPackageLI(newPackage, true);
16805            }
16806            // Add back the old system package
16807            try {
16808                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16809            } catch (PackageManagerException e) {
16810                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16811            }
16812
16813            synchronized (mPackages) {
16814                if (disabledSystem) {
16815                    enableSystemPackageLPw(deletedPackage);
16816                }
16817
16818                // Ensure the installer package name up to date
16819                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16820
16821                // Update permissions for restored package
16822                mPermissionManager.updatePermissions(
16823                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16824                        mPermissionCallback);
16825
16826                mSettings.writeLPr();
16827            }
16828
16829            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16830                    + " after failed upgrade");
16831        }
16832    }
16833
16834    /**
16835     * Checks whether the parent or any of the child packages have a change shared
16836     * user. For a package to be a valid update the shred users of the parent and
16837     * the children should match. We may later support changing child shared users.
16838     * @param oldPkg The updated package.
16839     * @param newPkg The update package.
16840     * @return The shared user that change between the versions.
16841     */
16842    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16843            PackageParser.Package newPkg) {
16844        // Check parent shared user
16845        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16846            return newPkg.packageName;
16847        }
16848        // Check child shared users
16849        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16850        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16851        for (int i = 0; i < newChildCount; i++) {
16852            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16853            // If this child was present, did it have the same shared user?
16854            for (int j = 0; j < oldChildCount; j++) {
16855                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16856                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16857                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16858                    return newChildPkg.packageName;
16859                }
16860            }
16861        }
16862        return null;
16863    }
16864
16865    private void removeNativeBinariesLI(PackageSetting ps) {
16866        // Remove the lib path for the parent package
16867        if (ps != null) {
16868            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16869            // Remove the lib path for the child packages
16870            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16871            for (int i = 0; i < childCount; i++) {
16872                PackageSetting childPs = null;
16873                synchronized (mPackages) {
16874                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16875                }
16876                if (childPs != null) {
16877                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16878                            .legacyNativeLibraryPathString);
16879                }
16880            }
16881        }
16882    }
16883
16884    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16885        // Enable the parent package
16886        mSettings.enableSystemPackageLPw(pkg.packageName);
16887        // Enable the child packages
16888        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16889        for (int i = 0; i < childCount; i++) {
16890            PackageParser.Package childPkg = pkg.childPackages.get(i);
16891            mSettings.enableSystemPackageLPw(childPkg.packageName);
16892        }
16893    }
16894
16895    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16896            PackageParser.Package newPkg) {
16897        // Disable the parent package (parent always replaced)
16898        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16899        // Disable the child packages
16900        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16901        for (int i = 0; i < childCount; i++) {
16902            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16903            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16904            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16905        }
16906        return disabled;
16907    }
16908
16909    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16910            String installerPackageName) {
16911        // Enable the parent package
16912        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16913        // Enable the child packages
16914        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16915        for (int i = 0; i < childCount; i++) {
16916            PackageParser.Package childPkg = pkg.childPackages.get(i);
16917            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16918        }
16919    }
16920
16921    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16922            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16923        // Update the parent package setting
16924        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16925                res, user, installReason);
16926        // Update the child packages setting
16927        final int childCount = (newPackage.childPackages != null)
16928                ? newPackage.childPackages.size() : 0;
16929        for (int i = 0; i < childCount; i++) {
16930            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16931            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16932            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16933                    childRes.origUsers, childRes, user, installReason);
16934        }
16935    }
16936
16937    private void updateSettingsInternalLI(PackageParser.Package pkg,
16938            String installerPackageName, int[] allUsers, int[] installedForUsers,
16939            PackageInstalledInfo res, UserHandle user, int installReason) {
16940        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16941
16942        final String pkgName = pkg.packageName;
16943
16944        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16945        synchronized (mPackages) {
16946// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16947            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16948                    mPermissionCallback);
16949            // For system-bundled packages, we assume that installing an upgraded version
16950            // of the package implies that the user actually wants to run that new code,
16951            // so we enable the package.
16952            PackageSetting ps = mSettings.mPackages.get(pkgName);
16953            final int userId = user.getIdentifier();
16954            if (ps != null) {
16955                if (isSystemApp(pkg)) {
16956                    if (DEBUG_INSTALL) {
16957                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16958                    }
16959                    // Enable system package for requested users
16960                    if (res.origUsers != null) {
16961                        for (int origUserId : res.origUsers) {
16962                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16963                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16964                                        origUserId, installerPackageName);
16965                            }
16966                        }
16967                    }
16968                    // Also convey the prior install/uninstall state
16969                    if (allUsers != null && installedForUsers != null) {
16970                        for (int currentUserId : allUsers) {
16971                            final boolean installed = ArrayUtils.contains(
16972                                    installedForUsers, currentUserId);
16973                            if (DEBUG_INSTALL) {
16974                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16975                            }
16976                            ps.setInstalled(installed, currentUserId);
16977                        }
16978                        // these install state changes will be persisted in the
16979                        // upcoming call to mSettings.writeLPr().
16980                    }
16981                }
16982                // It's implied that when a user requests installation, they want the app to be
16983                // installed and enabled.
16984                if (userId != UserHandle.USER_ALL) {
16985                    ps.setInstalled(true, userId);
16986                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16987                }
16988
16989                // When replacing an existing package, preserve the original install reason for all
16990                // users that had the package installed before.
16991                final Set<Integer> previousUserIds = new ArraySet<>();
16992                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16993                    final int installReasonCount = res.removedInfo.installReasons.size();
16994                    for (int i = 0; i < installReasonCount; i++) {
16995                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16996                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16997                        ps.setInstallReason(previousInstallReason, previousUserId);
16998                        previousUserIds.add(previousUserId);
16999                    }
17000                }
17001
17002                // Set install reason for users that are having the package newly installed.
17003                if (userId == UserHandle.USER_ALL) {
17004                    for (int currentUserId : sUserManager.getUserIds()) {
17005                        if (!previousUserIds.contains(currentUserId)) {
17006                            ps.setInstallReason(installReason, currentUserId);
17007                        }
17008                    }
17009                } else if (!previousUserIds.contains(userId)) {
17010                    ps.setInstallReason(installReason, userId);
17011                }
17012                mSettings.writeKernelMappingLPr(ps);
17013            }
17014            res.name = pkgName;
17015            res.uid = pkg.applicationInfo.uid;
17016            res.pkg = pkg;
17017            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17018            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17019            //to update install status
17020            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17021            mSettings.writeLPr();
17022            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17023        }
17024
17025        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17026    }
17027
17028    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17029        try {
17030            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17031            installPackageLI(args, res);
17032        } finally {
17033            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17034        }
17035    }
17036
17037    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17038        final int installFlags = args.installFlags;
17039        final String installerPackageName = args.installerPackageName;
17040        final String volumeUuid = args.volumeUuid;
17041        final File tmpPackageFile = new File(args.getCodePath());
17042        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17043        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17044                || (args.volumeUuid != null));
17045        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17046        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17047        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17048        final boolean virtualPreload =
17049                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
17050        boolean replace = false;
17051        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17052        if (args.move != null) {
17053            // moving a complete application; perform an initial scan on the new install location
17054            scanFlags |= SCAN_INITIAL;
17055        }
17056        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17057            scanFlags |= SCAN_DONT_KILL_APP;
17058        }
17059        if (instantApp) {
17060            scanFlags |= SCAN_AS_INSTANT_APP;
17061        }
17062        if (fullApp) {
17063            scanFlags |= SCAN_AS_FULL_APP;
17064        }
17065        if (virtualPreload) {
17066            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
17067        }
17068
17069        // Result object to be returned
17070        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17071        res.installerPackageName = installerPackageName;
17072
17073        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17074
17075        // Sanity check
17076        if (instantApp && (forwardLocked || onExternal)) {
17077            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17078                    + " external=" + onExternal);
17079            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17080            return;
17081        }
17082
17083        // Retrieve PackageSettings and parse package
17084        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17085                | PackageParser.PARSE_ENFORCE_CODE
17086                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17087                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17088                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17089        PackageParser pp = new PackageParser();
17090        pp.setSeparateProcesses(mSeparateProcesses);
17091        pp.setDisplayMetrics(mMetrics);
17092        pp.setCallback(mPackageParserCallback);
17093
17094        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17095        final PackageParser.Package pkg;
17096        try {
17097            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17098            DexMetadataHelper.validatePackageDexMetadata(pkg);
17099        } catch (PackageParserException e) {
17100            res.setError("Failed parse during installPackageLI", e);
17101            return;
17102        } finally {
17103            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17104        }
17105
17106        // Instant apps have several additional install-time checks.
17107        if (instantApp) {
17108            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
17109                Slog.w(TAG,
17110                        "Instant app package " + pkg.packageName + " does not target at least O");
17111                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17112                        "Instant app package must target at least O");
17113                return;
17114            }
17115            if (pkg.applicationInfo.targetSandboxVersion != 2) {
17116                Slog.w(TAG, "Instant app package " + pkg.packageName
17117                        + " does not target targetSandboxVersion 2");
17118                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17119                        "Instant app package must use targetSandboxVersion 2");
17120                return;
17121            }
17122            if (pkg.mSharedUserId != null) {
17123                Slog.w(TAG, "Instant app package " + pkg.packageName
17124                        + " may not declare sharedUserId.");
17125                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17126                        "Instant app package may not declare a sharedUserId");
17127                return;
17128            }
17129        }
17130
17131        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17132            // Static shared libraries have synthetic package names
17133            renameStaticSharedLibraryPackage(pkg);
17134
17135            // No static shared libs on external storage
17136            if (onExternal) {
17137                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17138                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17139                        "Packages declaring static-shared libs cannot be updated");
17140                return;
17141            }
17142        }
17143
17144        // If we are installing a clustered package add results for the children
17145        if (pkg.childPackages != null) {
17146            synchronized (mPackages) {
17147                final int childCount = pkg.childPackages.size();
17148                for (int i = 0; i < childCount; i++) {
17149                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17150                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17151                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17152                    childRes.pkg = childPkg;
17153                    childRes.name = childPkg.packageName;
17154                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17155                    if (childPs != null) {
17156                        childRes.origUsers = childPs.queryInstalledUsers(
17157                                sUserManager.getUserIds(), true);
17158                    }
17159                    if ((mPackages.containsKey(childPkg.packageName))) {
17160                        childRes.removedInfo = new PackageRemovedInfo(this);
17161                        childRes.removedInfo.removedPackage = childPkg.packageName;
17162                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17163                    }
17164                    if (res.addedChildPackages == null) {
17165                        res.addedChildPackages = new ArrayMap<>();
17166                    }
17167                    res.addedChildPackages.put(childPkg.packageName, childRes);
17168                }
17169            }
17170        }
17171
17172        // If package doesn't declare API override, mark that we have an install
17173        // time CPU ABI override.
17174        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17175            pkg.cpuAbiOverride = args.abiOverride;
17176        }
17177
17178        String pkgName = res.name = pkg.packageName;
17179        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17180            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17181                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17182                return;
17183            }
17184        }
17185
17186        try {
17187            // either use what we've been given or parse directly from the APK
17188            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
17189                pkg.setSigningDetails(args.signingDetails);
17190            } else {
17191                PackageParser.collectCertificates(pkg, false /* skipVerify */);
17192            }
17193        } catch (PackageParserException e) {
17194            res.setError("Failed collect during installPackageLI", e);
17195            return;
17196        }
17197
17198        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
17199                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
17200            Slog.w(TAG, "Instant app package " + pkg.packageName
17201                    + " is not signed with at least APK Signature Scheme v2");
17202            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17203                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
17204            return;
17205        }
17206
17207        // Get rid of all references to package scan path via parser.
17208        pp = null;
17209        String oldCodePath = null;
17210        boolean systemApp = false;
17211        synchronized (mPackages) {
17212            // Check if installing already existing package
17213            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17214                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17215                if (pkg.mOriginalPackages != null
17216                        && pkg.mOriginalPackages.contains(oldName)
17217                        && mPackages.containsKey(oldName)) {
17218                    // This package is derived from an original package,
17219                    // and this device has been updating from that original
17220                    // name.  We must continue using the original name, so
17221                    // rename the new package here.
17222                    pkg.setPackageName(oldName);
17223                    pkgName = pkg.packageName;
17224                    replace = true;
17225                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17226                            + oldName + " pkgName=" + pkgName);
17227                } else if (mPackages.containsKey(pkgName)) {
17228                    // This package, under its official name, already exists
17229                    // on the device; we should replace it.
17230                    replace = true;
17231                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17232                }
17233
17234                // Child packages are installed through the parent package
17235                if (pkg.parentPackage != null) {
17236                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17237                            "Package " + pkg.packageName + " is child of package "
17238                                    + pkg.parentPackage.parentPackage + ". Child packages "
17239                                    + "can be updated only through the parent package.");
17240                    return;
17241                }
17242
17243                if (replace) {
17244                    // Prevent apps opting out from runtime permissions
17245                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17246                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17247                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17248                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17249                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17250                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17251                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17252                                        + " doesn't support runtime permissions but the old"
17253                                        + " target SDK " + oldTargetSdk + " does.");
17254                        return;
17255                    }
17256                    // Prevent persistent apps from being updated
17257                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
17258                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
17259                                "Package " + oldPackage.packageName + " is a persistent app. "
17260                                        + "Persistent apps are not updateable.");
17261                        return;
17262                    }
17263                    // Prevent installing of child packages
17264                    if (oldPackage.parentPackage != null) {
17265                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17266                                "Package " + pkg.packageName + " is child of package "
17267                                        + oldPackage.parentPackage + ". Child packages "
17268                                        + "can be updated only through the parent package.");
17269                        return;
17270                    }
17271                }
17272            }
17273
17274            PackageSetting ps = mSettings.mPackages.get(pkgName);
17275            if (ps != null) {
17276                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17277
17278                // Static shared libs have same package with different versions where
17279                // we internally use a synthetic package name to allow multiple versions
17280                // of the same package, therefore we need to compare signatures against
17281                // the package setting for the latest library version.
17282                PackageSetting signatureCheckPs = ps;
17283                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17284                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17285                    if (libraryEntry != null) {
17286                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17287                    }
17288                }
17289
17290                // Quick sanity check that we're signed correctly if updating;
17291                // we'll check this again later when scanning, but we want to
17292                // bail early here before tripping over redefined permissions.
17293                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17294                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
17295                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
17296                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17297                                + pkg.packageName + " upgrade keys do not match the "
17298                                + "previously installed version");
17299                        return;
17300                    }
17301                } else {
17302                    try {
17303                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
17304                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
17305                        // We don't care about disabledPkgSetting on install for now.
17306                        final boolean compatMatch = verifySignatures(
17307                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
17308                                compareRecover);
17309                        // The new KeySets will be re-added later in the scanning process.
17310                        if (compatMatch) {
17311                            synchronized (mPackages) {
17312                                ksms.removeAppKeySetDataLPw(pkg.packageName);
17313                            }
17314                        }
17315                    } catch (PackageManagerException e) {
17316                        res.setError(e.error, e.getMessage());
17317                        return;
17318                    }
17319                }
17320
17321                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17322                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17323                    systemApp = (ps.pkg.applicationInfo.flags &
17324                            ApplicationInfo.FLAG_SYSTEM) != 0;
17325                }
17326                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17327            }
17328
17329            int N = pkg.permissions.size();
17330            for (int i = N-1; i >= 0; i--) {
17331                final PackageParser.Permission perm = pkg.permissions.get(i);
17332                final BasePermission bp =
17333                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17334
17335                // Don't allow anyone but the system to define ephemeral permissions.
17336                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17337                        && !systemApp) {
17338                    Slog.w(TAG, "Non-System package " + pkg.packageName
17339                            + " attempting to delcare ephemeral permission "
17340                            + perm.info.name + "; Removing ephemeral.");
17341                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17342                }
17343
17344                // Check whether the newly-scanned package wants to define an already-defined perm
17345                if (bp != null) {
17346                    // If the defining package is signed with our cert, it's okay.  This
17347                    // also includes the "updating the same package" case, of course.
17348                    // "updating same package" could also involve key-rotation.
17349                    final boolean sigsOk;
17350                    final String sourcePackageName = bp.getSourcePackageName();
17351                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17352                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17353                    if (sourcePackageName.equals(pkg.packageName)
17354                            && (ksms.shouldCheckUpgradeKeySetLocked(
17355                                    sourcePackageSetting, scanFlags))) {
17356                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17357                    } else {
17358
17359                        // in the event of signing certificate rotation, we need to see if the
17360                        // package's certificate has rotated from the current one, or if it is an
17361                        // older certificate with which the current is ok with sharing permissions
17362                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17363                                        pkg.mSigningDetails,
17364                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17365                            sigsOk = true;
17366                        } else if (pkg.mSigningDetails.checkCapability(
17367                                        sourcePackageSetting.signatures.mSigningDetails,
17368                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17369
17370                            // the scanned package checks out, has signing certificate rotation
17371                            // history, and is newer; bring it over
17372                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17373                            sigsOk = true;
17374                        } else {
17375                            sigsOk = false;
17376                        }
17377                    }
17378                    if (!sigsOk) {
17379                        // If the owning package is the system itself, we log but allow
17380                        // install to proceed; we fail the install on all other permission
17381                        // redefinitions.
17382                        if (!sourcePackageName.equals("android")) {
17383                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17384                                    + pkg.packageName + " attempting to redeclare permission "
17385                                    + perm.info.name + " already owned by " + sourcePackageName);
17386                            res.origPermission = perm.info.name;
17387                            res.origPackage = sourcePackageName;
17388                            return;
17389                        } else {
17390                            Slog.w(TAG, "Package " + pkg.packageName
17391                                    + " attempting to redeclare system permission "
17392                                    + perm.info.name + "; ignoring new declaration");
17393                            pkg.permissions.remove(i);
17394                        }
17395                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17396                        // Prevent apps to change protection level to dangerous from any other
17397                        // type as this would allow a privilege escalation where an app adds a
17398                        // normal/signature permission in other app's group and later redefines
17399                        // it as dangerous leading to the group auto-grant.
17400                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17401                                == PermissionInfo.PROTECTION_DANGEROUS) {
17402                            if (bp != null && !bp.isRuntime()) {
17403                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17404                                        + "non-runtime permission " + perm.info.name
17405                                        + " to runtime; keeping old protection level");
17406                                perm.info.protectionLevel = bp.getProtectionLevel();
17407                            }
17408                        }
17409                    }
17410                }
17411            }
17412        }
17413
17414        if (systemApp) {
17415            if (onExternal) {
17416                // Abort update; system app can't be replaced with app on sdcard
17417                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17418                        "Cannot install updates to system apps on sdcard");
17419                return;
17420            } else if (instantApp) {
17421                // Abort update; system app can't be replaced with an instant app
17422                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17423                        "Cannot update a system app with an instant app");
17424                return;
17425            }
17426        }
17427
17428        if (args.move != null) {
17429            // We did an in-place move, so dex is ready to roll
17430            scanFlags |= SCAN_NO_DEX;
17431            scanFlags |= SCAN_MOVE;
17432
17433            synchronized (mPackages) {
17434                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17435                if (ps == null) {
17436                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17437                            "Missing settings for moved package " + pkgName);
17438                }
17439
17440                // We moved the entire application as-is, so bring over the
17441                // previously derived ABI information.
17442                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17443                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17444            }
17445
17446        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17447            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17448            scanFlags |= SCAN_NO_DEX;
17449
17450            try {
17451                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17452                    args.abiOverride : pkg.cpuAbiOverride);
17453                final boolean extractNativeLibs = !pkg.isLibrary();
17454                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17455            } catch (PackageManagerException pme) {
17456                Slog.e(TAG, "Error deriving application ABI", pme);
17457                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17458                return;
17459            }
17460
17461            // Shared libraries for the package need to be updated.
17462            synchronized (mPackages) {
17463                try {
17464                    updateSharedLibrariesLPr(pkg, null);
17465                } catch (PackageManagerException e) {
17466                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17467                }
17468            }
17469        }
17470
17471        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17472            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17473            return;
17474        }
17475
17476        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17477            String apkPath = null;
17478            synchronized (mPackages) {
17479                // Note that if the attacker managed to skip verify setup, for example by tampering
17480                // with the package settings, upon reboot we will do full apk verification when
17481                // verity is not detected.
17482                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17483                if (ps != null && ps.isPrivileged()) {
17484                    apkPath = pkg.baseCodePath;
17485                }
17486            }
17487
17488            if (apkPath != null) {
17489                final VerityUtils.SetupResult result =
17490                        VerityUtils.generateApkVeritySetupData(apkPath);
17491                if (result.isOk()) {
17492                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17493                    FileDescriptor fd = result.getUnownedFileDescriptor();
17494                    try {
17495                        final byte[] signedRootHash = VerityUtils.generateFsverityRootHash(apkPath);
17496                        mInstaller.installApkVerity(apkPath, fd, result.getContentSize());
17497                        mInstaller.assertFsverityRootHashMatches(apkPath, signedRootHash);
17498                    } catch (InstallerException | IOException | DigestException |
17499                             NoSuchAlgorithmException e) {
17500                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17501                                "Failed to set up verity: " + e);
17502                        return;
17503                    } finally {
17504                        IoUtils.closeQuietly(fd);
17505                    }
17506                } else if (result.isFailed()) {
17507                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17508                    return;
17509                } else {
17510                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17511                    // reboot.
17512                }
17513            }
17514        }
17515
17516        if (!instantApp) {
17517            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17518        } else {
17519            if (DEBUG_DOMAIN_VERIFICATION) {
17520                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17521            }
17522        }
17523
17524        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17525                "installPackageLI")) {
17526            if (replace) {
17527                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17528                    // Static libs have a synthetic package name containing the version
17529                    // and cannot be updated as an update would get a new package name,
17530                    // unless this is the exact same version code which is useful for
17531                    // development.
17532                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17533                    if (existingPkg != null &&
17534                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17535                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17536                                + "static-shared libs cannot be updated");
17537                        return;
17538                    }
17539                }
17540                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17541                        installerPackageName, res, args.installReason);
17542            } else {
17543                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17544                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17545            }
17546        }
17547
17548        // Prepare the application profiles for the new code paths.
17549        // This needs to be done before invoking dexopt so that any install-time profile
17550        // can be used for optimizations.
17551        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17552
17553        // Check whether we need to dexopt the app.
17554        //
17555        // NOTE: it is IMPORTANT to call dexopt:
17556        //   - after doRename which will sync the package data from PackageParser.Package and its
17557        //     corresponding ApplicationInfo.
17558        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17559        //     uid of the application (pkg.applicationInfo.uid).
17560        //     This update happens in place!
17561        //
17562        // We only need to dexopt if the package meets ALL of the following conditions:
17563        //   1) it is not forward locked.
17564        //   2) it is not on on an external ASEC container.
17565        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17566        //   4) it is not debuggable.
17567        //
17568        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17569        // complete, so we skip this step during installation. Instead, we'll take extra time
17570        // the first time the instant app starts. It's preferred to do it this way to provide
17571        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17572        // middle of running an instant app. The default behaviour can be overridden
17573        // via gservices.
17574        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17575                && !forwardLocked
17576                && !pkg.applicationInfo.isExternalAsec()
17577                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17578                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0)
17579                && ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0);
17580
17581        if (performDexopt) {
17582            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17583            // Do not run PackageDexOptimizer through the local performDexOpt
17584            // method because `pkg` may not be in `mPackages` yet.
17585            //
17586            // Also, don't fail application installs if the dexopt step fails.
17587            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17588                    REASON_INSTALL,
17589                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17590                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17591            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17592                    null /* instructionSets */,
17593                    getOrCreateCompilerPackageStats(pkg),
17594                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17595                    dexoptOptions);
17596            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17597        }
17598
17599        // Notify BackgroundDexOptService that the package has been changed.
17600        // If this is an update of a package which used to fail to compile,
17601        // BackgroundDexOptService will remove it from its blacklist.
17602        // TODO: Layering violation
17603        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17604
17605        synchronized (mPackages) {
17606            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17607            if (ps != null) {
17608                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17609                ps.setUpdateAvailable(false /*updateAvailable*/);
17610            }
17611
17612            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17613            for (int i = 0; i < childCount; i++) {
17614                PackageParser.Package childPkg = pkg.childPackages.get(i);
17615                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17616                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17617                if (childPs != null) {
17618                    childRes.newUsers = childPs.queryInstalledUsers(
17619                            sUserManager.getUserIds(), true);
17620                }
17621            }
17622
17623            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17624                updateSequenceNumberLP(ps, res.newUsers);
17625                updateInstantAppInstallerLocked(pkgName);
17626            }
17627        }
17628    }
17629
17630    private void startIntentFilterVerifications(int userId, boolean replacing,
17631            PackageParser.Package pkg) {
17632        if (mIntentFilterVerifierComponent == null) {
17633            Slog.w(TAG, "No IntentFilter verification will not be done as "
17634                    + "there is no IntentFilterVerifier available!");
17635            return;
17636        }
17637
17638        final int verifierUid = getPackageUid(
17639                mIntentFilterVerifierComponent.getPackageName(),
17640                MATCH_DEBUG_TRIAGED_MISSING,
17641                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17642
17643        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17644        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17645        mHandler.sendMessage(msg);
17646
17647        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17648        for (int i = 0; i < childCount; i++) {
17649            PackageParser.Package childPkg = pkg.childPackages.get(i);
17650            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17651            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17652            mHandler.sendMessage(msg);
17653        }
17654    }
17655
17656    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17657            PackageParser.Package pkg) {
17658        int size = pkg.activities.size();
17659        if (size == 0) {
17660            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17661                    "No activity, so no need to verify any IntentFilter!");
17662            return;
17663        }
17664
17665        final boolean hasDomainURLs = hasDomainURLs(pkg);
17666        if (!hasDomainURLs) {
17667            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17668                    "No domain URLs, so no need to verify any IntentFilter!");
17669            return;
17670        }
17671
17672        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17673                + " if any IntentFilter from the " + size
17674                + " Activities needs verification ...");
17675
17676        int count = 0;
17677        final String packageName = pkg.packageName;
17678
17679        synchronized (mPackages) {
17680            // If this is a new install and we see that we've already run verification for this
17681            // package, we have nothing to do: it means the state was restored from backup.
17682            if (!replacing) {
17683                IntentFilterVerificationInfo ivi =
17684                        mSettings.getIntentFilterVerificationLPr(packageName);
17685                if (ivi != null) {
17686                    if (DEBUG_DOMAIN_VERIFICATION) {
17687                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17688                                + ivi.getStatusString());
17689                    }
17690                    return;
17691                }
17692            }
17693
17694            // If any filters need to be verified, then all need to be.
17695            boolean needToVerify = false;
17696            for (PackageParser.Activity a : pkg.activities) {
17697                for (ActivityIntentInfo filter : a.intents) {
17698                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17699                        if (DEBUG_DOMAIN_VERIFICATION) {
17700                            Slog.d(TAG,
17701                                    "Intent filter needs verification, so processing all filters");
17702                        }
17703                        needToVerify = true;
17704                        break;
17705                    }
17706                }
17707            }
17708
17709            if (needToVerify) {
17710                final int verificationId = mIntentFilterVerificationToken++;
17711                for (PackageParser.Activity a : pkg.activities) {
17712                    for (ActivityIntentInfo filter : a.intents) {
17713                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17714                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17715                                    "Verification needed for IntentFilter:" + filter.toString());
17716                            mIntentFilterVerifier.addOneIntentFilterVerification(
17717                                    verifierUid, userId, verificationId, filter, packageName);
17718                            count++;
17719                        }
17720                    }
17721                }
17722            }
17723        }
17724
17725        if (count > 0) {
17726            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17727                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17728                    +  " for userId:" + userId);
17729            mIntentFilterVerifier.startVerifications(userId);
17730        } else {
17731            if (DEBUG_DOMAIN_VERIFICATION) {
17732                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17733            }
17734        }
17735    }
17736
17737    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17738        final ComponentName cn  = filter.activity.getComponentName();
17739        final String packageName = cn.getPackageName();
17740
17741        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17742                packageName);
17743        if (ivi == null) {
17744            return true;
17745        }
17746        int status = ivi.getStatus();
17747        switch (status) {
17748            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17749            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17750                return true;
17751
17752            default:
17753                // Nothing to do
17754                return false;
17755        }
17756    }
17757
17758    private static boolean isMultiArch(ApplicationInfo info) {
17759        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17760    }
17761
17762    private static boolean isExternal(PackageParser.Package pkg) {
17763        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17764    }
17765
17766    private static boolean isExternal(PackageSetting ps) {
17767        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17768    }
17769
17770    private static boolean isSystemApp(PackageParser.Package pkg) {
17771        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17772    }
17773
17774    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17775        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17776    }
17777
17778    private static boolean isOemApp(PackageParser.Package pkg) {
17779        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17780    }
17781
17782    private static boolean isVendorApp(PackageParser.Package pkg) {
17783        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17784    }
17785
17786    private static boolean isProductApp(PackageParser.Package pkg) {
17787        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17788    }
17789
17790    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17791        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17792    }
17793
17794    private static boolean isSystemApp(PackageSetting ps) {
17795        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17796    }
17797
17798    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17799        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17800    }
17801
17802    private int packageFlagsToInstallFlags(PackageSetting ps) {
17803        int installFlags = 0;
17804        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17805            // This existing package was an external ASEC install when we have
17806            // the external flag without a UUID
17807            installFlags |= PackageManager.INSTALL_EXTERNAL;
17808        }
17809        if (ps.isForwardLocked()) {
17810            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17811        }
17812        return installFlags;
17813    }
17814
17815    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17816        if (isExternal(pkg)) {
17817            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17818                return mSettings.getExternalVersion();
17819            } else {
17820                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17821            }
17822        } else {
17823            return mSettings.getInternalVersion();
17824        }
17825    }
17826
17827    private void deleteTempPackageFiles() {
17828        final FilenameFilter filter = new FilenameFilter() {
17829            public boolean accept(File dir, String name) {
17830                return name.startsWith("vmdl") && name.endsWith(".tmp");
17831            }
17832        };
17833        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17834            file.delete();
17835        }
17836    }
17837
17838    @Override
17839    public void deletePackageAsUser(String packageName, int versionCode,
17840            IPackageDeleteObserver observer, int userId, int flags) {
17841        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17842                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17843    }
17844
17845    @Override
17846    public void deletePackageVersioned(VersionedPackage versionedPackage,
17847            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17848        final int callingUid = Binder.getCallingUid();
17849        mContext.enforceCallingOrSelfPermission(
17850                android.Manifest.permission.DELETE_PACKAGES, null);
17851        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17852        Preconditions.checkNotNull(versionedPackage);
17853        Preconditions.checkNotNull(observer);
17854        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17855                PackageManager.VERSION_CODE_HIGHEST,
17856                Long.MAX_VALUE, "versionCode must be >= -1");
17857
17858        final String packageName = versionedPackage.getPackageName();
17859        final long versionCode = versionedPackage.getLongVersionCode();
17860        final String internalPackageName;
17861        synchronized (mPackages) {
17862            // Normalize package name to handle renamed packages and static libs
17863            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17864        }
17865
17866        final int uid = Binder.getCallingUid();
17867        if (!isOrphaned(internalPackageName)
17868                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17869            try {
17870                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17871                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17872                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17873                observer.onUserActionRequired(intent);
17874            } catch (RemoteException re) {
17875            }
17876            return;
17877        }
17878        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17879        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17880        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17881            mContext.enforceCallingOrSelfPermission(
17882                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17883                    "deletePackage for user " + userId);
17884        }
17885
17886        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17887            try {
17888                observer.onPackageDeleted(packageName,
17889                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17890            } catch (RemoteException re) {
17891            }
17892            return;
17893        }
17894
17895        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17896            try {
17897                observer.onPackageDeleted(packageName,
17898                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17899            } catch (RemoteException re) {
17900            }
17901            return;
17902        }
17903
17904        if (DEBUG_REMOVE) {
17905            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17906                    + " deleteAllUsers: " + deleteAllUsers + " version="
17907                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17908                    ? "VERSION_CODE_HIGHEST" : versionCode));
17909        }
17910        // Queue up an async operation since the package deletion may take a little while.
17911        mHandler.post(new Runnable() {
17912            public void run() {
17913                mHandler.removeCallbacks(this);
17914                int returnCode;
17915                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17916                boolean doDeletePackage = true;
17917                if (ps != null) {
17918                    final boolean targetIsInstantApp =
17919                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17920                    doDeletePackage = !targetIsInstantApp
17921                            || canViewInstantApps;
17922                }
17923                if (doDeletePackage) {
17924                    if (!deleteAllUsers) {
17925                        returnCode = deletePackageX(internalPackageName, versionCode,
17926                                userId, deleteFlags);
17927                    } else {
17928                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17929                                internalPackageName, users);
17930                        // If nobody is blocking uninstall, proceed with delete for all users
17931                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17932                            returnCode = deletePackageX(internalPackageName, versionCode,
17933                                    userId, deleteFlags);
17934                        } else {
17935                            // Otherwise uninstall individually for users with blockUninstalls=false
17936                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17937                            for (int userId : users) {
17938                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17939                                    returnCode = deletePackageX(internalPackageName, versionCode,
17940                                            userId, userFlags);
17941                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17942                                        Slog.w(TAG, "Package delete failed for user " + userId
17943                                                + ", returnCode " + returnCode);
17944                                    }
17945                                }
17946                            }
17947                            // The app has only been marked uninstalled for certain users.
17948                            // We still need to report that delete was blocked
17949                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17950                        }
17951                    }
17952                } else {
17953                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17954                }
17955                try {
17956                    observer.onPackageDeleted(packageName, returnCode, null);
17957                } catch (RemoteException e) {
17958                    Log.i(TAG, "Observer no longer exists.");
17959                } //end catch
17960            } //end run
17961        });
17962    }
17963
17964    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17965        if (pkg.staticSharedLibName != null) {
17966            return pkg.manifestPackageName;
17967        }
17968        return pkg.packageName;
17969    }
17970
17971    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17972        // Handle renamed packages
17973        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17974        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17975
17976        // Is this a static library?
17977        LongSparseArray<SharedLibraryEntry> versionedLib =
17978                mStaticLibsByDeclaringPackage.get(packageName);
17979        if (versionedLib == null || versionedLib.size() <= 0) {
17980            return packageName;
17981        }
17982
17983        // Figure out which lib versions the caller can see
17984        LongSparseLongArray versionsCallerCanSee = null;
17985        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17986        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17987                && callingAppId != Process.ROOT_UID) {
17988            versionsCallerCanSee = new LongSparseLongArray();
17989            String libName = versionedLib.valueAt(0).info.getName();
17990            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17991            if (uidPackages != null) {
17992                for (String uidPackage : uidPackages) {
17993                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17994                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17995                    if (libIdx >= 0) {
17996                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17997                        versionsCallerCanSee.append(libVersion, libVersion);
17998                    }
17999                }
18000            }
18001        }
18002
18003        // Caller can see nothing - done
18004        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18005            return packageName;
18006        }
18007
18008        // Find the version the caller can see and the app version code
18009        SharedLibraryEntry highestVersion = null;
18010        final int versionCount = versionedLib.size();
18011        for (int i = 0; i < versionCount; i++) {
18012            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18013            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18014                    libEntry.info.getLongVersion()) < 0) {
18015                continue;
18016            }
18017            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
18018            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18019                if (libVersionCode == versionCode) {
18020                    return libEntry.apk;
18021                }
18022            } else if (highestVersion == null) {
18023                highestVersion = libEntry;
18024            } else if (libVersionCode  > highestVersion.info
18025                    .getDeclaringPackage().getLongVersionCode()) {
18026                highestVersion = libEntry;
18027            }
18028        }
18029
18030        if (highestVersion != null) {
18031            return highestVersion.apk;
18032        }
18033
18034        return packageName;
18035    }
18036
18037    boolean isCallerVerifier(int callingUid) {
18038        final int callingUserId = UserHandle.getUserId(callingUid);
18039        return mRequiredVerifierPackage != null &&
18040                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
18041    }
18042
18043    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18044        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18045              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18046            return true;
18047        }
18048        final int callingUserId = UserHandle.getUserId(callingUid);
18049        // If the caller installed the pkgName, then allow it to silently uninstall.
18050        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18051            return true;
18052        }
18053
18054        // Allow package verifier to silently uninstall.
18055        if (mRequiredVerifierPackage != null &&
18056                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18057            return true;
18058        }
18059
18060        // Allow package uninstaller to silently uninstall.
18061        if (mRequiredUninstallerPackage != null &&
18062                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18063            return true;
18064        }
18065
18066        // Allow storage manager to silently uninstall.
18067        if (mStorageManagerPackage != null &&
18068                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18069            return true;
18070        }
18071
18072        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18073        // uninstall for device owner provisioning.
18074        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18075                == PERMISSION_GRANTED) {
18076            return true;
18077        }
18078
18079        return false;
18080    }
18081
18082    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18083        int[] result = EMPTY_INT_ARRAY;
18084        for (int userId : userIds) {
18085            if (getBlockUninstallForUser(packageName, userId)) {
18086                result = ArrayUtils.appendInt(result, userId);
18087            }
18088        }
18089        return result;
18090    }
18091
18092    @Override
18093    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18094        final int callingUid = Binder.getCallingUid();
18095        if (getInstantAppPackageName(callingUid) != null
18096                && !isCallerSameApp(packageName, callingUid)) {
18097            return false;
18098        }
18099        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18100    }
18101
18102    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18103        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18104                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18105        try {
18106            if (dpm != null) {
18107                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18108                        /* callingUserOnly =*/ false);
18109                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18110                        : deviceOwnerComponentName.getPackageName();
18111                // Does the package contains the device owner?
18112                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18113                // this check is probably not needed, since DO should be registered as a device
18114                // admin on some user too. (Original bug for this: b/17657954)
18115                if (packageName.equals(deviceOwnerPackageName)) {
18116                    return true;
18117                }
18118                // Does it contain a device admin for any user?
18119                int[] users;
18120                if (userId == UserHandle.USER_ALL) {
18121                    users = sUserManager.getUserIds();
18122                } else {
18123                    users = new int[]{userId};
18124                }
18125                for (int i = 0; i < users.length; ++i) {
18126                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18127                        return true;
18128                    }
18129                }
18130            }
18131        } catch (RemoteException e) {
18132        }
18133        return false;
18134    }
18135
18136    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18137        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18138    }
18139
18140    /**
18141     *  This method is an internal method that could be get invoked either
18142     *  to delete an installed package or to clean up a failed installation.
18143     *  After deleting an installed package, a broadcast is sent to notify any
18144     *  listeners that the package has been removed. For cleaning up a failed
18145     *  installation, the broadcast is not necessary since the package's
18146     *  installation wouldn't have sent the initial broadcast either
18147     *  The key steps in deleting a package are
18148     *  deleting the package information in internal structures like mPackages,
18149     *  deleting the packages base directories through installd
18150     *  updating mSettings to reflect current status
18151     *  persisting settings for later use
18152     *  sending a broadcast if necessary
18153     */
18154    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
18155        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18156        final boolean res;
18157
18158        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18159                ? UserHandle.USER_ALL : userId;
18160
18161        if (isPackageDeviceAdmin(packageName, removeUser)) {
18162            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18163            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18164        }
18165
18166        PackageSetting uninstalledPs = null;
18167        PackageParser.Package pkg = null;
18168
18169        // for the uninstall-updates case and restricted profiles, remember the per-
18170        // user handle installed state
18171        int[] allUsers;
18172        synchronized (mPackages) {
18173            uninstalledPs = mSettings.mPackages.get(packageName);
18174            if (uninstalledPs == null) {
18175                Slog.w(TAG, "Not removing non-existent package " + packageName);
18176                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18177            }
18178
18179            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18180                    && uninstalledPs.versionCode != versionCode) {
18181                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18182                        + uninstalledPs.versionCode + " != " + versionCode);
18183                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18184            }
18185
18186            // Static shared libs can be declared by any package, so let us not
18187            // allow removing a package if it provides a lib others depend on.
18188            pkg = mPackages.get(packageName);
18189
18190            allUsers = sUserManager.getUserIds();
18191
18192            if (pkg != null && pkg.staticSharedLibName != null) {
18193                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18194                        pkg.staticSharedLibVersion);
18195                if (libEntry != null) {
18196                    for (int currUserId : allUsers) {
18197                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18198                            continue;
18199                        }
18200                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18201                                libEntry.info, 0, currUserId);
18202                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18203                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18204                                    + " hosting lib " + libEntry.info.getName() + " version "
18205                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
18206                                    + " for user " + currUserId);
18207                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18208                        }
18209                    }
18210                }
18211            }
18212
18213            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18214        }
18215
18216        final int freezeUser;
18217        if (isUpdatedSystemApp(uninstalledPs)
18218                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18219            // We're downgrading a system app, which will apply to all users, so
18220            // freeze them all during the downgrade
18221            freezeUser = UserHandle.USER_ALL;
18222        } else {
18223            freezeUser = removeUser;
18224        }
18225
18226        synchronized (mInstallLock) {
18227            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18228            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18229                    deleteFlags, "deletePackageX")) {
18230                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18231                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
18232            }
18233            synchronized (mPackages) {
18234                if (res) {
18235                    if (pkg != null) {
18236                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18237                    }
18238                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18239                    updateInstantAppInstallerLocked(packageName);
18240                }
18241            }
18242        }
18243
18244        if (res) {
18245            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18246            info.sendPackageRemovedBroadcasts(killApp);
18247            info.sendSystemPackageUpdatedBroadcasts();
18248            info.sendSystemPackageAppearedBroadcasts();
18249        }
18250        // Force a gc here.
18251        Runtime.getRuntime().gc();
18252        // Delete the resources here after sending the broadcast to let
18253        // other processes clean up before deleting resources.
18254        if (info.args != null) {
18255            synchronized (mInstallLock) {
18256                info.args.doPostDeleteLI(true);
18257            }
18258        }
18259
18260        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18261    }
18262
18263    static class PackageRemovedInfo {
18264        final PackageSender packageSender;
18265        String removedPackage;
18266        String installerPackageName;
18267        int uid = -1;
18268        int removedAppId = -1;
18269        int[] origUsers;
18270        int[] removedUsers = null;
18271        int[] broadcastUsers = null;
18272        int[] instantUserIds = null;
18273        SparseArray<Integer> installReasons;
18274        boolean isRemovedPackageSystemUpdate = false;
18275        boolean isUpdate;
18276        boolean dataRemoved;
18277        boolean removedForAllUsers;
18278        boolean isStaticSharedLib;
18279        // Clean up resources deleted packages.
18280        InstallArgs args = null;
18281        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18282        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18283
18284        PackageRemovedInfo(PackageSender packageSender) {
18285            this.packageSender = packageSender;
18286        }
18287
18288        void sendPackageRemovedBroadcasts(boolean killApp) {
18289            sendPackageRemovedBroadcastInternal(killApp);
18290            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18291            for (int i = 0; i < childCount; i++) {
18292                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18293                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18294            }
18295        }
18296
18297        void sendSystemPackageUpdatedBroadcasts() {
18298            if (isRemovedPackageSystemUpdate) {
18299                sendSystemPackageUpdatedBroadcastsInternal();
18300                final int childCount = (removedChildPackages != null)
18301                        ? removedChildPackages.size() : 0;
18302                for (int i = 0; i < childCount; i++) {
18303                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18304                    if (childInfo.isRemovedPackageSystemUpdate) {
18305                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18306                    }
18307                }
18308            }
18309        }
18310
18311        void sendSystemPackageAppearedBroadcasts() {
18312            final int packageCount = (appearedChildPackages != null)
18313                    ? appearedChildPackages.size() : 0;
18314            for (int i = 0; i < packageCount; i++) {
18315                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18316                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18317                    true /*sendBootCompleted*/, false /*startReceiver*/,
18318                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
18319            }
18320        }
18321
18322        private void sendSystemPackageUpdatedBroadcastsInternal() {
18323            Bundle extras = new Bundle(2);
18324            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18325            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18326            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18327                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18328            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18329                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18330            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18331                null, null, 0, removedPackage, null, null, null);
18332            if (installerPackageName != null) {
18333                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18334                        removedPackage, extras, 0 /*flags*/,
18335                        installerPackageName, null, null, null);
18336                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18337                        removedPackage, extras, 0 /*flags*/,
18338                        installerPackageName, null, null, null);
18339            }
18340        }
18341
18342        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18343            // Don't send static shared library removal broadcasts as these
18344            // libs are visible only the the apps that depend on them an one
18345            // cannot remove the library if it has a dependency.
18346            if (isStaticSharedLib) {
18347                return;
18348            }
18349            Bundle extras = new Bundle(2);
18350            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18351            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18352            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18353            if (isUpdate || isRemovedPackageSystemUpdate) {
18354                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18355            }
18356            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18357            if (removedPackage != null) {
18358                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18359                    removedPackage, extras, 0, null /*targetPackage*/, null,
18360                    broadcastUsers, instantUserIds);
18361                if (installerPackageName != null) {
18362                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18363                            removedPackage, extras, 0 /*flags*/,
18364                            installerPackageName, null, broadcastUsers, instantUserIds);
18365                }
18366                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18367                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18368                        removedPackage, extras,
18369                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18370                        null, null, broadcastUsers, instantUserIds);
18371                    packageSender.notifyPackageRemoved(removedPackage);
18372                }
18373            }
18374            if (removedAppId >= 0) {
18375                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18376                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18377                    null, null, broadcastUsers, instantUserIds);
18378            }
18379        }
18380
18381        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18382            removedUsers = userIds;
18383            if (removedUsers == null) {
18384                broadcastUsers = null;
18385                return;
18386            }
18387
18388            broadcastUsers = EMPTY_INT_ARRAY;
18389            instantUserIds = EMPTY_INT_ARRAY;
18390            for (int i = userIds.length - 1; i >= 0; --i) {
18391                final int userId = userIds[i];
18392                if (deletedPackageSetting.getInstantApp(userId)) {
18393                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18394                } else {
18395                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18396                }
18397            }
18398        }
18399    }
18400
18401    /*
18402     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18403     * flag is not set, the data directory is removed as well.
18404     * make sure this flag is set for partially installed apps. If not its meaningless to
18405     * delete a partially installed application.
18406     */
18407    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18408            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18409        String packageName = ps.name;
18410        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18411        // Retrieve object to delete permissions for shared user later on
18412        final PackageParser.Package deletedPkg;
18413        final PackageSetting deletedPs;
18414        // reader
18415        synchronized (mPackages) {
18416            deletedPkg = mPackages.get(packageName);
18417            deletedPs = mSettings.mPackages.get(packageName);
18418            if (outInfo != null) {
18419                outInfo.removedPackage = packageName;
18420                outInfo.installerPackageName = ps.installerPackageName;
18421                outInfo.isStaticSharedLib = deletedPkg != null
18422                        && deletedPkg.staticSharedLibName != null;
18423                outInfo.populateUsers(deletedPs == null ? null
18424                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18425            }
18426        }
18427
18428        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18429
18430        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18431            final PackageParser.Package resolvedPkg;
18432            if (deletedPkg != null) {
18433                resolvedPkg = deletedPkg;
18434            } else {
18435                // We don't have a parsed package when it lives on an ejected
18436                // adopted storage device, so fake something together
18437                resolvedPkg = new PackageParser.Package(ps.name);
18438                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18439            }
18440            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18441                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18442            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18443            if (outInfo != null) {
18444                outInfo.dataRemoved = true;
18445            }
18446            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18447        }
18448
18449        int removedAppId = -1;
18450
18451        // writer
18452        synchronized (mPackages) {
18453            boolean installedStateChanged = false;
18454            if (deletedPs != null) {
18455                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18456                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18457                    clearDefaultBrowserIfNeeded(packageName);
18458                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18459                    removedAppId = mSettings.removePackageLPw(packageName);
18460                    if (outInfo != null) {
18461                        outInfo.removedAppId = removedAppId;
18462                    }
18463                    mPermissionManager.updatePermissions(
18464                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18465                    if (deletedPs.sharedUser != null) {
18466                        // Remove permissions associated with package. Since runtime
18467                        // permissions are per user we have to kill the removed package
18468                        // or packages running under the shared user of the removed
18469                        // package if revoking the permissions requested only by the removed
18470                        // package is successful and this causes a change in gids.
18471                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18472                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18473                                    userId);
18474                            if (userIdToKill == UserHandle.USER_ALL
18475                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18476                                // If gids changed for this user, kill all affected packages.
18477                                mHandler.post(new Runnable() {
18478                                    @Override
18479                                    public void run() {
18480                                        // This has to happen with no lock held.
18481                                        killApplication(deletedPs.name, deletedPs.appId,
18482                                                KILL_APP_REASON_GIDS_CHANGED);
18483                                    }
18484                                });
18485                                break;
18486                            }
18487                        }
18488                    }
18489                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18490                }
18491                // make sure to preserve per-user disabled state if this removal was just
18492                // a downgrade of a system app to the factory package
18493                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18494                    if (DEBUG_REMOVE) {
18495                        Slog.d(TAG, "Propagating install state across downgrade");
18496                    }
18497                    for (int userId : allUserHandles) {
18498                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18499                        if (DEBUG_REMOVE) {
18500                            Slog.d(TAG, "    user " + userId + " => " + installed);
18501                        }
18502                        if (installed != ps.getInstalled(userId)) {
18503                            installedStateChanged = true;
18504                        }
18505                        ps.setInstalled(installed, userId);
18506                    }
18507                }
18508            }
18509            // can downgrade to reader
18510            if (writeSettings) {
18511                // Save settings now
18512                mSettings.writeLPr();
18513            }
18514            if (installedStateChanged) {
18515                mSettings.writeKernelMappingLPr(ps);
18516            }
18517        }
18518        if (removedAppId != -1) {
18519            // A user ID was deleted here. Go through all users and remove it
18520            // from KeyStore.
18521            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18522        }
18523    }
18524
18525    static boolean locationIsPrivileged(String path) {
18526        try {
18527            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18528            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18529            final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app");
18530            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18531            return path.startsWith(privilegedAppDir.getCanonicalPath())
18532                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18533                    || path.startsWith(privilegedOdmAppDir.getCanonicalPath())
18534                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18535        } catch (IOException e) {
18536            Slog.e(TAG, "Unable to access code path " + path);
18537        }
18538        return false;
18539    }
18540
18541    static boolean locationIsOem(String path) {
18542        try {
18543            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18544        } catch (IOException e) {
18545            Slog.e(TAG, "Unable to access code path " + path);
18546        }
18547        return false;
18548    }
18549
18550    static boolean locationIsVendor(String path) {
18551        try {
18552            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath())
18553                    || path.startsWith(Environment.getOdmDirectory().getCanonicalPath());
18554        } catch (IOException e) {
18555            Slog.e(TAG, "Unable to access code path " + path);
18556        }
18557        return false;
18558    }
18559
18560    static boolean locationIsProduct(String path) {
18561        try {
18562            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18563        } catch (IOException e) {
18564            Slog.e(TAG, "Unable to access code path " + path);
18565        }
18566        return false;
18567    }
18568
18569    /*
18570     * Tries to delete system package.
18571     */
18572    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18573            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18574            boolean writeSettings) {
18575        if (deletedPs.parentPackageName != null) {
18576            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18577            return false;
18578        }
18579
18580        final boolean applyUserRestrictions
18581                = (allUserHandles != null) && (outInfo.origUsers != null);
18582        final PackageSetting disabledPs;
18583        // Confirm if the system package has been updated
18584        // An updated system app can be deleted. This will also have to restore
18585        // the system pkg from system partition
18586        // reader
18587        synchronized (mPackages) {
18588            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18589        }
18590
18591        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18592                + " disabledPs=" + disabledPs);
18593
18594        if (disabledPs == null) {
18595            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18596            return false;
18597        } else if (DEBUG_REMOVE) {
18598            Slog.d(TAG, "Deleting system pkg from data partition");
18599        }
18600
18601        if (DEBUG_REMOVE) {
18602            if (applyUserRestrictions) {
18603                Slog.d(TAG, "Remembering install states:");
18604                for (int userId : allUserHandles) {
18605                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18606                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18607                }
18608            }
18609        }
18610
18611        // Delete the updated package
18612        outInfo.isRemovedPackageSystemUpdate = true;
18613        if (outInfo.removedChildPackages != null) {
18614            final int childCount = (deletedPs.childPackageNames != null)
18615                    ? deletedPs.childPackageNames.size() : 0;
18616            for (int i = 0; i < childCount; i++) {
18617                String childPackageName = deletedPs.childPackageNames.get(i);
18618                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18619                        .contains(childPackageName)) {
18620                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18621                            childPackageName);
18622                    if (childInfo != null) {
18623                        childInfo.isRemovedPackageSystemUpdate = true;
18624                    }
18625                }
18626            }
18627        }
18628
18629        if (disabledPs.versionCode < deletedPs.versionCode) {
18630            // Delete data for downgrades
18631            flags &= ~PackageManager.DELETE_KEEP_DATA;
18632        } else {
18633            // Preserve data by setting flag
18634            flags |= PackageManager.DELETE_KEEP_DATA;
18635        }
18636
18637        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18638                outInfo, writeSettings, disabledPs.pkg);
18639        if (!ret) {
18640            return false;
18641        }
18642
18643        // writer
18644        synchronized (mPackages) {
18645            // NOTE: The system package always needs to be enabled; even if it's for
18646            // a compressed stub. If we don't, installing the system package fails
18647            // during scan [scanning checks the disabled packages]. We will reverse
18648            // this later, after we've "installed" the stub.
18649            // Reinstate the old system package
18650            enableSystemPackageLPw(disabledPs.pkg);
18651            // Remove any native libraries from the upgraded package.
18652            removeNativeBinariesLI(deletedPs);
18653        }
18654
18655        // Install the system package
18656        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18657        try {
18658            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18659                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18660        } catch (PackageManagerException e) {
18661            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18662                    + e.getMessage());
18663            return false;
18664        } finally {
18665            if (disabledPs.pkg.isStub) {
18666                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18667            }
18668        }
18669        return true;
18670    }
18671
18672    /**
18673     * Installs a package that's already on the system partition.
18674     */
18675    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18676            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18677            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18678                    throws PackageManagerException {
18679        @ParseFlags int parseFlags =
18680                mDefParseFlags
18681                | PackageParser.PARSE_MUST_BE_APK
18682                | PackageParser.PARSE_IS_SYSTEM_DIR;
18683        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18684        if (isPrivileged || locationIsPrivileged(codePathString)) {
18685            scanFlags |= SCAN_AS_PRIVILEGED;
18686        }
18687        if (locationIsOem(codePathString)) {
18688            scanFlags |= SCAN_AS_OEM;
18689        }
18690        if (locationIsVendor(codePathString)) {
18691            scanFlags |= SCAN_AS_VENDOR;
18692        }
18693        if (locationIsProduct(codePathString)) {
18694            scanFlags |= SCAN_AS_PRODUCT;
18695        }
18696
18697        final File codePath = new File(codePathString);
18698        final PackageParser.Package pkg =
18699                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18700
18701        try {
18702            // update shared libraries for the newly re-installed system package
18703            updateSharedLibrariesLPr(pkg, null);
18704        } catch (PackageManagerException e) {
18705            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18706        }
18707
18708        prepareAppDataAfterInstallLIF(pkg);
18709
18710        // writer
18711        synchronized (mPackages) {
18712            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18713
18714            // Propagate the permissions state as we do not want to drop on the floor
18715            // runtime permissions. The update permissions method below will take
18716            // care of removing obsolete permissions and grant install permissions.
18717            if (origPermissionState != null) {
18718                ps.getPermissionsState().copyFrom(origPermissionState);
18719            }
18720            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18721                    mPermissionCallback);
18722
18723            final boolean applyUserRestrictions
18724                    = (allUserHandles != null) && (origUserHandles != null);
18725            if (applyUserRestrictions) {
18726                boolean installedStateChanged = false;
18727                if (DEBUG_REMOVE) {
18728                    Slog.d(TAG, "Propagating install state across reinstall");
18729                }
18730                for (int userId : allUserHandles) {
18731                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18732                    if (DEBUG_REMOVE) {
18733                        Slog.d(TAG, "    user " + userId + " => " + installed);
18734                    }
18735                    if (installed != ps.getInstalled(userId)) {
18736                        installedStateChanged = true;
18737                    }
18738                    ps.setInstalled(installed, userId);
18739
18740                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18741                }
18742                // Regardless of writeSettings we need to ensure that this restriction
18743                // state propagation is persisted
18744                mSettings.writeAllUsersPackageRestrictionsLPr();
18745                if (installedStateChanged) {
18746                    mSettings.writeKernelMappingLPr(ps);
18747                }
18748            }
18749            // can downgrade to reader here
18750            if (writeSettings) {
18751                mSettings.writeLPr();
18752            }
18753        }
18754        return pkg;
18755    }
18756
18757    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18758            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18759            PackageRemovedInfo outInfo, boolean writeSettings,
18760            PackageParser.Package replacingPackage) {
18761        synchronized (mPackages) {
18762            if (outInfo != null) {
18763                outInfo.uid = ps.appId;
18764            }
18765
18766            if (outInfo != null && outInfo.removedChildPackages != null) {
18767                final int childCount = (ps.childPackageNames != null)
18768                        ? ps.childPackageNames.size() : 0;
18769                for (int i = 0; i < childCount; i++) {
18770                    String childPackageName = ps.childPackageNames.get(i);
18771                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18772                    if (childPs == null) {
18773                        return false;
18774                    }
18775                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18776                            childPackageName);
18777                    if (childInfo != null) {
18778                        childInfo.uid = childPs.appId;
18779                    }
18780                }
18781            }
18782        }
18783
18784        // Delete package data from internal structures and also remove data if flag is set
18785        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18786
18787        // Delete the child packages data
18788        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18789        for (int i = 0; i < childCount; i++) {
18790            PackageSetting childPs;
18791            synchronized (mPackages) {
18792                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18793            }
18794            if (childPs != null) {
18795                PackageRemovedInfo childOutInfo = (outInfo != null
18796                        && outInfo.removedChildPackages != null)
18797                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18798                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18799                        && (replacingPackage != null
18800                        && !replacingPackage.hasChildPackage(childPs.name))
18801                        ? flags & ~DELETE_KEEP_DATA : flags;
18802                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18803                        deleteFlags, writeSettings);
18804            }
18805        }
18806
18807        // Delete application code and resources only for parent packages
18808        if (ps.parentPackageName == null) {
18809            if (deleteCodeAndResources && (outInfo != null)) {
18810                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18811                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18812                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18813            }
18814        }
18815
18816        return true;
18817    }
18818
18819    @Override
18820    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18821            int userId) {
18822        mContext.enforceCallingOrSelfPermission(
18823                android.Manifest.permission.DELETE_PACKAGES, null);
18824        synchronized (mPackages) {
18825            // Cannot block uninstall of static shared libs as they are
18826            // considered a part of the using app (emulating static linking).
18827            // Also static libs are installed always on internal storage.
18828            PackageParser.Package pkg = mPackages.get(packageName);
18829            if (pkg != null && pkg.staticSharedLibName != null) {
18830                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18831                        + " providing static shared library: " + pkg.staticSharedLibName);
18832                return false;
18833            }
18834            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18835            mSettings.writePackageRestrictionsLPr(userId);
18836        }
18837        return true;
18838    }
18839
18840    @Override
18841    public boolean getBlockUninstallForUser(String packageName, int userId) {
18842        synchronized (mPackages) {
18843            final PackageSetting ps = mSettings.mPackages.get(packageName);
18844            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18845                return false;
18846            }
18847            return mSettings.getBlockUninstallLPr(userId, packageName);
18848        }
18849    }
18850
18851    @Override
18852    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18853        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18854        synchronized (mPackages) {
18855            PackageSetting ps = mSettings.mPackages.get(packageName);
18856            if (ps == null) {
18857                Log.w(TAG, "Package doesn't exist: " + packageName);
18858                return false;
18859            }
18860            if (systemUserApp) {
18861                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18862            } else {
18863                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18864            }
18865            mSettings.writeLPr();
18866        }
18867        return true;
18868    }
18869
18870    /*
18871     * This method handles package deletion in general
18872     */
18873    private boolean deletePackageLIF(String packageName, UserHandle user,
18874            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18875            PackageRemovedInfo outInfo, boolean writeSettings,
18876            PackageParser.Package replacingPackage) {
18877        if (packageName == null) {
18878            Slog.w(TAG, "Attempt to delete null packageName.");
18879            return false;
18880        }
18881
18882        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18883
18884        PackageSetting ps;
18885        synchronized (mPackages) {
18886            ps = mSettings.mPackages.get(packageName);
18887            if (ps == null) {
18888                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18889                return false;
18890            }
18891
18892            if (ps.parentPackageName != null && (!isSystemApp(ps)
18893                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18894                if (DEBUG_REMOVE) {
18895                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18896                            + ((user == null) ? UserHandle.USER_ALL : user));
18897                }
18898                final int removedUserId = (user != null) ? user.getIdentifier()
18899                        : UserHandle.USER_ALL;
18900
18901                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18902                    return false;
18903                }
18904                markPackageUninstalledForUserLPw(ps, user);
18905                scheduleWritePackageRestrictionsLocked(user);
18906                return true;
18907            }
18908        }
18909
18910        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
18911        if (ps.getPermissionsState().hasPermission(Manifest.permission.SUSPEND_APPS, userId)) {
18912            unsuspendForSuspendingPackage(packageName, userId);
18913        }
18914
18915
18916        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18917                && user.getIdentifier() != UserHandle.USER_ALL)) {
18918            // The caller is asking that the package only be deleted for a single
18919            // user.  To do this, we just mark its uninstalled state and delete
18920            // its data. If this is a system app, we only allow this to happen if
18921            // they have set the special DELETE_SYSTEM_APP which requests different
18922            // semantics than normal for uninstalling system apps.
18923            markPackageUninstalledForUserLPw(ps, user);
18924
18925            if (!isSystemApp(ps)) {
18926                // Do not uninstall the APK if an app should be cached
18927                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18928                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18929                    // Other user still have this package installed, so all
18930                    // we need to do is clear this user's data and save that
18931                    // it is uninstalled.
18932                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18933                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18934                        return false;
18935                    }
18936                    scheduleWritePackageRestrictionsLocked(user);
18937                    return true;
18938                } else {
18939                    // We need to set it back to 'installed' so the uninstall
18940                    // broadcasts will be sent correctly.
18941                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18942                    ps.setInstalled(true, user.getIdentifier());
18943                    mSettings.writeKernelMappingLPr(ps);
18944                }
18945            } else {
18946                // This is a system app, so we assume that the
18947                // other users still have this package installed, so all
18948                // we need to do is clear this user's data and save that
18949                // it is uninstalled.
18950                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18951                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18952                    return false;
18953                }
18954                scheduleWritePackageRestrictionsLocked(user);
18955                return true;
18956            }
18957        }
18958
18959        // If we are deleting a composite package for all users, keep track
18960        // of result for each child.
18961        if (ps.childPackageNames != null && outInfo != null) {
18962            synchronized (mPackages) {
18963                final int childCount = ps.childPackageNames.size();
18964                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18965                for (int i = 0; i < childCount; i++) {
18966                    String childPackageName = ps.childPackageNames.get(i);
18967                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18968                    childInfo.removedPackage = childPackageName;
18969                    childInfo.installerPackageName = ps.installerPackageName;
18970                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18971                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18972                    if (childPs != null) {
18973                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18974                    }
18975                }
18976            }
18977        }
18978
18979        boolean ret = false;
18980        if (isSystemApp(ps)) {
18981            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18982            // When an updated system application is deleted we delete the existing resources
18983            // as well and fall back to existing code in system partition
18984            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18985        } else {
18986            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18987            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18988                    outInfo, writeSettings, replacingPackage);
18989        }
18990
18991        // Take a note whether we deleted the package for all users
18992        if (outInfo != null) {
18993            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18994            if (outInfo.removedChildPackages != null) {
18995                synchronized (mPackages) {
18996                    final int childCount = outInfo.removedChildPackages.size();
18997                    for (int i = 0; i < childCount; i++) {
18998                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18999                        if (childInfo != null) {
19000                            childInfo.removedForAllUsers = mPackages.get(
19001                                    childInfo.removedPackage) == null;
19002                        }
19003                    }
19004                }
19005            }
19006            // If we uninstalled an update to a system app there may be some
19007            // child packages that appeared as they are declared in the system
19008            // app but were not declared in the update.
19009            if (isSystemApp(ps)) {
19010                synchronized (mPackages) {
19011                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19012                    final int childCount = (updatedPs.childPackageNames != null)
19013                            ? updatedPs.childPackageNames.size() : 0;
19014                    for (int i = 0; i < childCount; i++) {
19015                        String childPackageName = updatedPs.childPackageNames.get(i);
19016                        if (outInfo.removedChildPackages == null
19017                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19018                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19019                            if (childPs == null) {
19020                                continue;
19021                            }
19022                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19023                            installRes.name = childPackageName;
19024                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19025                            installRes.pkg = mPackages.get(childPackageName);
19026                            installRes.uid = childPs.pkg.applicationInfo.uid;
19027                            if (outInfo.appearedChildPackages == null) {
19028                                outInfo.appearedChildPackages = new ArrayMap<>();
19029                            }
19030                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19031                        }
19032                    }
19033                }
19034            }
19035        }
19036
19037        return ret;
19038    }
19039
19040    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19041        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19042                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19043        for (int nextUserId : userIds) {
19044            if (DEBUG_REMOVE) {
19045                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19046            }
19047            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19048                    false /*installed*/,
19049                    true /*stopped*/,
19050                    true /*notLaunched*/,
19051                    false /*hidden*/,
19052                    false /*suspended*/,
19053                    null /*suspendingPackage*/,
19054                    null /*dialogMessage*/,
19055                    null /*suspendedAppExtras*/,
19056                    null /*suspendedLauncherExtras*/,
19057                    false /*instantApp*/,
19058                    false /*virtualPreload*/,
19059                    null /*lastDisableAppCaller*/,
19060                    null /*enabledComponents*/,
19061                    null /*disabledComponents*/,
19062                    ps.readUserState(nextUserId).domainVerificationStatus,
19063                    0, PackageManager.INSTALL_REASON_UNKNOWN,
19064                    null /*harmfulAppWarning*/);
19065        }
19066        mSettings.writeKernelMappingLPr(ps);
19067    }
19068
19069    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19070            PackageRemovedInfo outInfo) {
19071        final PackageParser.Package pkg;
19072        synchronized (mPackages) {
19073            pkg = mPackages.get(ps.name);
19074        }
19075
19076        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19077                : new int[] {userId};
19078        for (int nextUserId : userIds) {
19079            if (DEBUG_REMOVE) {
19080                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19081                        + nextUserId);
19082            }
19083
19084            destroyAppDataLIF(pkg, userId,
19085                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19086            destroyAppProfilesLIF(pkg, userId);
19087            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19088            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19089            schedulePackageCleaning(ps.name, nextUserId, false);
19090            synchronized (mPackages) {
19091                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19092                    scheduleWritePackageRestrictionsLocked(nextUserId);
19093                }
19094                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19095            }
19096        }
19097
19098        if (outInfo != null) {
19099            outInfo.removedPackage = ps.name;
19100            outInfo.installerPackageName = ps.installerPackageName;
19101            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19102            outInfo.removedAppId = ps.appId;
19103            outInfo.removedUsers = userIds;
19104            outInfo.broadcastUsers = userIds;
19105        }
19106
19107        return true;
19108    }
19109
19110    private final class ClearStorageConnection implements ServiceConnection {
19111        IMediaContainerService mContainerService;
19112
19113        @Override
19114        public void onServiceConnected(ComponentName name, IBinder service) {
19115            synchronized (this) {
19116                mContainerService = IMediaContainerService.Stub
19117                        .asInterface(Binder.allowBlocking(service));
19118                notifyAll();
19119            }
19120        }
19121
19122        @Override
19123        public void onServiceDisconnected(ComponentName name) {
19124        }
19125    }
19126
19127    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19128        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19129
19130        final boolean mounted;
19131        if (Environment.isExternalStorageEmulated()) {
19132            mounted = true;
19133        } else {
19134            final String status = Environment.getExternalStorageState();
19135
19136            mounted = status.equals(Environment.MEDIA_MOUNTED)
19137                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19138        }
19139
19140        if (!mounted) {
19141            return;
19142        }
19143
19144        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19145        int[] users;
19146        if (userId == UserHandle.USER_ALL) {
19147            users = sUserManager.getUserIds();
19148        } else {
19149            users = new int[] { userId };
19150        }
19151        final ClearStorageConnection conn = new ClearStorageConnection();
19152        if (mContext.bindServiceAsUser(
19153                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19154            try {
19155                for (int curUser : users) {
19156                    long timeout = SystemClock.uptimeMillis() + 5000;
19157                    synchronized (conn) {
19158                        long now;
19159                        while (conn.mContainerService == null &&
19160                                (now = SystemClock.uptimeMillis()) < timeout) {
19161                            try {
19162                                conn.wait(timeout - now);
19163                            } catch (InterruptedException e) {
19164                            }
19165                        }
19166                    }
19167                    if (conn.mContainerService == null) {
19168                        return;
19169                    }
19170
19171                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19172                    clearDirectory(conn.mContainerService,
19173                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19174                    if (allData) {
19175                        clearDirectory(conn.mContainerService,
19176                                userEnv.buildExternalStorageAppDataDirs(packageName));
19177                        clearDirectory(conn.mContainerService,
19178                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19179                    }
19180                }
19181            } finally {
19182                mContext.unbindService(conn);
19183            }
19184        }
19185    }
19186
19187    @Override
19188    public void clearApplicationProfileData(String packageName) {
19189        enforceSystemOrRoot("Only the system can clear all profile data");
19190
19191        final PackageParser.Package pkg;
19192        synchronized (mPackages) {
19193            pkg = mPackages.get(packageName);
19194        }
19195
19196        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19197            synchronized (mInstallLock) {
19198                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19199            }
19200        }
19201    }
19202
19203    @Override
19204    public void clearApplicationUserData(final String packageName,
19205            final IPackageDataObserver observer, final int userId) {
19206        mContext.enforceCallingOrSelfPermission(
19207                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19208
19209        final int callingUid = Binder.getCallingUid();
19210        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19211                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19212
19213        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19214        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
19215        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19216            throw new SecurityException("Cannot clear data for a protected package: "
19217                    + packageName);
19218        }
19219        // Queue up an async operation since the package deletion may take a little while.
19220        mHandler.post(new Runnable() {
19221            public void run() {
19222                mHandler.removeCallbacks(this);
19223                final boolean succeeded;
19224                if (!filterApp) {
19225                    try (PackageFreezer freezer = freezePackage(packageName,
19226                            "clearApplicationUserData")) {
19227                        synchronized (mInstallLock) {
19228                            succeeded = clearApplicationUserDataLIF(packageName, userId);
19229                        }
19230                        clearExternalStorageDataSync(packageName, userId, true);
19231                        synchronized (mPackages) {
19232                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19233                                    packageName, userId);
19234                        }
19235                    }
19236                    if (succeeded) {
19237                        // invoke DeviceStorageMonitor's update method to clear any notifications
19238                        DeviceStorageMonitorInternal dsm = LocalServices
19239                                .getService(DeviceStorageMonitorInternal.class);
19240                        if (dsm != null) {
19241                            dsm.checkMemory();
19242                        }
19243                        if (checkPermission(Manifest.permission.SUSPEND_APPS, packageName, userId)
19244                                == PERMISSION_GRANTED) {
19245                            unsuspendForSuspendingPackage(packageName, userId);
19246                        }
19247                    }
19248                } else {
19249                    succeeded = false;
19250                }
19251                if (observer != null) {
19252                    try {
19253                        observer.onRemoveCompleted(packageName, succeeded);
19254                    } catch (RemoteException e) {
19255                        Log.i(TAG, "Observer no longer exists.");
19256                    }
19257                } //end if observer
19258            } //end run
19259        });
19260    }
19261
19262    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19263        if (packageName == null) {
19264            Slog.w(TAG, "Attempt to delete null packageName.");
19265            return false;
19266        }
19267
19268        // Try finding details about the requested package
19269        PackageParser.Package pkg;
19270        synchronized (mPackages) {
19271            pkg = mPackages.get(packageName);
19272            if (pkg == null) {
19273                final PackageSetting ps = mSettings.mPackages.get(packageName);
19274                if (ps != null) {
19275                    pkg = ps.pkg;
19276                }
19277            }
19278
19279            if (pkg == null) {
19280                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19281                return false;
19282            }
19283
19284            PackageSetting ps = (PackageSetting) pkg.mExtras;
19285            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19286        }
19287
19288        clearAppDataLIF(pkg, userId,
19289                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19290
19291        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19292        removeKeystoreDataIfNeeded(userId, appId);
19293
19294        UserManagerInternal umInternal = getUserManagerInternal();
19295        final int flags;
19296        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19297            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19298        } else if (umInternal.isUserRunning(userId)) {
19299            flags = StorageManager.FLAG_STORAGE_DE;
19300        } else {
19301            flags = 0;
19302        }
19303        prepareAppDataContentsLIF(pkg, userId, flags);
19304
19305        return true;
19306    }
19307
19308    /**
19309     * Reverts user permission state changes (permissions and flags) in
19310     * all packages for a given user.
19311     *
19312     * @param userId The device user for which to do a reset.
19313     */
19314    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19315        final int packageCount = mPackages.size();
19316        for (int i = 0; i < packageCount; i++) {
19317            PackageParser.Package pkg = mPackages.valueAt(i);
19318            PackageSetting ps = (PackageSetting) pkg.mExtras;
19319            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19320        }
19321    }
19322
19323    private void resetNetworkPolicies(int userId) {
19324        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19325    }
19326
19327    /**
19328     * Reverts user permission state changes (permissions and flags).
19329     *
19330     * @param ps The package for which to reset.
19331     * @param userId The device user for which to do a reset.
19332     */
19333    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19334            final PackageSetting ps, final int userId) {
19335        if (ps.pkg == null) {
19336            return;
19337        }
19338
19339        // These are flags that can change base on user actions.
19340        final int userSettableMask = FLAG_PERMISSION_USER_SET
19341                | FLAG_PERMISSION_USER_FIXED
19342                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19343                | FLAG_PERMISSION_REVIEW_REQUIRED;
19344
19345        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19346                | FLAG_PERMISSION_POLICY_FIXED;
19347
19348        boolean writeInstallPermissions = false;
19349        boolean writeRuntimePermissions = false;
19350
19351        final int permissionCount = ps.pkg.requestedPermissions.size();
19352        for (int i = 0; i < permissionCount; i++) {
19353            final String permName = ps.pkg.requestedPermissions.get(i);
19354            final BasePermission bp =
19355                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19356            if (bp == null) {
19357                continue;
19358            }
19359
19360            // If shared user we just reset the state to which only this app contributed.
19361            if (ps.sharedUser != null) {
19362                boolean used = false;
19363                final int packageCount = ps.sharedUser.packages.size();
19364                for (int j = 0; j < packageCount; j++) {
19365                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19366                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19367                            && pkg.pkg.requestedPermissions.contains(permName)) {
19368                        used = true;
19369                        break;
19370                    }
19371                }
19372                if (used) {
19373                    continue;
19374                }
19375            }
19376
19377            final PermissionsState permissionsState = ps.getPermissionsState();
19378
19379            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19380
19381            // Always clear the user settable flags.
19382            final boolean hasInstallState =
19383                    permissionsState.getInstallPermissionState(permName) != null;
19384            // If permission review is enabled and this is a legacy app, mark the
19385            // permission as requiring a review as this is the initial state.
19386            int flags = 0;
19387            if (mSettings.mPermissions.mPermissionReviewRequired
19388                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19389                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19390            }
19391            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19392                if (hasInstallState) {
19393                    writeInstallPermissions = true;
19394                } else {
19395                    writeRuntimePermissions = true;
19396                }
19397            }
19398
19399            // Below is only runtime permission handling.
19400            if (!bp.isRuntime()) {
19401                continue;
19402            }
19403
19404            // Never clobber system or policy.
19405            if ((oldFlags & policyOrSystemFlags) != 0) {
19406                continue;
19407            }
19408
19409            // If this permission was granted by default, make sure it is.
19410            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19411                if (permissionsState.grantRuntimePermission(bp, userId)
19412                        != PERMISSION_OPERATION_FAILURE) {
19413                    writeRuntimePermissions = true;
19414                }
19415            // If permission review is enabled the permissions for a legacy apps
19416            // are represented as constantly granted runtime ones, so don't revoke.
19417            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19418                // Otherwise, reset the permission.
19419                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19420                switch (revokeResult) {
19421                    case PERMISSION_OPERATION_SUCCESS:
19422                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19423                        writeRuntimePermissions = true;
19424                        final int appId = ps.appId;
19425                        mHandler.post(new Runnable() {
19426                            @Override
19427                            public void run() {
19428                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19429                            }
19430                        });
19431                    } break;
19432                }
19433            }
19434        }
19435
19436        // Synchronously write as we are taking permissions away.
19437        if (writeRuntimePermissions) {
19438            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19439        }
19440
19441        // Synchronously write as we are taking permissions away.
19442        if (writeInstallPermissions) {
19443            mSettings.writeLPr();
19444        }
19445    }
19446
19447    /**
19448     * Remove entries from the keystore daemon. Will only remove it if the
19449     * {@code appId} is valid.
19450     */
19451    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19452        if (appId < 0) {
19453            return;
19454        }
19455
19456        final KeyStore keyStore = KeyStore.getInstance();
19457        if (keyStore != null) {
19458            if (userId == UserHandle.USER_ALL) {
19459                for (final int individual : sUserManager.getUserIds()) {
19460                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19461                }
19462            } else {
19463                keyStore.clearUid(UserHandle.getUid(userId, appId));
19464            }
19465        } else {
19466            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19467        }
19468    }
19469
19470    @Override
19471    public void deleteApplicationCacheFiles(final String packageName,
19472            final IPackageDataObserver observer) {
19473        final int userId = UserHandle.getCallingUserId();
19474        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19475    }
19476
19477    @Override
19478    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19479            final IPackageDataObserver observer) {
19480        final int callingUid = Binder.getCallingUid();
19481        if (mContext.checkCallingOrSelfPermission(
19482                android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
19483                != PackageManager.PERMISSION_GRANTED) {
19484            // If the caller has the old delete cache permission, silently ignore.  Else throw.
19485            if (mContext.checkCallingOrSelfPermission(
19486                    android.Manifest.permission.DELETE_CACHE_FILES)
19487                    == PackageManager.PERMISSION_GRANTED) {
19488                Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
19489                        android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
19490                        ", silently ignoring");
19491                return;
19492            }
19493            mContext.enforceCallingOrSelfPermission(
19494                    android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
19495        }
19496        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19497                /* requireFullPermission= */ true, /* checkShell= */ false,
19498                "delete application cache files");
19499        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19500                android.Manifest.permission.ACCESS_INSTANT_APPS);
19501
19502        final PackageParser.Package pkg;
19503        synchronized (mPackages) {
19504            pkg = mPackages.get(packageName);
19505        }
19506
19507        // Queue up an async operation since the package deletion may take a little while.
19508        mHandler.post(new Runnable() {
19509            public void run() {
19510                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19511                boolean doClearData = true;
19512                if (ps != null) {
19513                    final boolean targetIsInstantApp =
19514                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19515                    doClearData = !targetIsInstantApp
19516                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19517                }
19518                if (doClearData) {
19519                    synchronized (mInstallLock) {
19520                        final int flags = StorageManager.FLAG_STORAGE_DE
19521                                | StorageManager.FLAG_STORAGE_CE;
19522                        // We're only clearing cache files, so we don't care if the
19523                        // app is unfrozen and still able to run
19524                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19525                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19526                    }
19527                    clearExternalStorageDataSync(packageName, userId, false);
19528                }
19529                if (observer != null) {
19530                    try {
19531                        observer.onRemoveCompleted(packageName, true);
19532                    } catch (RemoteException e) {
19533                        Log.i(TAG, "Observer no longer exists.");
19534                    }
19535                }
19536            }
19537        });
19538    }
19539
19540    @Override
19541    public void getPackageSizeInfo(final String packageName, int userHandle,
19542            final IPackageStatsObserver observer) {
19543        throw new UnsupportedOperationException(
19544                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19545    }
19546
19547    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19548        final PackageSetting ps;
19549        synchronized (mPackages) {
19550            ps = mSettings.mPackages.get(packageName);
19551            if (ps == null) {
19552                Slog.w(TAG, "Failed to find settings for " + packageName);
19553                return false;
19554            }
19555        }
19556
19557        final String[] packageNames = { packageName };
19558        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19559        final String[] codePaths = { ps.codePathString };
19560
19561        try {
19562            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19563                    ps.appId, ceDataInodes, codePaths, stats);
19564
19565            // For now, ignore code size of packages on system partition
19566            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19567                stats.codeSize = 0;
19568            }
19569
19570            // External clients expect these to be tracked separately
19571            stats.dataSize -= stats.cacheSize;
19572
19573        } catch (InstallerException e) {
19574            Slog.w(TAG, String.valueOf(e));
19575            return false;
19576        }
19577
19578        return true;
19579    }
19580
19581    private int getUidTargetSdkVersionLockedLPr(int uid) {
19582        Object obj = mSettings.getUserIdLPr(uid);
19583        if (obj instanceof SharedUserSetting) {
19584            final SharedUserSetting sus = (SharedUserSetting) obj;
19585            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19586            final Iterator<PackageSetting> it = sus.packages.iterator();
19587            while (it.hasNext()) {
19588                final PackageSetting ps = it.next();
19589                if (ps.pkg != null) {
19590                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19591                    if (v < vers) vers = v;
19592                }
19593            }
19594            return vers;
19595        } else if (obj instanceof PackageSetting) {
19596            final PackageSetting ps = (PackageSetting) obj;
19597            if (ps.pkg != null) {
19598                return ps.pkg.applicationInfo.targetSdkVersion;
19599            }
19600        }
19601        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19602    }
19603
19604    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19605        final PackageParser.Package p = mPackages.get(packageName);
19606        if (p != null) {
19607            return p.applicationInfo.targetSdkVersion;
19608        }
19609        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19610    }
19611
19612    @Override
19613    public void addPreferredActivity(IntentFilter filter, int match,
19614            ComponentName[] set, ComponentName activity, int userId) {
19615        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19616                "Adding preferred");
19617    }
19618
19619    private void addPreferredActivityInternal(IntentFilter filter, int match,
19620            ComponentName[] set, ComponentName activity, boolean always, int userId,
19621            String opname) {
19622        // writer
19623        int callingUid = Binder.getCallingUid();
19624        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19625                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19626        if (filter.countActions() == 0) {
19627            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19628            return;
19629        }
19630        synchronized (mPackages) {
19631            if (mContext.checkCallingOrSelfPermission(
19632                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19633                    != PackageManager.PERMISSION_GRANTED) {
19634                if (getUidTargetSdkVersionLockedLPr(callingUid)
19635                        < Build.VERSION_CODES.FROYO) {
19636                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19637                            + callingUid);
19638                    return;
19639                }
19640                mContext.enforceCallingOrSelfPermission(
19641                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19642            }
19643
19644            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19645            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19646                    + userId + ":");
19647            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19648            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19649            scheduleWritePackageRestrictionsLocked(userId);
19650            postPreferredActivityChangedBroadcast(userId);
19651        }
19652    }
19653
19654    private void postPreferredActivityChangedBroadcast(int userId) {
19655        mHandler.post(() -> {
19656            final IActivityManager am = ActivityManager.getService();
19657            if (am == null) {
19658                return;
19659            }
19660
19661            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19662            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19663            try {
19664                am.broadcastIntent(null, intent, null, null,
19665                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19666                        null, false, false, userId);
19667            } catch (RemoteException e) {
19668            }
19669        });
19670    }
19671
19672    @Override
19673    public void replacePreferredActivity(IntentFilter filter, int match,
19674            ComponentName[] set, ComponentName activity, int userId) {
19675        if (filter.countActions() != 1) {
19676            throw new IllegalArgumentException(
19677                    "replacePreferredActivity expects filter to have only 1 action.");
19678        }
19679        if (filter.countDataAuthorities() != 0
19680                || filter.countDataPaths() != 0
19681                || filter.countDataSchemes() > 1
19682                || filter.countDataTypes() != 0) {
19683            throw new IllegalArgumentException(
19684                    "replacePreferredActivity expects filter to have no data authorities, " +
19685                    "paths, or types; and at most one scheme.");
19686        }
19687
19688        final int callingUid = Binder.getCallingUid();
19689        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19690                true /* requireFullPermission */, false /* checkShell */,
19691                "replace preferred activity");
19692        synchronized (mPackages) {
19693            if (mContext.checkCallingOrSelfPermission(
19694                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19695                    != PackageManager.PERMISSION_GRANTED) {
19696                if (getUidTargetSdkVersionLockedLPr(callingUid)
19697                        < Build.VERSION_CODES.FROYO) {
19698                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19699                            + Binder.getCallingUid());
19700                    return;
19701                }
19702                mContext.enforceCallingOrSelfPermission(
19703                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19704            }
19705
19706            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19707            if (pir != null) {
19708                // Get all of the existing entries that exactly match this filter.
19709                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19710                if (existing != null && existing.size() == 1) {
19711                    PreferredActivity cur = existing.get(0);
19712                    if (DEBUG_PREFERRED) {
19713                        Slog.i(TAG, "Checking replace of preferred:");
19714                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19715                        if (!cur.mPref.mAlways) {
19716                            Slog.i(TAG, "  -- CUR; not mAlways!");
19717                        } else {
19718                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19719                            Slog.i(TAG, "  -- CUR: mSet="
19720                                    + Arrays.toString(cur.mPref.mSetComponents));
19721                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19722                            Slog.i(TAG, "  -- NEW: mMatch="
19723                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19724                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19725                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19726                        }
19727                    }
19728                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19729                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19730                            && cur.mPref.sameSet(set)) {
19731                        // Setting the preferred activity to what it happens to be already
19732                        if (DEBUG_PREFERRED) {
19733                            Slog.i(TAG, "Replacing with same preferred activity "
19734                                    + cur.mPref.mShortComponent + " for user "
19735                                    + userId + ":");
19736                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19737                        }
19738                        return;
19739                    }
19740                }
19741
19742                if (existing != null) {
19743                    if (DEBUG_PREFERRED) {
19744                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19745                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19746                    }
19747                    for (int i = 0; i < existing.size(); i++) {
19748                        PreferredActivity pa = existing.get(i);
19749                        if (DEBUG_PREFERRED) {
19750                            Slog.i(TAG, "Removing existing preferred activity "
19751                                    + pa.mPref.mComponent + ":");
19752                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19753                        }
19754                        pir.removeFilter(pa);
19755                    }
19756                }
19757            }
19758            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19759                    "Replacing preferred");
19760        }
19761    }
19762
19763    @Override
19764    public void clearPackagePreferredActivities(String packageName) {
19765        final int callingUid = Binder.getCallingUid();
19766        if (getInstantAppPackageName(callingUid) != null) {
19767            return;
19768        }
19769        // writer
19770        synchronized (mPackages) {
19771            PackageParser.Package pkg = mPackages.get(packageName);
19772            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19773                if (mContext.checkCallingOrSelfPermission(
19774                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19775                        != PackageManager.PERMISSION_GRANTED) {
19776                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19777                            < Build.VERSION_CODES.FROYO) {
19778                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19779                                + callingUid);
19780                        return;
19781                    }
19782                    mContext.enforceCallingOrSelfPermission(
19783                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19784                }
19785            }
19786            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19787            if (ps != null
19788                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19789                return;
19790            }
19791            int user = UserHandle.getCallingUserId();
19792            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19793                scheduleWritePackageRestrictionsLocked(user);
19794            }
19795        }
19796    }
19797
19798    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19799    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19800        ArrayList<PreferredActivity> removed = null;
19801        boolean changed = false;
19802        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19803            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19804            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19805            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19806                continue;
19807            }
19808            Iterator<PreferredActivity> it = pir.filterIterator();
19809            while (it.hasNext()) {
19810                PreferredActivity pa = it.next();
19811                // Mark entry for removal only if it matches the package name
19812                // and the entry is of type "always".
19813                if (packageName == null ||
19814                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19815                                && pa.mPref.mAlways)) {
19816                    if (removed == null) {
19817                        removed = new ArrayList<PreferredActivity>();
19818                    }
19819                    removed.add(pa);
19820                }
19821            }
19822            if (removed != null) {
19823                for (int j=0; j<removed.size(); j++) {
19824                    PreferredActivity pa = removed.get(j);
19825                    pir.removeFilter(pa);
19826                }
19827                changed = true;
19828            }
19829        }
19830        if (changed) {
19831            postPreferredActivityChangedBroadcast(userId);
19832        }
19833        return changed;
19834    }
19835
19836    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19837    private void clearIntentFilterVerificationsLPw(int userId) {
19838        final int packageCount = mPackages.size();
19839        for (int i = 0; i < packageCount; i++) {
19840            PackageParser.Package pkg = mPackages.valueAt(i);
19841            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19842        }
19843    }
19844
19845    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19846    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19847        if (userId == UserHandle.USER_ALL) {
19848            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19849                    sUserManager.getUserIds())) {
19850                for (int oneUserId : sUserManager.getUserIds()) {
19851                    scheduleWritePackageRestrictionsLocked(oneUserId);
19852                }
19853            }
19854        } else {
19855            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19856                scheduleWritePackageRestrictionsLocked(userId);
19857            }
19858        }
19859    }
19860
19861    /** Clears state for all users, and touches intent filter verification policy */
19862    void clearDefaultBrowserIfNeeded(String packageName) {
19863        for (int oneUserId : sUserManager.getUserIds()) {
19864            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19865        }
19866    }
19867
19868    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19869        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19870        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19871            if (packageName.equals(defaultBrowserPackageName)) {
19872                setDefaultBrowserPackageName(null, userId);
19873            }
19874        }
19875    }
19876
19877    @Override
19878    public void resetApplicationPreferences(int userId) {
19879        mContext.enforceCallingOrSelfPermission(
19880                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19881        final long identity = Binder.clearCallingIdentity();
19882        // writer
19883        try {
19884            synchronized (mPackages) {
19885                clearPackagePreferredActivitiesLPw(null, userId);
19886                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19887                // TODO: We have to reset the default SMS and Phone. This requires
19888                // significant refactoring to keep all default apps in the package
19889                // manager (cleaner but more work) or have the services provide
19890                // callbacks to the package manager to request a default app reset.
19891                applyFactoryDefaultBrowserLPw(userId);
19892                clearIntentFilterVerificationsLPw(userId);
19893                primeDomainVerificationsLPw(userId);
19894                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19895                scheduleWritePackageRestrictionsLocked(userId);
19896            }
19897            resetNetworkPolicies(userId);
19898        } finally {
19899            Binder.restoreCallingIdentity(identity);
19900        }
19901    }
19902
19903    @Override
19904    public int getPreferredActivities(List<IntentFilter> outFilters,
19905            List<ComponentName> outActivities, String packageName) {
19906        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19907            return 0;
19908        }
19909        int num = 0;
19910        final int userId = UserHandle.getCallingUserId();
19911        // reader
19912        synchronized (mPackages) {
19913            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19914            if (pir != null) {
19915                final Iterator<PreferredActivity> it = pir.filterIterator();
19916                while (it.hasNext()) {
19917                    final PreferredActivity pa = it.next();
19918                    if (packageName == null
19919                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19920                                    && pa.mPref.mAlways)) {
19921                        if (outFilters != null) {
19922                            outFilters.add(new IntentFilter(pa));
19923                        }
19924                        if (outActivities != null) {
19925                            outActivities.add(pa.mPref.mComponent);
19926                        }
19927                    }
19928                }
19929            }
19930        }
19931
19932        return num;
19933    }
19934
19935    @Override
19936    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19937            int userId) {
19938        int callingUid = Binder.getCallingUid();
19939        if (callingUid != Process.SYSTEM_UID) {
19940            throw new SecurityException(
19941                    "addPersistentPreferredActivity can only be run by the system");
19942        }
19943        if (filter.countActions() == 0) {
19944            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19945            return;
19946        }
19947        synchronized (mPackages) {
19948            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19949                    ":");
19950            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19951            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19952                    new PersistentPreferredActivity(filter, activity));
19953            scheduleWritePackageRestrictionsLocked(userId);
19954            postPreferredActivityChangedBroadcast(userId);
19955        }
19956    }
19957
19958    @Override
19959    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19960        int callingUid = Binder.getCallingUid();
19961        if (callingUid != Process.SYSTEM_UID) {
19962            throw new SecurityException(
19963                    "clearPackagePersistentPreferredActivities can only be run by the system");
19964        }
19965        ArrayList<PersistentPreferredActivity> removed = null;
19966        boolean changed = false;
19967        synchronized (mPackages) {
19968            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19969                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19970                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19971                        .valueAt(i);
19972                if (userId != thisUserId) {
19973                    continue;
19974                }
19975                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19976                while (it.hasNext()) {
19977                    PersistentPreferredActivity ppa = it.next();
19978                    // Mark entry for removal only if it matches the package name.
19979                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19980                        if (removed == null) {
19981                            removed = new ArrayList<PersistentPreferredActivity>();
19982                        }
19983                        removed.add(ppa);
19984                    }
19985                }
19986                if (removed != null) {
19987                    for (int j=0; j<removed.size(); j++) {
19988                        PersistentPreferredActivity ppa = removed.get(j);
19989                        ppir.removeFilter(ppa);
19990                    }
19991                    changed = true;
19992                }
19993            }
19994
19995            if (changed) {
19996                scheduleWritePackageRestrictionsLocked(userId);
19997                postPreferredActivityChangedBroadcast(userId);
19998            }
19999        }
20000    }
20001
20002    /**
20003     * Common machinery for picking apart a restored XML blob and passing
20004     * it to a caller-supplied functor to be applied to the running system.
20005     */
20006    private void restoreFromXml(XmlPullParser parser, int userId,
20007            String expectedStartTag, BlobXmlRestorer functor)
20008            throws IOException, XmlPullParserException {
20009        int type;
20010        while ((type = parser.next()) != XmlPullParser.START_TAG
20011                && type != XmlPullParser.END_DOCUMENT) {
20012        }
20013        if (type != XmlPullParser.START_TAG) {
20014            // oops didn't find a start tag?!
20015            if (DEBUG_BACKUP) {
20016                Slog.e(TAG, "Didn't find start tag during restore");
20017            }
20018            return;
20019        }
20020Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20021        // this is supposed to be TAG_PREFERRED_BACKUP
20022        if (!expectedStartTag.equals(parser.getName())) {
20023            if (DEBUG_BACKUP) {
20024                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20025            }
20026            return;
20027        }
20028
20029        // skip interfering stuff, then we're aligned with the backing implementation
20030        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20031Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20032        functor.apply(parser, userId);
20033    }
20034
20035    private interface BlobXmlRestorer {
20036        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20037    }
20038
20039    /**
20040     * Non-Binder method, support for the backup/restore mechanism: write the
20041     * full set of preferred activities in its canonical XML format.  Returns the
20042     * XML output as a byte array, or null if there is none.
20043     */
20044    @Override
20045    public byte[] getPreferredActivityBackup(int userId) {
20046        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20047            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20048        }
20049
20050        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20051        try {
20052            final XmlSerializer serializer = new FastXmlSerializer();
20053            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20054            serializer.startDocument(null, true);
20055            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20056
20057            synchronized (mPackages) {
20058                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20059            }
20060
20061            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20062            serializer.endDocument();
20063            serializer.flush();
20064        } catch (Exception e) {
20065            if (DEBUG_BACKUP) {
20066                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20067            }
20068            return null;
20069        }
20070
20071        return dataStream.toByteArray();
20072    }
20073
20074    @Override
20075    public void restorePreferredActivities(byte[] backup, int userId) {
20076        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20077            throw new SecurityException("Only the system may call restorePreferredActivities()");
20078        }
20079
20080        try {
20081            final XmlPullParser parser = Xml.newPullParser();
20082            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20083            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20084                    new BlobXmlRestorer() {
20085                        @Override
20086                        public void apply(XmlPullParser parser, int userId)
20087                                throws XmlPullParserException, IOException {
20088                            synchronized (mPackages) {
20089                                mSettings.readPreferredActivitiesLPw(parser, userId);
20090                            }
20091                        }
20092                    } );
20093        } catch (Exception e) {
20094            if (DEBUG_BACKUP) {
20095                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20096            }
20097        }
20098    }
20099
20100    /**
20101     * Non-Binder method, support for the backup/restore mechanism: write the
20102     * default browser (etc) settings in its canonical XML format.  Returns the default
20103     * browser XML representation as a byte array, or null if there is none.
20104     */
20105    @Override
20106    public byte[] getDefaultAppsBackup(int userId) {
20107        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20108            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20109        }
20110
20111        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20112        try {
20113            final XmlSerializer serializer = new FastXmlSerializer();
20114            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20115            serializer.startDocument(null, true);
20116            serializer.startTag(null, TAG_DEFAULT_APPS);
20117
20118            synchronized (mPackages) {
20119                mSettings.writeDefaultAppsLPr(serializer, userId);
20120            }
20121
20122            serializer.endTag(null, TAG_DEFAULT_APPS);
20123            serializer.endDocument();
20124            serializer.flush();
20125        } catch (Exception e) {
20126            if (DEBUG_BACKUP) {
20127                Slog.e(TAG, "Unable to write default apps for backup", e);
20128            }
20129            return null;
20130        }
20131
20132        return dataStream.toByteArray();
20133    }
20134
20135    @Override
20136    public void restoreDefaultApps(byte[] backup, int userId) {
20137        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20138            throw new SecurityException("Only the system may call restoreDefaultApps()");
20139        }
20140
20141        try {
20142            final XmlPullParser parser = Xml.newPullParser();
20143            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20144            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20145                    new BlobXmlRestorer() {
20146                        @Override
20147                        public void apply(XmlPullParser parser, int userId)
20148                                throws XmlPullParserException, IOException {
20149                            synchronized (mPackages) {
20150                                mSettings.readDefaultAppsLPw(parser, userId);
20151                            }
20152                        }
20153                    } );
20154        } catch (Exception e) {
20155            if (DEBUG_BACKUP) {
20156                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20157            }
20158        }
20159    }
20160
20161    @Override
20162    public byte[] getIntentFilterVerificationBackup(int userId) {
20163        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20164            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20165        }
20166
20167        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20168        try {
20169            final XmlSerializer serializer = new FastXmlSerializer();
20170            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20171            serializer.startDocument(null, true);
20172            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20173
20174            synchronized (mPackages) {
20175                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20176            }
20177
20178            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20179            serializer.endDocument();
20180            serializer.flush();
20181        } catch (Exception e) {
20182            if (DEBUG_BACKUP) {
20183                Slog.e(TAG, "Unable to write default apps for backup", e);
20184            }
20185            return null;
20186        }
20187
20188        return dataStream.toByteArray();
20189    }
20190
20191    @Override
20192    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20193        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20194            throw new SecurityException("Only the system may call restorePreferredActivities()");
20195        }
20196
20197        try {
20198            final XmlPullParser parser = Xml.newPullParser();
20199            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20200            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20201                    new BlobXmlRestorer() {
20202                        @Override
20203                        public void apply(XmlPullParser parser, int userId)
20204                                throws XmlPullParserException, IOException {
20205                            synchronized (mPackages) {
20206                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20207                                mSettings.writeLPr();
20208                            }
20209                        }
20210                    } );
20211        } catch (Exception e) {
20212            if (DEBUG_BACKUP) {
20213                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20214            }
20215        }
20216    }
20217
20218    @Override
20219    public byte[] getPermissionGrantBackup(int userId) {
20220        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20221            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20222        }
20223
20224        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20225        try {
20226            final XmlSerializer serializer = new FastXmlSerializer();
20227            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20228            serializer.startDocument(null, true);
20229            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20230
20231            synchronized (mPackages) {
20232                serializeRuntimePermissionGrantsLPr(serializer, userId);
20233            }
20234
20235            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20236            serializer.endDocument();
20237            serializer.flush();
20238        } catch (Exception e) {
20239            if (DEBUG_BACKUP) {
20240                Slog.e(TAG, "Unable to write default apps for backup", e);
20241            }
20242            return null;
20243        }
20244
20245        return dataStream.toByteArray();
20246    }
20247
20248    @Override
20249    public void restorePermissionGrants(byte[] backup, int userId) {
20250        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20251            throw new SecurityException("Only the system may call restorePermissionGrants()");
20252        }
20253
20254        try {
20255            final XmlPullParser parser = Xml.newPullParser();
20256            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20257            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20258                    new BlobXmlRestorer() {
20259                        @Override
20260                        public void apply(XmlPullParser parser, int userId)
20261                                throws XmlPullParserException, IOException {
20262                            synchronized (mPackages) {
20263                                processRestoredPermissionGrantsLPr(parser, userId);
20264                            }
20265                        }
20266                    } );
20267        } catch (Exception e) {
20268            if (DEBUG_BACKUP) {
20269                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20270            }
20271        }
20272    }
20273
20274    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20275            throws IOException {
20276        serializer.startTag(null, TAG_ALL_GRANTS);
20277
20278        final int N = mSettings.mPackages.size();
20279        for (int i = 0; i < N; i++) {
20280            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20281            boolean pkgGrantsKnown = false;
20282
20283            PermissionsState packagePerms = ps.getPermissionsState();
20284
20285            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20286                final int grantFlags = state.getFlags();
20287                // only look at grants that are not system/policy fixed
20288                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20289                    final boolean isGranted = state.isGranted();
20290                    // And only back up the user-twiddled state bits
20291                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20292                        final String packageName = mSettings.mPackages.keyAt(i);
20293                        if (!pkgGrantsKnown) {
20294                            serializer.startTag(null, TAG_GRANT);
20295                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20296                            pkgGrantsKnown = true;
20297                        }
20298
20299                        final boolean userSet =
20300                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20301                        final boolean userFixed =
20302                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20303                        final boolean revoke =
20304                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20305
20306                        serializer.startTag(null, TAG_PERMISSION);
20307                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20308                        if (isGranted) {
20309                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20310                        }
20311                        if (userSet) {
20312                            serializer.attribute(null, ATTR_USER_SET, "true");
20313                        }
20314                        if (userFixed) {
20315                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20316                        }
20317                        if (revoke) {
20318                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20319                        }
20320                        serializer.endTag(null, TAG_PERMISSION);
20321                    }
20322                }
20323            }
20324
20325            if (pkgGrantsKnown) {
20326                serializer.endTag(null, TAG_GRANT);
20327            }
20328        }
20329
20330        serializer.endTag(null, TAG_ALL_GRANTS);
20331    }
20332
20333    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20334            throws XmlPullParserException, IOException {
20335        String pkgName = null;
20336        int outerDepth = parser.getDepth();
20337        int type;
20338        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20339                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20340            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20341                continue;
20342            }
20343
20344            final String tagName = parser.getName();
20345            if (tagName.equals(TAG_GRANT)) {
20346                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20347                if (DEBUG_BACKUP) {
20348                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20349                }
20350            } else if (tagName.equals(TAG_PERMISSION)) {
20351
20352                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20353                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20354
20355                int newFlagSet = 0;
20356                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20357                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20358                }
20359                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20360                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20361                }
20362                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20363                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20364                }
20365                if (DEBUG_BACKUP) {
20366                    Slog.v(TAG, "  + Restoring grant:"
20367                            + " pkg=" + pkgName
20368                            + " perm=" + permName
20369                            + " granted=" + isGranted
20370                            + " bits=0x" + Integer.toHexString(newFlagSet));
20371                }
20372                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20373                if (ps != null) {
20374                    // Already installed so we apply the grant immediately
20375                    if (DEBUG_BACKUP) {
20376                        Slog.v(TAG, "        + already installed; applying");
20377                    }
20378                    PermissionsState perms = ps.getPermissionsState();
20379                    BasePermission bp =
20380                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20381                    if (bp != null) {
20382                        if (isGranted) {
20383                            perms.grantRuntimePermission(bp, userId);
20384                        }
20385                        if (newFlagSet != 0) {
20386                            perms.updatePermissionFlags(
20387                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20388                        }
20389                    }
20390                } else {
20391                    // Need to wait for post-restore install to apply the grant
20392                    if (DEBUG_BACKUP) {
20393                        Slog.v(TAG, "        - not yet installed; saving for later");
20394                    }
20395                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20396                            isGranted, newFlagSet, userId);
20397                }
20398            } else {
20399                PackageManagerService.reportSettingsProblem(Log.WARN,
20400                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20401                XmlUtils.skipCurrentTag(parser);
20402            }
20403        }
20404
20405        scheduleWriteSettingsLocked();
20406        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20407    }
20408
20409    @Override
20410    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20411            int sourceUserId, int targetUserId, int flags) {
20412        mContext.enforceCallingOrSelfPermission(
20413                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20414        int callingUid = Binder.getCallingUid();
20415        enforceOwnerRights(ownerPackage, callingUid);
20416        PackageManagerServiceUtils.enforceShellRestriction(
20417                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20418        if (intentFilter.countActions() == 0) {
20419            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20420            return;
20421        }
20422        synchronized (mPackages) {
20423            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20424                    ownerPackage, targetUserId, flags);
20425            CrossProfileIntentResolver resolver =
20426                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20427            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20428            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20429            if (existing != null) {
20430                int size = existing.size();
20431                for (int i = 0; i < size; i++) {
20432                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20433                        return;
20434                    }
20435                }
20436            }
20437            resolver.addFilter(newFilter);
20438            scheduleWritePackageRestrictionsLocked(sourceUserId);
20439        }
20440    }
20441
20442    @Override
20443    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20444        mContext.enforceCallingOrSelfPermission(
20445                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20446        final int callingUid = Binder.getCallingUid();
20447        enforceOwnerRights(ownerPackage, callingUid);
20448        PackageManagerServiceUtils.enforceShellRestriction(
20449                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20450        synchronized (mPackages) {
20451            CrossProfileIntentResolver resolver =
20452                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20453            ArraySet<CrossProfileIntentFilter> set =
20454                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20455            for (CrossProfileIntentFilter filter : set) {
20456                if (filter.getOwnerPackage().equals(ownerPackage)) {
20457                    resolver.removeFilter(filter);
20458                }
20459            }
20460            scheduleWritePackageRestrictionsLocked(sourceUserId);
20461        }
20462    }
20463
20464    // Enforcing that callingUid is owning pkg on userId
20465    private void enforceOwnerRights(String pkg, int callingUid) {
20466        // The system owns everything.
20467        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20468            return;
20469        }
20470        final int callingUserId = UserHandle.getUserId(callingUid);
20471        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20472        if (pi == null) {
20473            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20474                    + callingUserId);
20475        }
20476        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20477            throw new SecurityException("Calling uid " + callingUid
20478                    + " does not own package " + pkg);
20479        }
20480    }
20481
20482    @Override
20483    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20484        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20485            return null;
20486        }
20487        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20488    }
20489
20490    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20491        UserManagerService ums = UserManagerService.getInstance();
20492        if (ums != null) {
20493            final UserInfo parent = ums.getProfileParent(userId);
20494            final int launcherUid = (parent != null) ? parent.id : userId;
20495            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20496            if (launcherComponent != null) {
20497                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20498                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20499                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20500                        .setPackage(launcherComponent.getPackageName());
20501                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20502            }
20503        }
20504    }
20505
20506    /**
20507     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20508     * then reports the most likely home activity or null if there are more than one.
20509     */
20510    private ComponentName getDefaultHomeActivity(int userId) {
20511        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20512        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20513        if (cn != null) {
20514            return cn;
20515        }
20516
20517        // Find the launcher with the highest priority and return that component if there are no
20518        // other home activity with the same priority.
20519        int lastPriority = Integer.MIN_VALUE;
20520        ComponentName lastComponent = null;
20521        final int size = allHomeCandidates.size();
20522        for (int i = 0; i < size; i++) {
20523            final ResolveInfo ri = allHomeCandidates.get(i);
20524            if (ri.priority > lastPriority) {
20525                lastComponent = ri.activityInfo.getComponentName();
20526                lastPriority = ri.priority;
20527            } else if (ri.priority == lastPriority) {
20528                // Two components found with same priority.
20529                lastComponent = null;
20530            }
20531        }
20532        return lastComponent;
20533    }
20534
20535    private Intent getHomeIntent() {
20536        Intent intent = new Intent(Intent.ACTION_MAIN);
20537        intent.addCategory(Intent.CATEGORY_HOME);
20538        intent.addCategory(Intent.CATEGORY_DEFAULT);
20539        return intent;
20540    }
20541
20542    private IntentFilter getHomeFilter() {
20543        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20544        filter.addCategory(Intent.CATEGORY_HOME);
20545        filter.addCategory(Intent.CATEGORY_DEFAULT);
20546        return filter;
20547    }
20548
20549    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20550            int userId) {
20551        Intent intent  = getHomeIntent();
20552        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20553                PackageManager.GET_META_DATA, userId);
20554        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20555                true, false, false, userId);
20556
20557        allHomeCandidates.clear();
20558        if (list != null) {
20559            for (ResolveInfo ri : list) {
20560                allHomeCandidates.add(ri);
20561            }
20562        }
20563        return (preferred == null || preferred.activityInfo == null)
20564                ? null
20565                : new ComponentName(preferred.activityInfo.packageName,
20566                        preferred.activityInfo.name);
20567    }
20568
20569    @Override
20570    public void setHomeActivity(ComponentName comp, int userId) {
20571        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20572            return;
20573        }
20574        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20575        getHomeActivitiesAsUser(homeActivities, userId);
20576
20577        boolean found = false;
20578
20579        final int size = homeActivities.size();
20580        final ComponentName[] set = new ComponentName[size];
20581        for (int i = 0; i < size; i++) {
20582            final ResolveInfo candidate = homeActivities.get(i);
20583            final ActivityInfo info = candidate.activityInfo;
20584            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20585            set[i] = activityName;
20586            if (!found && activityName.equals(comp)) {
20587                found = true;
20588            }
20589        }
20590        if (!found) {
20591            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20592                    + userId);
20593        }
20594        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20595                set, comp, userId);
20596    }
20597
20598    private @Nullable String getSetupWizardPackageName() {
20599        final Intent intent = new Intent(Intent.ACTION_MAIN);
20600        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20601
20602        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20603                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20604                        | MATCH_DISABLED_COMPONENTS,
20605                UserHandle.myUserId());
20606        if (matches.size() == 1) {
20607            return matches.get(0).getComponentInfo().packageName;
20608        } else {
20609            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20610                    + ": matches=" + matches);
20611            return null;
20612        }
20613    }
20614
20615    private @Nullable String getStorageManagerPackageName() {
20616        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20617
20618        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20619                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20620                        | MATCH_DISABLED_COMPONENTS,
20621                UserHandle.myUserId());
20622        if (matches.size() == 1) {
20623            return matches.get(0).getComponentInfo().packageName;
20624        } else {
20625            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20626                    + matches.size() + ": matches=" + matches);
20627            return null;
20628        }
20629    }
20630
20631    @Override
20632    public String getSystemTextClassifierPackageName() {
20633        return mContext.getString(R.string.config_defaultTextClassifierPackage);
20634    }
20635
20636    @Override
20637    public void setApplicationEnabledSetting(String appPackageName,
20638            int newState, int flags, int userId, String callingPackage) {
20639        if (!sUserManager.exists(userId)) return;
20640        if (callingPackage == null) {
20641            callingPackage = Integer.toString(Binder.getCallingUid());
20642        }
20643        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20644    }
20645
20646    @Override
20647    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20648        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20649        synchronized (mPackages) {
20650            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20651            if (pkgSetting != null) {
20652                pkgSetting.setUpdateAvailable(updateAvailable);
20653            }
20654        }
20655    }
20656
20657    @Override
20658    public void setComponentEnabledSetting(ComponentName componentName,
20659            int newState, int flags, int userId) {
20660        if (!sUserManager.exists(userId)) return;
20661        setEnabledSetting(componentName.getPackageName(),
20662                componentName.getClassName(), newState, flags, userId, null);
20663    }
20664
20665    private void setEnabledSetting(final String packageName, String className, int newState,
20666            final int flags, int userId, String callingPackage) {
20667        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20668              || newState == COMPONENT_ENABLED_STATE_ENABLED
20669              || newState == COMPONENT_ENABLED_STATE_DISABLED
20670              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20671              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20672            throw new IllegalArgumentException("Invalid new component state: "
20673                    + newState);
20674        }
20675        PackageSetting pkgSetting;
20676        final int callingUid = Binder.getCallingUid();
20677        final int permission;
20678        if (callingUid == Process.SYSTEM_UID) {
20679            permission = PackageManager.PERMISSION_GRANTED;
20680        } else {
20681            permission = mContext.checkCallingOrSelfPermission(
20682                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20683        }
20684        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20685                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20686        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20687        boolean sendNow = false;
20688        boolean isApp = (className == null);
20689        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20690        String componentName = isApp ? packageName : className;
20691        int packageUid = -1;
20692        ArrayList<String> components;
20693
20694        // reader
20695        synchronized (mPackages) {
20696            pkgSetting = mSettings.mPackages.get(packageName);
20697            if (pkgSetting == null) {
20698                if (!isCallerInstantApp) {
20699                    if (className == null) {
20700                        throw new IllegalArgumentException("Unknown package: " + packageName);
20701                    }
20702                    throw new IllegalArgumentException(
20703                            "Unknown component: " + packageName + "/" + className);
20704                } else {
20705                    // throw SecurityException to prevent leaking package information
20706                    throw new SecurityException(
20707                            "Attempt to change component state; "
20708                            + "pid=" + Binder.getCallingPid()
20709                            + ", uid=" + callingUid
20710                            + (className == null
20711                                    ? ", package=" + packageName
20712                                    : ", component=" + packageName + "/" + className));
20713                }
20714            }
20715        }
20716
20717        // Limit who can change which apps
20718        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20719            // Don't allow apps that don't have permission to modify other apps
20720            if (!allowedByPermission
20721                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20722                throw new SecurityException(
20723                        "Attempt to change component state; "
20724                        + "pid=" + Binder.getCallingPid()
20725                        + ", uid=" + callingUid
20726                        + (className == null
20727                                ? ", package=" + packageName
20728                                : ", component=" + packageName + "/" + className));
20729            }
20730            // Don't allow changing protected packages.
20731            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20732                throw new SecurityException("Cannot disable a protected package: " + packageName);
20733            }
20734        }
20735
20736        synchronized (mPackages) {
20737            if (callingUid == Process.SHELL_UID
20738                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20739                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20740                // unless it is a test package.
20741                int oldState = pkgSetting.getEnabled(userId);
20742                if (className == null
20743                        &&
20744                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20745                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20746                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20747                        &&
20748                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20749                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20750                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20751                    // ok
20752                } else {
20753                    throw new SecurityException(
20754                            "Shell cannot change component state for " + packageName + "/"
20755                                    + className + " to " + newState);
20756                }
20757            }
20758        }
20759        if (className == null) {
20760            // We're dealing with an application/package level state change
20761            synchronized (mPackages) {
20762                if (pkgSetting.getEnabled(userId) == newState) {
20763                    // Nothing to do
20764                    return;
20765                }
20766            }
20767            // If we're enabling a system stub, there's a little more work to do.
20768            // Prior to enabling the package, we need to decompress the APK(s) to the
20769            // data partition and then replace the version on the system partition.
20770            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20771            final boolean isSystemStub = deletedPkg.isStub
20772                    && deletedPkg.isSystem();
20773            if (isSystemStub
20774                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20775                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20776                final File codePath = decompressPackage(deletedPkg);
20777                if (codePath == null) {
20778                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20779                    return;
20780                }
20781                // TODO remove direct parsing of the package object during internal cleanup
20782                // of scan package
20783                // We need to call parse directly here for no other reason than we need
20784                // the new package in order to disable the old one [we use the information
20785                // for some internal optimization to optionally create a new package setting
20786                // object on replace]. However, we can't get the package from the scan
20787                // because the scan modifies live structures and we need to remove the
20788                // old [system] package from the system before a scan can be attempted.
20789                // Once scan is indempotent we can remove this parse and use the package
20790                // object we scanned, prior to adding it to package settings.
20791                final PackageParser pp = new PackageParser();
20792                pp.setSeparateProcesses(mSeparateProcesses);
20793                pp.setDisplayMetrics(mMetrics);
20794                pp.setCallback(mPackageParserCallback);
20795                final PackageParser.Package tmpPkg;
20796                try {
20797                    final @ParseFlags int parseFlags = mDefParseFlags
20798                            | PackageParser.PARSE_MUST_BE_APK
20799                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20800                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20801                } catch (PackageParserException e) {
20802                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20803                    return;
20804                }
20805                synchronized (mInstallLock) {
20806                    // Disable the stub and remove any package entries
20807                    removePackageLI(deletedPkg, true);
20808                    synchronized (mPackages) {
20809                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20810                    }
20811                    final PackageParser.Package pkg;
20812                    try (PackageFreezer freezer =
20813                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20814                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20815                                | PackageParser.PARSE_ENFORCE_CODE;
20816                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20817                                0 /*currentTime*/, null /*user*/);
20818                        prepareAppDataAfterInstallLIF(pkg);
20819                        synchronized (mPackages) {
20820                            try {
20821                                updateSharedLibrariesLPr(pkg, null);
20822                            } catch (PackageManagerException e) {
20823                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20824                            }
20825                            mPermissionManager.updatePermissions(
20826                                    pkg.packageName, pkg, true, mPackages.values(),
20827                                    mPermissionCallback);
20828                            mSettings.writeLPr();
20829                        }
20830                    } catch (PackageManagerException e) {
20831                        // Whoops! Something went wrong; try to roll back to the stub
20832                        Slog.w(TAG, "Failed to install compressed system package:"
20833                                + pkgSetting.name, e);
20834                        // Remove the failed install
20835                        removeCodePathLI(codePath);
20836
20837                        // Install the system package
20838                        try (PackageFreezer freezer =
20839                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20840                            synchronized (mPackages) {
20841                                // NOTE: The system package always needs to be enabled; even
20842                                // if it's for a compressed stub. If we don't, installing the
20843                                // system package fails during scan [scanning checks the disabled
20844                                // packages]. We will reverse this later, after we've "installed"
20845                                // the stub.
20846                                // This leaves us in a fragile state; the stub should never be
20847                                // enabled, so, cross your fingers and hope nothing goes wrong
20848                                // until we can disable the package later.
20849                                enableSystemPackageLPw(deletedPkg);
20850                            }
20851                            installPackageFromSystemLIF(deletedPkg.codePath,
20852                                    false /*isPrivileged*/, null /*allUserHandles*/,
20853                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20854                                    true /*writeSettings*/);
20855                        } catch (PackageManagerException pme) {
20856                            Slog.w(TAG, "Failed to restore system package:"
20857                                    + deletedPkg.packageName, pme);
20858                        } finally {
20859                            synchronized (mPackages) {
20860                                mSettings.disableSystemPackageLPw(
20861                                        deletedPkg.packageName, true /*replaced*/);
20862                                mSettings.writeLPr();
20863                            }
20864                        }
20865                        return;
20866                    }
20867                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20868                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20869                    mDexManager.notifyPackageUpdated(pkg.packageName,
20870                            pkg.baseCodePath, pkg.splitCodePaths);
20871                }
20872            }
20873            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20874                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20875                // Don't care about who enables an app.
20876                callingPackage = null;
20877            }
20878            synchronized (mPackages) {
20879                pkgSetting.setEnabled(newState, userId, callingPackage);
20880            }
20881        } else {
20882            synchronized (mPackages) {
20883                // We're dealing with a component level state change
20884                // First, verify that this is a valid class name.
20885                PackageParser.Package pkg = pkgSetting.pkg;
20886                if (pkg == null || !pkg.hasComponentClassName(className)) {
20887                    if (pkg != null &&
20888                            pkg.applicationInfo.targetSdkVersion >=
20889                                    Build.VERSION_CODES.JELLY_BEAN) {
20890                        throw new IllegalArgumentException("Component class " + className
20891                                + " does not exist in " + packageName);
20892                    } else {
20893                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20894                                + className + " does not exist in " + packageName);
20895                    }
20896                }
20897                switch (newState) {
20898                    case COMPONENT_ENABLED_STATE_ENABLED:
20899                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20900                            return;
20901                        }
20902                        break;
20903                    case COMPONENT_ENABLED_STATE_DISABLED:
20904                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20905                            return;
20906                        }
20907                        break;
20908                    case COMPONENT_ENABLED_STATE_DEFAULT:
20909                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20910                            return;
20911                        }
20912                        break;
20913                    default:
20914                        Slog.e(TAG, "Invalid new component state: " + newState);
20915                        return;
20916                }
20917            }
20918        }
20919        synchronized (mPackages) {
20920            scheduleWritePackageRestrictionsLocked(userId);
20921            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20922            final long callingId = Binder.clearCallingIdentity();
20923            try {
20924                updateInstantAppInstallerLocked(packageName);
20925            } finally {
20926                Binder.restoreCallingIdentity(callingId);
20927            }
20928            components = mPendingBroadcasts.get(userId, packageName);
20929            final boolean newPackage = components == null;
20930            if (newPackage) {
20931                components = new ArrayList<String>();
20932            }
20933            if (!components.contains(componentName)) {
20934                components.add(componentName);
20935            }
20936            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20937                sendNow = true;
20938                // Purge entry from pending broadcast list if another one exists already
20939                // since we are sending one right away.
20940                mPendingBroadcasts.remove(userId, packageName);
20941            } else {
20942                if (newPackage) {
20943                    mPendingBroadcasts.put(userId, packageName, components);
20944                }
20945                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20946                    // Schedule a message
20947                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20948                }
20949            }
20950        }
20951
20952        long callingId = Binder.clearCallingIdentity();
20953        try {
20954            if (sendNow) {
20955                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20956                sendPackageChangedBroadcast(packageName,
20957                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20958            }
20959        } finally {
20960            Binder.restoreCallingIdentity(callingId);
20961        }
20962    }
20963
20964    @Override
20965    public void flushPackageRestrictionsAsUser(int userId) {
20966        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20967            return;
20968        }
20969        if (!sUserManager.exists(userId)) {
20970            return;
20971        }
20972        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20973                false /* checkShell */, "flushPackageRestrictions");
20974        synchronized (mPackages) {
20975            mSettings.writePackageRestrictionsLPr(userId);
20976            mDirtyUsers.remove(userId);
20977            if (mDirtyUsers.isEmpty()) {
20978                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20979            }
20980        }
20981    }
20982
20983    private void sendPackageChangedBroadcast(String packageName,
20984            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20985        if (DEBUG_INSTALL)
20986            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20987                    + componentNames);
20988        Bundle extras = new Bundle(4);
20989        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20990        String nameList[] = new String[componentNames.size()];
20991        componentNames.toArray(nameList);
20992        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20993        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20994        extras.putInt(Intent.EXTRA_UID, packageUid);
20995        // If this is not reporting a change of the overall package, then only send it
20996        // to registered receivers.  We don't want to launch a swath of apps for every
20997        // little component state change.
20998        final int flags = !componentNames.contains(packageName)
20999                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21000        final int userId = UserHandle.getUserId(packageUid);
21001        final boolean isInstantApp = isInstantApp(packageName, userId);
21002        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
21003        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
21004        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21005                userIds, instantUserIds);
21006    }
21007
21008    @Override
21009    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21010        if (!sUserManager.exists(userId)) return;
21011        final int callingUid = Binder.getCallingUid();
21012        if (getInstantAppPackageName(callingUid) != null) {
21013            return;
21014        }
21015        final int permission = mContext.checkCallingOrSelfPermission(
21016                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21017        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21018        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
21019                true /* requireFullPermission */, true /* checkShell */, "stop package");
21020        // writer
21021        synchronized (mPackages) {
21022            final PackageSetting ps = mSettings.mPackages.get(packageName);
21023            if (!filterAppAccessLPr(ps, callingUid, userId)
21024                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21025                            allowedByPermission, callingUid, userId)) {
21026                scheduleWritePackageRestrictionsLocked(userId);
21027            }
21028        }
21029    }
21030
21031    @Override
21032    public String getInstallerPackageName(String packageName) {
21033        final int callingUid = Binder.getCallingUid();
21034        synchronized (mPackages) {
21035            final PackageSetting ps = mSettings.mPackages.get(packageName);
21036            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21037                return null;
21038            }
21039            return mSettings.getInstallerPackageNameLPr(packageName);
21040        }
21041    }
21042
21043    public boolean isOrphaned(String packageName) {
21044        // reader
21045        synchronized (mPackages) {
21046            return mSettings.isOrphaned(packageName);
21047        }
21048    }
21049
21050    @Override
21051    public int getApplicationEnabledSetting(String packageName, int userId) {
21052        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21053        int callingUid = Binder.getCallingUid();
21054        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
21055                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21056        // reader
21057        synchronized (mPackages) {
21058            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21059                return COMPONENT_ENABLED_STATE_DISABLED;
21060            }
21061            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21062        }
21063    }
21064
21065    @Override
21066    public int getComponentEnabledSetting(ComponentName component, int userId) {
21067        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21068        int callingUid = Binder.getCallingUid();
21069        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
21070                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21071        synchronized (mPackages) {
21072            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21073                    component, TYPE_UNKNOWN, userId)) {
21074                return COMPONENT_ENABLED_STATE_DISABLED;
21075            }
21076            return mSettings.getComponentEnabledSettingLPr(component, userId);
21077        }
21078    }
21079
21080    @Override
21081    public void enterSafeMode() {
21082        enforceSystemOrRoot("Only the system can request entering safe mode");
21083
21084        if (!mSystemReady) {
21085            mSafeMode = true;
21086        }
21087    }
21088
21089    @Override
21090    public void systemReady() {
21091        enforceSystemOrRoot("Only the system can claim the system is ready");
21092
21093        mSystemReady = true;
21094        final ContentResolver resolver = mContext.getContentResolver();
21095        ContentObserver co = new ContentObserver(mHandler) {
21096            @Override
21097            public void onChange(boolean selfChange) {
21098                mWebInstantAppsDisabled =
21099                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21100                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21101            }
21102        };
21103        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21104                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21105                false, co, UserHandle.USER_SYSTEM);
21106        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
21107                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21108        co.onChange(true);
21109
21110        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21111        // disabled after already being started.
21112        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21113                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21114
21115        // Read the compatibilty setting when the system is ready.
21116        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21117                mContext.getContentResolver(),
21118                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21119        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21120        if (DEBUG_SETTINGS) {
21121            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21122        }
21123
21124        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21125
21126        synchronized (mPackages) {
21127            // Verify that all of the preferred activity components actually
21128            // exist.  It is possible for applications to be updated and at
21129            // that point remove a previously declared activity component that
21130            // had been set as a preferred activity.  We try to clean this up
21131            // the next time we encounter that preferred activity, but it is
21132            // possible for the user flow to never be able to return to that
21133            // situation so here we do a sanity check to make sure we haven't
21134            // left any junk around.
21135            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21136            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21137                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21138                removed.clear();
21139                for (PreferredActivity pa : pir.filterSet()) {
21140                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21141                        removed.add(pa);
21142                    }
21143                }
21144                if (removed.size() > 0) {
21145                    for (int r=0; r<removed.size(); r++) {
21146                        PreferredActivity pa = removed.get(r);
21147                        Slog.w(TAG, "Removing dangling preferred activity: "
21148                                + pa.mPref.mComponent);
21149                        pir.removeFilter(pa);
21150                    }
21151                    mSettings.writePackageRestrictionsLPr(
21152                            mSettings.mPreferredActivities.keyAt(i));
21153                }
21154            }
21155
21156            for (int userId : UserManagerService.getInstance().getUserIds()) {
21157                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21158                    grantPermissionsUserIds = ArrayUtils.appendInt(
21159                            grantPermissionsUserIds, userId);
21160                }
21161            }
21162        }
21163        sUserManager.systemReady();
21164        // If we upgraded grant all default permissions before kicking off.
21165        for (int userId : grantPermissionsUserIds) {
21166            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21167        }
21168
21169        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21170            // If we did not grant default permissions, we preload from this the
21171            // default permission exceptions lazily to ensure we don't hit the
21172            // disk on a new user creation.
21173            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21174        }
21175
21176        // Now that we've scanned all packages, and granted any default
21177        // permissions, ensure permissions are updated. Beware of dragons if you
21178        // try optimizing this.
21179        synchronized (mPackages) {
21180            mPermissionManager.updateAllPermissions(
21181                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
21182                    mPermissionCallback);
21183        }
21184
21185        // Kick off any messages waiting for system ready
21186        if (mPostSystemReadyMessages != null) {
21187            for (Message msg : mPostSystemReadyMessages) {
21188                msg.sendToTarget();
21189            }
21190            mPostSystemReadyMessages = null;
21191        }
21192
21193        // Watch for external volumes that come and go over time
21194        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21195        storage.registerListener(mStorageListener);
21196
21197        mInstallerService.systemReady();
21198        mDexManager.systemReady();
21199        mPackageDexOptimizer.systemReady();
21200
21201        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21202                StorageManagerInternal.class);
21203        StorageManagerInternal.addExternalStoragePolicy(
21204                new StorageManagerInternal.ExternalStorageMountPolicy() {
21205            @Override
21206            public int getMountMode(int uid, String packageName) {
21207                if (Process.isIsolated(uid)) {
21208                    return Zygote.MOUNT_EXTERNAL_NONE;
21209                }
21210                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21211                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21212                }
21213                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21214                    return Zygote.MOUNT_EXTERNAL_READ;
21215                }
21216                return Zygote.MOUNT_EXTERNAL_WRITE;
21217            }
21218
21219            @Override
21220            public boolean hasExternalStorage(int uid, String packageName) {
21221                return true;
21222            }
21223        });
21224
21225        // Now that we're mostly running, clean up stale users and apps
21226        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21227        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21228
21229        mPermissionManager.systemReady();
21230
21231        if (mInstantAppResolverConnection != null) {
21232            mContext.registerReceiver(new BroadcastReceiver() {
21233                @Override
21234                public void onReceive(Context context, Intent intent) {
21235                    mInstantAppResolverConnection.optimisticBind();
21236                    mContext.unregisterReceiver(this);
21237                }
21238            }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
21239        }
21240    }
21241
21242    public void waitForAppDataPrepared() {
21243        if (mPrepareAppDataFuture == null) {
21244            return;
21245        }
21246        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21247        mPrepareAppDataFuture = null;
21248    }
21249
21250    @Override
21251    public boolean isSafeMode() {
21252        // allow instant applications
21253        return mSafeMode;
21254    }
21255
21256    @Override
21257    public boolean hasSystemUidErrors() {
21258        // allow instant applications
21259        return mHasSystemUidErrors;
21260    }
21261
21262    static String arrayToString(int[] array) {
21263        StringBuffer buf = new StringBuffer(128);
21264        buf.append('[');
21265        if (array != null) {
21266            for (int i=0; i<array.length; i++) {
21267                if (i > 0) buf.append(", ");
21268                buf.append(array[i]);
21269            }
21270        }
21271        buf.append(']');
21272        return buf.toString();
21273    }
21274
21275    @Override
21276    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21277            FileDescriptor err, String[] args, ShellCallback callback,
21278            ResultReceiver resultReceiver) {
21279        (new PackageManagerShellCommand(this)).exec(
21280                this, in, out, err, args, callback, resultReceiver);
21281    }
21282
21283    @Override
21284    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21285        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21286
21287        DumpState dumpState = new DumpState();
21288        boolean fullPreferred = false;
21289        boolean checkin = false;
21290
21291        String packageName = null;
21292        ArraySet<String> permissionNames = null;
21293
21294        int opti = 0;
21295        while (opti < args.length) {
21296            String opt = args[opti];
21297            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21298                break;
21299            }
21300            opti++;
21301
21302            if ("-a".equals(opt)) {
21303                // Right now we only know how to print all.
21304            } else if ("-h".equals(opt)) {
21305                pw.println("Package manager dump options:");
21306                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21307                pw.println("    --checkin: dump for a checkin");
21308                pw.println("    -f: print details of intent filters");
21309                pw.println("    -h: print this help");
21310                pw.println("  cmd may be one of:");
21311                pw.println("    l[ibraries]: list known shared libraries");
21312                pw.println("    f[eatures]: list device features");
21313                pw.println("    k[eysets]: print known keysets");
21314                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21315                pw.println("    perm[issions]: dump permissions");
21316                pw.println("    permission [name ...]: dump declaration and use of given permission");
21317                pw.println("    pref[erred]: print preferred package settings");
21318                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21319                pw.println("    prov[iders]: dump content providers");
21320                pw.println("    p[ackages]: dump installed packages");
21321                pw.println("    s[hared-users]: dump shared user IDs");
21322                pw.println("    m[essages]: print collected runtime messages");
21323                pw.println("    v[erifiers]: print package verifier info");
21324                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21325                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21326                pw.println("    version: print database version info");
21327                pw.println("    write: write current settings now");
21328                pw.println("    installs: details about install sessions");
21329                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21330                pw.println("    dexopt: dump dexopt state");
21331                pw.println("    compiler-stats: dump compiler statistics");
21332                pw.println("    service-permissions: dump permissions required by services");
21333                pw.println("    <package.name>: info about given package");
21334                return;
21335            } else if ("--checkin".equals(opt)) {
21336                checkin = true;
21337            } else if ("-f".equals(opt)) {
21338                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21339            } else if ("--proto".equals(opt)) {
21340                dumpProto(fd);
21341                return;
21342            } else {
21343                pw.println("Unknown argument: " + opt + "; use -h for help");
21344            }
21345        }
21346
21347        // Is the caller requesting to dump a particular piece of data?
21348        if (opti < args.length) {
21349            String cmd = args[opti];
21350            opti++;
21351            // Is this a package name?
21352            if ("android".equals(cmd) || cmd.contains(".")) {
21353                packageName = cmd;
21354                // When dumping a single package, we always dump all of its
21355                // filter information since the amount of data will be reasonable.
21356                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21357            } else if ("check-permission".equals(cmd)) {
21358                if (opti >= args.length) {
21359                    pw.println("Error: check-permission missing permission argument");
21360                    return;
21361                }
21362                String perm = args[opti];
21363                opti++;
21364                if (opti >= args.length) {
21365                    pw.println("Error: check-permission missing package argument");
21366                    return;
21367                }
21368
21369                String pkg = args[opti];
21370                opti++;
21371                int user = UserHandle.getUserId(Binder.getCallingUid());
21372                if (opti < args.length) {
21373                    try {
21374                        user = Integer.parseInt(args[opti]);
21375                    } catch (NumberFormatException e) {
21376                        pw.println("Error: check-permission user argument is not a number: "
21377                                + args[opti]);
21378                        return;
21379                    }
21380                }
21381
21382                // Normalize package name to handle renamed packages and static libs
21383                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21384
21385                pw.println(checkPermission(perm, pkg, user));
21386                return;
21387            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21388                dumpState.setDump(DumpState.DUMP_LIBS);
21389            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21390                dumpState.setDump(DumpState.DUMP_FEATURES);
21391            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21392                if (opti >= args.length) {
21393                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21394                            | DumpState.DUMP_SERVICE_RESOLVERS
21395                            | DumpState.DUMP_RECEIVER_RESOLVERS
21396                            | DumpState.DUMP_CONTENT_RESOLVERS);
21397                } else {
21398                    while (opti < args.length) {
21399                        String name = args[opti];
21400                        if ("a".equals(name) || "activity".equals(name)) {
21401                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21402                        } else if ("s".equals(name) || "service".equals(name)) {
21403                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21404                        } else if ("r".equals(name) || "receiver".equals(name)) {
21405                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21406                        } else if ("c".equals(name) || "content".equals(name)) {
21407                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21408                        } else {
21409                            pw.println("Error: unknown resolver table type: " + name);
21410                            return;
21411                        }
21412                        opti++;
21413                    }
21414                }
21415            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21416                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21417            } else if ("permission".equals(cmd)) {
21418                if (opti >= args.length) {
21419                    pw.println("Error: permission requires permission name");
21420                    return;
21421                }
21422                permissionNames = new ArraySet<>();
21423                while (opti < args.length) {
21424                    permissionNames.add(args[opti]);
21425                    opti++;
21426                }
21427                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21428                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21429            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21430                dumpState.setDump(DumpState.DUMP_PREFERRED);
21431            } else if ("preferred-xml".equals(cmd)) {
21432                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21433                if (opti < args.length && "--full".equals(args[opti])) {
21434                    fullPreferred = true;
21435                    opti++;
21436                }
21437            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21438                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21439            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21440                dumpState.setDump(DumpState.DUMP_PACKAGES);
21441            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21442                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21443            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21444                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21445            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21446                dumpState.setDump(DumpState.DUMP_MESSAGES);
21447            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21448                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21449            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21450                    || "intent-filter-verifiers".equals(cmd)) {
21451                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21452            } else if ("version".equals(cmd)) {
21453                dumpState.setDump(DumpState.DUMP_VERSION);
21454            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21455                dumpState.setDump(DumpState.DUMP_KEYSETS);
21456            } else if ("installs".equals(cmd)) {
21457                dumpState.setDump(DumpState.DUMP_INSTALLS);
21458            } else if ("frozen".equals(cmd)) {
21459                dumpState.setDump(DumpState.DUMP_FROZEN);
21460            } else if ("volumes".equals(cmd)) {
21461                dumpState.setDump(DumpState.DUMP_VOLUMES);
21462            } else if ("dexopt".equals(cmd)) {
21463                dumpState.setDump(DumpState.DUMP_DEXOPT);
21464            } else if ("compiler-stats".equals(cmd)) {
21465                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21466            } else if ("changes".equals(cmd)) {
21467                dumpState.setDump(DumpState.DUMP_CHANGES);
21468            } else if ("service-permissions".equals(cmd)) {
21469                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21470            } else if ("write".equals(cmd)) {
21471                synchronized (mPackages) {
21472                    mSettings.writeLPr();
21473                    pw.println("Settings written.");
21474                    return;
21475                }
21476            }
21477        }
21478
21479        if (checkin) {
21480            pw.println("vers,1");
21481        }
21482
21483        // reader
21484        synchronized (mPackages) {
21485            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21486                if (!checkin) {
21487                    if (dumpState.onTitlePrinted())
21488                        pw.println();
21489                    pw.println("Database versions:");
21490                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21491                }
21492            }
21493
21494            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21495                if (!checkin) {
21496                    if (dumpState.onTitlePrinted())
21497                        pw.println();
21498                    pw.println("Verifiers:");
21499                    pw.print("  Required: ");
21500                    pw.print(mRequiredVerifierPackage);
21501                    pw.print(" (uid=");
21502                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21503                            UserHandle.USER_SYSTEM));
21504                    pw.println(")");
21505                } else if (mRequiredVerifierPackage != null) {
21506                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21507                    pw.print(",");
21508                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21509                            UserHandle.USER_SYSTEM));
21510                }
21511            }
21512
21513            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21514                    packageName == null) {
21515                if (mIntentFilterVerifierComponent != null) {
21516                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21517                    if (!checkin) {
21518                        if (dumpState.onTitlePrinted())
21519                            pw.println();
21520                        pw.println("Intent Filter Verifier:");
21521                        pw.print("  Using: ");
21522                        pw.print(verifierPackageName);
21523                        pw.print(" (uid=");
21524                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21525                                UserHandle.USER_SYSTEM));
21526                        pw.println(")");
21527                    } else if (verifierPackageName != null) {
21528                        pw.print("ifv,"); pw.print(verifierPackageName);
21529                        pw.print(",");
21530                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21531                                UserHandle.USER_SYSTEM));
21532                    }
21533                } else {
21534                    pw.println();
21535                    pw.println("No Intent Filter Verifier available!");
21536                }
21537            }
21538
21539            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21540                boolean printedHeader = false;
21541                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21542                while (it.hasNext()) {
21543                    String libName = it.next();
21544                    LongSparseArray<SharedLibraryEntry> versionedLib
21545                            = mSharedLibraries.get(libName);
21546                    if (versionedLib == null) {
21547                        continue;
21548                    }
21549                    final int versionCount = versionedLib.size();
21550                    for (int i = 0; i < versionCount; i++) {
21551                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21552                        if (!checkin) {
21553                            if (!printedHeader) {
21554                                if (dumpState.onTitlePrinted())
21555                                    pw.println();
21556                                pw.println("Libraries:");
21557                                printedHeader = true;
21558                            }
21559                            pw.print("  ");
21560                        } else {
21561                            pw.print("lib,");
21562                        }
21563                        pw.print(libEntry.info.getName());
21564                        if (libEntry.info.isStatic()) {
21565                            pw.print(" version=" + libEntry.info.getLongVersion());
21566                        }
21567                        if (!checkin) {
21568                            pw.print(" -> ");
21569                        }
21570                        if (libEntry.path != null) {
21571                            pw.print(" (jar) ");
21572                            pw.print(libEntry.path);
21573                        } else {
21574                            pw.print(" (apk) ");
21575                            pw.print(libEntry.apk);
21576                        }
21577                        pw.println();
21578                    }
21579                }
21580            }
21581
21582            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21583                if (dumpState.onTitlePrinted())
21584                    pw.println();
21585                if (!checkin) {
21586                    pw.println("Features:");
21587                }
21588
21589                synchronized (mAvailableFeatures) {
21590                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21591                        if (checkin) {
21592                            pw.print("feat,");
21593                            pw.print(feat.name);
21594                            pw.print(",");
21595                            pw.println(feat.version);
21596                        } else {
21597                            pw.print("  ");
21598                            pw.print(feat.name);
21599                            if (feat.version > 0) {
21600                                pw.print(" version=");
21601                                pw.print(feat.version);
21602                            }
21603                            pw.println();
21604                        }
21605                    }
21606                }
21607            }
21608
21609            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21610                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21611                        : "Activity Resolver Table:", "  ", packageName,
21612                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21613                    dumpState.setTitlePrinted(true);
21614                }
21615            }
21616            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21617                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21618                        : "Receiver Resolver Table:", "  ", packageName,
21619                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21620                    dumpState.setTitlePrinted(true);
21621                }
21622            }
21623            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21624                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21625                        : "Service Resolver Table:", "  ", packageName,
21626                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21627                    dumpState.setTitlePrinted(true);
21628                }
21629            }
21630            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21631                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21632                        : "Provider Resolver Table:", "  ", packageName,
21633                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21634                    dumpState.setTitlePrinted(true);
21635                }
21636            }
21637
21638            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21639                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21640                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21641                    int user = mSettings.mPreferredActivities.keyAt(i);
21642                    if (pir.dump(pw,
21643                            dumpState.getTitlePrinted()
21644                                ? "\nPreferred Activities User " + user + ":"
21645                                : "Preferred Activities User " + user + ":", "  ",
21646                            packageName, true, false)) {
21647                        dumpState.setTitlePrinted(true);
21648                    }
21649                }
21650            }
21651
21652            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21653                pw.flush();
21654                FileOutputStream fout = new FileOutputStream(fd);
21655                BufferedOutputStream str = new BufferedOutputStream(fout);
21656                XmlSerializer serializer = new FastXmlSerializer();
21657                try {
21658                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21659                    serializer.startDocument(null, true);
21660                    serializer.setFeature(
21661                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21662                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21663                    serializer.endDocument();
21664                    serializer.flush();
21665                } catch (IllegalArgumentException e) {
21666                    pw.println("Failed writing: " + e);
21667                } catch (IllegalStateException e) {
21668                    pw.println("Failed writing: " + e);
21669                } catch (IOException e) {
21670                    pw.println("Failed writing: " + e);
21671                }
21672            }
21673
21674            if (!checkin
21675                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21676                    && packageName == null) {
21677                pw.println();
21678                int count = mSettings.mPackages.size();
21679                if (count == 0) {
21680                    pw.println("No applications!");
21681                    pw.println();
21682                } else {
21683                    final String prefix = "  ";
21684                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21685                    if (allPackageSettings.size() == 0) {
21686                        pw.println("No domain preferred apps!");
21687                        pw.println();
21688                    } else {
21689                        pw.println("App verification status:");
21690                        pw.println();
21691                        count = 0;
21692                        for (PackageSetting ps : allPackageSettings) {
21693                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21694                            if (ivi == null || ivi.getPackageName() == null) continue;
21695                            pw.println(prefix + "Package: " + ivi.getPackageName());
21696                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21697                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21698                            pw.println();
21699                            count++;
21700                        }
21701                        if (count == 0) {
21702                            pw.println(prefix + "No app verification established.");
21703                            pw.println();
21704                        }
21705                        for (int userId : sUserManager.getUserIds()) {
21706                            pw.println("App linkages for user " + userId + ":");
21707                            pw.println();
21708                            count = 0;
21709                            for (PackageSetting ps : allPackageSettings) {
21710                                final long status = ps.getDomainVerificationStatusForUser(userId);
21711                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21712                                        && !DEBUG_DOMAIN_VERIFICATION) {
21713                                    continue;
21714                                }
21715                                pw.println(prefix + "Package: " + ps.name);
21716                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21717                                String statusStr = IntentFilterVerificationInfo.
21718                                        getStatusStringFromValue(status);
21719                                pw.println(prefix + "Status:  " + statusStr);
21720                                pw.println();
21721                                count++;
21722                            }
21723                            if (count == 0) {
21724                                pw.println(prefix + "No configured app linkages.");
21725                                pw.println();
21726                            }
21727                        }
21728                    }
21729                }
21730            }
21731
21732            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21733                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21734            }
21735
21736            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21737                boolean printedSomething = false;
21738                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21739                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21740                        continue;
21741                    }
21742                    if (!printedSomething) {
21743                        if (dumpState.onTitlePrinted())
21744                            pw.println();
21745                        pw.println("Registered ContentProviders:");
21746                        printedSomething = true;
21747                    }
21748                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21749                    pw.print("    "); pw.println(p.toString());
21750                }
21751                printedSomething = false;
21752                for (Map.Entry<String, PackageParser.Provider> entry :
21753                        mProvidersByAuthority.entrySet()) {
21754                    PackageParser.Provider p = entry.getValue();
21755                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21756                        continue;
21757                    }
21758                    if (!printedSomething) {
21759                        if (dumpState.onTitlePrinted())
21760                            pw.println();
21761                        pw.println("ContentProvider Authorities:");
21762                        printedSomething = true;
21763                    }
21764                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21765                    pw.print("    "); pw.println(p.toString());
21766                    if (p.info != null && p.info.applicationInfo != null) {
21767                        final String appInfo = p.info.applicationInfo.toString();
21768                        pw.print("      applicationInfo="); pw.println(appInfo);
21769                    }
21770                }
21771            }
21772
21773            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21774                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21775            }
21776
21777            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21778                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21779            }
21780
21781            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21782                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21783            }
21784
21785            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21786                if (dumpState.onTitlePrinted()) pw.println();
21787                pw.println("Package Changes:");
21788                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21789                final int K = mChangedPackages.size();
21790                for (int i = 0; i < K; i++) {
21791                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21792                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21793                    final int N = changes.size();
21794                    if (N == 0) {
21795                        pw.print("    "); pw.println("No packages changed");
21796                    } else {
21797                        for (int j = 0; j < N; j++) {
21798                            final String pkgName = changes.valueAt(j);
21799                            final int sequenceNumber = changes.keyAt(j);
21800                            pw.print("    ");
21801                            pw.print("seq=");
21802                            pw.print(sequenceNumber);
21803                            pw.print(", package=");
21804                            pw.println(pkgName);
21805                        }
21806                    }
21807                }
21808            }
21809
21810            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21811                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21812            }
21813
21814            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21815                // XXX should handle packageName != null by dumping only install data that
21816                // the given package is involved with.
21817                if (dumpState.onTitlePrinted()) pw.println();
21818
21819                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21820                ipw.println();
21821                ipw.println("Frozen packages:");
21822                ipw.increaseIndent();
21823                if (mFrozenPackages.size() == 0) {
21824                    ipw.println("(none)");
21825                } else {
21826                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21827                        ipw.println(mFrozenPackages.valueAt(i));
21828                    }
21829                }
21830                ipw.decreaseIndent();
21831            }
21832
21833            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21834                if (dumpState.onTitlePrinted()) pw.println();
21835
21836                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21837                ipw.println();
21838                ipw.println("Loaded volumes:");
21839                ipw.increaseIndent();
21840                if (mLoadedVolumes.size() == 0) {
21841                    ipw.println("(none)");
21842                } else {
21843                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21844                        ipw.println(mLoadedVolumes.valueAt(i));
21845                    }
21846                }
21847                ipw.decreaseIndent();
21848            }
21849
21850            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21851                    && packageName == null) {
21852                if (dumpState.onTitlePrinted()) pw.println();
21853                pw.println("Service permissions:");
21854
21855                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21856                while (filterIterator.hasNext()) {
21857                    final ServiceIntentInfo info = filterIterator.next();
21858                    final ServiceInfo serviceInfo = info.service.info;
21859                    final String permission = serviceInfo.permission;
21860                    if (permission != null) {
21861                        pw.print("    ");
21862                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21863                        pw.print(": ");
21864                        pw.println(permission);
21865                    }
21866                }
21867            }
21868
21869            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21870                if (dumpState.onTitlePrinted()) pw.println();
21871                dumpDexoptStateLPr(pw, packageName);
21872            }
21873
21874            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21875                if (dumpState.onTitlePrinted()) pw.println();
21876                dumpCompilerStatsLPr(pw, packageName);
21877            }
21878
21879            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21880                if (dumpState.onTitlePrinted()) pw.println();
21881                mSettings.dumpReadMessagesLPr(pw, dumpState);
21882
21883                pw.println();
21884                pw.println("Package warning messages:");
21885                dumpCriticalInfo(pw, null);
21886            }
21887
21888            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21889                dumpCriticalInfo(pw, "msg,");
21890            }
21891        }
21892
21893        // PackageInstaller should be called outside of mPackages lock
21894        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21895            // XXX should handle packageName != null by dumping only install data that
21896            // the given package is involved with.
21897            if (dumpState.onTitlePrinted()) pw.println();
21898            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21899        }
21900    }
21901
21902    private void dumpProto(FileDescriptor fd) {
21903        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21904
21905        synchronized (mPackages) {
21906            final long requiredVerifierPackageToken =
21907                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21908            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21909            proto.write(
21910                    PackageServiceDumpProto.PackageShortProto.UID,
21911                    getPackageUid(
21912                            mRequiredVerifierPackage,
21913                            MATCH_DEBUG_TRIAGED_MISSING,
21914                            UserHandle.USER_SYSTEM));
21915            proto.end(requiredVerifierPackageToken);
21916
21917            if (mIntentFilterVerifierComponent != null) {
21918                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21919                final long verifierPackageToken =
21920                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21921                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21922                proto.write(
21923                        PackageServiceDumpProto.PackageShortProto.UID,
21924                        getPackageUid(
21925                                verifierPackageName,
21926                                MATCH_DEBUG_TRIAGED_MISSING,
21927                                UserHandle.USER_SYSTEM));
21928                proto.end(verifierPackageToken);
21929            }
21930
21931            dumpSharedLibrariesProto(proto);
21932            dumpFeaturesProto(proto);
21933            mSettings.dumpPackagesProto(proto);
21934            mSettings.dumpSharedUsersProto(proto);
21935            dumpCriticalInfo(proto);
21936        }
21937        proto.flush();
21938    }
21939
21940    private void dumpFeaturesProto(ProtoOutputStream proto) {
21941        synchronized (mAvailableFeatures) {
21942            final int count = mAvailableFeatures.size();
21943            for (int i = 0; i < count; i++) {
21944                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21945            }
21946        }
21947    }
21948
21949    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21950        final int count = mSharedLibraries.size();
21951        for (int i = 0; i < count; i++) {
21952            final String libName = mSharedLibraries.keyAt(i);
21953            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21954            if (versionedLib == null) {
21955                continue;
21956            }
21957            final int versionCount = versionedLib.size();
21958            for (int j = 0; j < versionCount; j++) {
21959                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21960                final long sharedLibraryToken =
21961                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21962                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21963                final boolean isJar = (libEntry.path != null);
21964                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21965                if (isJar) {
21966                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21967                } else {
21968                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21969                }
21970                proto.end(sharedLibraryToken);
21971            }
21972        }
21973    }
21974
21975    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21976        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21977        ipw.println();
21978        ipw.println("Dexopt state:");
21979        ipw.increaseIndent();
21980        Collection<PackageParser.Package> packages = null;
21981        if (packageName != null) {
21982            PackageParser.Package targetPackage = mPackages.get(packageName);
21983            if (targetPackage != null) {
21984                packages = Collections.singletonList(targetPackage);
21985            } else {
21986                ipw.println("Unable to find package: " + packageName);
21987                return;
21988            }
21989        } else {
21990            packages = mPackages.values();
21991        }
21992
21993        for (PackageParser.Package pkg : packages) {
21994            ipw.println("[" + pkg.packageName + "]");
21995            ipw.increaseIndent();
21996            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21997                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21998            ipw.decreaseIndent();
21999        }
22000    }
22001
22002    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22003        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
22004        ipw.println();
22005        ipw.println("Compiler stats:");
22006        ipw.increaseIndent();
22007        Collection<PackageParser.Package> packages = null;
22008        if (packageName != null) {
22009            PackageParser.Package targetPackage = mPackages.get(packageName);
22010            if (targetPackage != null) {
22011                packages = Collections.singletonList(targetPackage);
22012            } else {
22013                ipw.println("Unable to find package: " + packageName);
22014                return;
22015            }
22016        } else {
22017            packages = mPackages.values();
22018        }
22019
22020        for (PackageParser.Package pkg : packages) {
22021            ipw.println("[" + pkg.packageName + "]");
22022            ipw.increaseIndent();
22023
22024            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22025            if (stats == null) {
22026                ipw.println("(No recorded stats)");
22027            } else {
22028                stats.dump(ipw);
22029            }
22030            ipw.decreaseIndent();
22031        }
22032    }
22033
22034    private String dumpDomainString(String packageName) {
22035        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22036                .getList();
22037        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22038
22039        ArraySet<String> result = new ArraySet<>();
22040        if (iviList.size() > 0) {
22041            for (IntentFilterVerificationInfo ivi : iviList) {
22042                for (String host : ivi.getDomains()) {
22043                    result.add(host);
22044                }
22045            }
22046        }
22047        if (filters != null && filters.size() > 0) {
22048            for (IntentFilter filter : filters) {
22049                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22050                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22051                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22052                    result.addAll(filter.getHostsList());
22053                }
22054            }
22055        }
22056
22057        StringBuilder sb = new StringBuilder(result.size() * 16);
22058        for (String domain : result) {
22059            if (sb.length() > 0) sb.append(" ");
22060            sb.append(domain);
22061        }
22062        return sb.toString();
22063    }
22064
22065    // ------- apps on sdcard specific code -------
22066    static final boolean DEBUG_SD_INSTALL = false;
22067
22068    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22069
22070    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22071
22072    private boolean mMediaMounted = false;
22073
22074    static String getEncryptKey() {
22075        try {
22076            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22077                    SD_ENCRYPTION_KEYSTORE_NAME);
22078            if (sdEncKey == null) {
22079                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22080                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22081                if (sdEncKey == null) {
22082                    Slog.e(TAG, "Failed to create encryption keys");
22083                    return null;
22084                }
22085            }
22086            return sdEncKey;
22087        } catch (NoSuchAlgorithmException nsae) {
22088            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22089            return null;
22090        } catch (IOException ioe) {
22091            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22092            return null;
22093        }
22094    }
22095
22096    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22097            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22098        final int size = infos.size();
22099        final String[] packageNames = new String[size];
22100        final int[] packageUids = new int[size];
22101        for (int i = 0; i < size; i++) {
22102            final ApplicationInfo info = infos.get(i);
22103            packageNames[i] = info.packageName;
22104            packageUids[i] = info.uid;
22105        }
22106        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22107                finishedReceiver);
22108    }
22109
22110    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22111            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22112        sendResourcesChangedBroadcast(mediaStatus, replacing,
22113                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22114    }
22115
22116    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22117            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22118        int size = pkgList.length;
22119        if (size > 0) {
22120            // Send broadcasts here
22121            Bundle extras = new Bundle();
22122            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22123            if (uidArr != null) {
22124                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22125            }
22126            if (replacing) {
22127                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22128            }
22129            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22130                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22131            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
22132        }
22133    }
22134
22135    private void loadPrivatePackages(final VolumeInfo vol) {
22136        mHandler.post(new Runnable() {
22137            @Override
22138            public void run() {
22139                loadPrivatePackagesInner(vol);
22140            }
22141        });
22142    }
22143
22144    private void loadPrivatePackagesInner(VolumeInfo vol) {
22145        final String volumeUuid = vol.fsUuid;
22146        if (TextUtils.isEmpty(volumeUuid)) {
22147            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22148            return;
22149        }
22150
22151        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22152        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22153        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22154
22155        final VersionInfo ver;
22156        final List<PackageSetting> packages;
22157        synchronized (mPackages) {
22158            ver = mSettings.findOrCreateVersion(volumeUuid);
22159            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22160        }
22161
22162        for (PackageSetting ps : packages) {
22163            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22164            synchronized (mInstallLock) {
22165                final PackageParser.Package pkg;
22166                try {
22167                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22168                    loaded.add(pkg.applicationInfo);
22169
22170                } catch (PackageManagerException e) {
22171                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22172                }
22173
22174                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22175                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22176                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22177                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22178                }
22179            }
22180        }
22181
22182        // Reconcile app data for all started/unlocked users
22183        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22184        final UserManager um = mContext.getSystemService(UserManager.class);
22185        UserManagerInternal umInternal = getUserManagerInternal();
22186        for (UserInfo user : um.getUsers()) {
22187            final int flags;
22188            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22189                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22190            } else if (umInternal.isUserRunning(user.id)) {
22191                flags = StorageManager.FLAG_STORAGE_DE;
22192            } else {
22193                continue;
22194            }
22195
22196            try {
22197                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22198                synchronized (mInstallLock) {
22199                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22200                }
22201            } catch (IllegalStateException e) {
22202                // Device was probably ejected, and we'll process that event momentarily
22203                Slog.w(TAG, "Failed to prepare storage: " + e);
22204            }
22205        }
22206
22207        synchronized (mPackages) {
22208            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
22209            if (sdkUpdated) {
22210                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22211                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22212            }
22213            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
22214                    mPermissionCallback);
22215
22216            // Yay, everything is now upgraded
22217            ver.forceCurrent();
22218
22219            mSettings.writeLPr();
22220        }
22221
22222        for (PackageFreezer freezer : freezers) {
22223            freezer.close();
22224        }
22225
22226        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22227        sendResourcesChangedBroadcast(true, false, loaded, null);
22228        mLoadedVolumes.add(vol.getId());
22229    }
22230
22231    private void unloadPrivatePackages(final VolumeInfo vol) {
22232        mHandler.post(new Runnable() {
22233            @Override
22234            public void run() {
22235                unloadPrivatePackagesInner(vol);
22236            }
22237        });
22238    }
22239
22240    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22241        final String volumeUuid = vol.fsUuid;
22242        if (TextUtils.isEmpty(volumeUuid)) {
22243            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22244            return;
22245        }
22246
22247        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22248        synchronized (mInstallLock) {
22249        synchronized (mPackages) {
22250            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22251            for (PackageSetting ps : packages) {
22252                if (ps.pkg == null) continue;
22253
22254                final ApplicationInfo info = ps.pkg.applicationInfo;
22255                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22256                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22257
22258                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22259                        "unloadPrivatePackagesInner")) {
22260                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22261                            false, null)) {
22262                        unloaded.add(info);
22263                    } else {
22264                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22265                    }
22266                }
22267
22268                // Try very hard to release any references to this package
22269                // so we don't risk the system server being killed due to
22270                // open FDs
22271                AttributeCache.instance().removePackage(ps.name);
22272            }
22273
22274            mSettings.writeLPr();
22275        }
22276        }
22277
22278        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22279        sendResourcesChangedBroadcast(false, false, unloaded, null);
22280        mLoadedVolumes.remove(vol.getId());
22281
22282        // Try very hard to release any references to this path so we don't risk
22283        // the system server being killed due to open FDs
22284        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22285
22286        for (int i = 0; i < 3; i++) {
22287            System.gc();
22288            System.runFinalization();
22289        }
22290    }
22291
22292    private void assertPackageKnown(String volumeUuid, String packageName)
22293            throws PackageManagerException {
22294        synchronized (mPackages) {
22295            // Normalize package name to handle renamed packages
22296            packageName = normalizePackageNameLPr(packageName);
22297
22298            final PackageSetting ps = mSettings.mPackages.get(packageName);
22299            if (ps == null) {
22300                throw new PackageManagerException("Package " + packageName + " is unknown");
22301            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22302                throw new PackageManagerException(
22303                        "Package " + packageName + " found on unknown volume " + volumeUuid
22304                                + "; expected volume " + ps.volumeUuid);
22305            }
22306        }
22307    }
22308
22309    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22310            throws PackageManagerException {
22311        synchronized (mPackages) {
22312            // Normalize package name to handle renamed packages
22313            packageName = normalizePackageNameLPr(packageName);
22314
22315            final PackageSetting ps = mSettings.mPackages.get(packageName);
22316            if (ps == null) {
22317                throw new PackageManagerException("Package " + packageName + " is unknown");
22318            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22319                throw new PackageManagerException(
22320                        "Package " + packageName + " found on unknown volume " + volumeUuid
22321                                + "; expected volume " + ps.volumeUuid);
22322            } else if (!ps.getInstalled(userId)) {
22323                throw new PackageManagerException(
22324                        "Package " + packageName + " not installed for user " + userId);
22325            }
22326        }
22327    }
22328
22329    private List<String> collectAbsoluteCodePaths() {
22330        synchronized (mPackages) {
22331            List<String> codePaths = new ArrayList<>();
22332            final int packageCount = mSettings.mPackages.size();
22333            for (int i = 0; i < packageCount; i++) {
22334                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22335                codePaths.add(ps.codePath.getAbsolutePath());
22336            }
22337            return codePaths;
22338        }
22339    }
22340
22341    /**
22342     * Examine all apps present on given mounted volume, and destroy apps that
22343     * aren't expected, either due to uninstallation or reinstallation on
22344     * another volume.
22345     */
22346    private void reconcileApps(String volumeUuid) {
22347        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22348        List<File> filesToDelete = null;
22349
22350        final File[] files = FileUtils.listFilesOrEmpty(
22351                Environment.getDataAppDirectory(volumeUuid));
22352        for (File file : files) {
22353            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22354                    && !PackageInstallerService.isStageName(file.getName());
22355            if (!isPackage) {
22356                // Ignore entries which are not packages
22357                continue;
22358            }
22359
22360            String absolutePath = file.getAbsolutePath();
22361
22362            boolean pathValid = false;
22363            final int absoluteCodePathCount = absoluteCodePaths.size();
22364            for (int i = 0; i < absoluteCodePathCount; i++) {
22365                String absoluteCodePath = absoluteCodePaths.get(i);
22366                if (absolutePath.startsWith(absoluteCodePath)) {
22367                    pathValid = true;
22368                    break;
22369                }
22370            }
22371
22372            if (!pathValid) {
22373                if (filesToDelete == null) {
22374                    filesToDelete = new ArrayList<>();
22375                }
22376                filesToDelete.add(file);
22377            }
22378        }
22379
22380        if (filesToDelete != null) {
22381            final int fileToDeleteCount = filesToDelete.size();
22382            for (int i = 0; i < fileToDeleteCount; i++) {
22383                File fileToDelete = filesToDelete.get(i);
22384                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22385                synchronized (mInstallLock) {
22386                    removeCodePathLI(fileToDelete);
22387                }
22388            }
22389        }
22390    }
22391
22392    /**
22393     * Reconcile all app data for the given user.
22394     * <p>
22395     * Verifies that directories exist and that ownership and labeling is
22396     * correct for all installed apps on all mounted volumes.
22397     */
22398    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22399        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22400        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22401            final String volumeUuid = vol.getFsUuid();
22402            synchronized (mInstallLock) {
22403                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22404            }
22405        }
22406    }
22407
22408    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22409            boolean migrateAppData) {
22410        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22411    }
22412
22413    /**
22414     * Reconcile all app data on given mounted volume.
22415     * <p>
22416     * Destroys app data that isn't expected, either due to uninstallation or
22417     * reinstallation on another volume.
22418     * <p>
22419     * Verifies that directories exist and that ownership and labeling is
22420     * correct for all installed apps.
22421     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22422     */
22423    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22424            boolean migrateAppData, boolean onlyCoreApps) {
22425        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22426                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22427        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22428
22429        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22430        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22431
22432        // First look for stale data that doesn't belong, and check if things
22433        // have changed since we did our last restorecon
22434        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22435            if (StorageManager.isFileEncryptedNativeOrEmulated()
22436                    && !StorageManager.isUserKeyUnlocked(userId)) {
22437                throw new RuntimeException(
22438                        "Yikes, someone asked us to reconcile CE storage while " + userId
22439                                + " was still locked; this would have caused massive data loss!");
22440            }
22441
22442            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22443            for (File file : files) {
22444                final String packageName = file.getName();
22445                try {
22446                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22447                } catch (PackageManagerException e) {
22448                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22449                    try {
22450                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22451                                StorageManager.FLAG_STORAGE_CE, 0);
22452                    } catch (InstallerException e2) {
22453                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22454                    }
22455                }
22456            }
22457        }
22458        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22459            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22460            for (File file : files) {
22461                final String packageName = file.getName();
22462                try {
22463                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22464                } catch (PackageManagerException e) {
22465                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22466                    try {
22467                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22468                                StorageManager.FLAG_STORAGE_DE, 0);
22469                    } catch (InstallerException e2) {
22470                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22471                    }
22472                }
22473            }
22474        }
22475
22476        // Ensure that data directories are ready to roll for all packages
22477        // installed for this volume and user
22478        final List<PackageSetting> packages;
22479        synchronized (mPackages) {
22480            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22481        }
22482        int preparedCount = 0;
22483        for (PackageSetting ps : packages) {
22484            final String packageName = ps.name;
22485            if (ps.pkg == null) {
22486                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22487                // TODO: might be due to legacy ASEC apps; we should circle back
22488                // and reconcile again once they're scanned
22489                continue;
22490            }
22491            // Skip non-core apps if requested
22492            if (onlyCoreApps && !ps.pkg.coreApp) {
22493                result.add(packageName);
22494                continue;
22495            }
22496
22497            if (ps.getInstalled(userId)) {
22498                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22499                preparedCount++;
22500            }
22501        }
22502
22503        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22504        return result;
22505    }
22506
22507    /**
22508     * Prepare app data for the given app just after it was installed or
22509     * upgraded. This method carefully only touches users that it's installed
22510     * for, and it forces a restorecon to handle any seinfo changes.
22511     * <p>
22512     * Verifies that directories exist and that ownership and labeling is
22513     * correct for all installed apps. If there is an ownership mismatch, it
22514     * will try recovering system apps by wiping data; third-party app data is
22515     * left intact.
22516     * <p>
22517     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22518     */
22519    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22520        final PackageSetting ps;
22521        synchronized (mPackages) {
22522            ps = mSettings.mPackages.get(pkg.packageName);
22523            mSettings.writeKernelMappingLPr(ps);
22524        }
22525
22526        final UserManager um = mContext.getSystemService(UserManager.class);
22527        UserManagerInternal umInternal = getUserManagerInternal();
22528        for (UserInfo user : um.getUsers()) {
22529            final int flags;
22530            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22531                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22532            } else if (umInternal.isUserRunning(user.id)) {
22533                flags = StorageManager.FLAG_STORAGE_DE;
22534            } else {
22535                continue;
22536            }
22537
22538            if (ps.getInstalled(user.id)) {
22539                // TODO: when user data is locked, mark that we're still dirty
22540                prepareAppDataLIF(pkg, user.id, flags);
22541            }
22542        }
22543    }
22544
22545    /**
22546     * Prepare app data for the given app.
22547     * <p>
22548     * Verifies that directories exist and that ownership and labeling is
22549     * correct for all installed apps. If there is an ownership mismatch, this
22550     * will try recovering system apps by wiping data; third-party app data is
22551     * left intact.
22552     */
22553    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22554        if (pkg == null) {
22555            Slog.wtf(TAG, "Package was null!", new Throwable());
22556            return;
22557        }
22558        prepareAppDataLeafLIF(pkg, userId, flags);
22559        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22560        for (int i = 0; i < childCount; i++) {
22561            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22562        }
22563    }
22564
22565    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22566            boolean maybeMigrateAppData) {
22567        prepareAppDataLIF(pkg, userId, flags);
22568
22569        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22570            // We may have just shuffled around app data directories, so
22571            // prepare them one more time
22572            prepareAppDataLIF(pkg, userId, flags);
22573        }
22574    }
22575
22576    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22577        if (DEBUG_APP_DATA) {
22578            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22579                    + Integer.toHexString(flags));
22580        }
22581
22582        final PackageSetting ps;
22583        synchronized (mPackages) {
22584            ps = mSettings.mPackages.get(pkg.packageName);
22585        }
22586        final String volumeUuid = pkg.volumeUuid;
22587        final String packageName = pkg.packageName;
22588
22589        ApplicationInfo app = (ps == null)
22590                ? pkg.applicationInfo
22591                : PackageParser.generateApplicationInfo(pkg, 0, ps.readUserState(userId), userId);
22592        if (app == null) {
22593            app = pkg.applicationInfo;
22594        }
22595
22596        final int appId = UserHandle.getAppId(app.uid);
22597
22598        Preconditions.checkNotNull(app.seInfo);
22599
22600        final String seInfo = app.seInfo + (app.seInfoUser != null ? app.seInfoUser : "");
22601        long ceDataInode = -1;
22602        try {
22603            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22604                    appId, seInfo, app.targetSdkVersion);
22605        } catch (InstallerException e) {
22606            if (app.isSystemApp()) {
22607                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22608                        + ", but trying to recover: " + e);
22609                destroyAppDataLeafLIF(pkg, userId, flags);
22610                try {
22611                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22612                            appId, seInfo, app.targetSdkVersion);
22613                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22614                } catch (InstallerException e2) {
22615                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22616                }
22617            } else {
22618                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22619            }
22620        }
22621        // Prepare the application profiles only for upgrades and first boot (so that we don't
22622        // repeat the same operation at each boot).
22623        // We only have to cover the upgrade and first boot here because for app installs we
22624        // prepare the profiles before invoking dexopt (in installPackageLI).
22625        //
22626        // We also have to cover non system users because we do not call the usual install package
22627        // methods for them.
22628        if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) {
22629            mArtManagerService.prepareAppProfiles(pkg, userId);
22630        }
22631
22632        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22633            // TODO: mark this structure as dirty so we persist it!
22634            synchronized (mPackages) {
22635                if (ps != null) {
22636                    ps.setCeDataInode(ceDataInode, userId);
22637                }
22638            }
22639        }
22640
22641        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22642    }
22643
22644    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22645        if (pkg == null) {
22646            Slog.wtf(TAG, "Package was null!", new Throwable());
22647            return;
22648        }
22649        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22650        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22651        for (int i = 0; i < childCount; i++) {
22652            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22653        }
22654    }
22655
22656    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22657        final String volumeUuid = pkg.volumeUuid;
22658        final String packageName = pkg.packageName;
22659        final ApplicationInfo app = pkg.applicationInfo;
22660
22661        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22662            // Create a native library symlink only if we have native libraries
22663            // and if the native libraries are 32 bit libraries. We do not provide
22664            // this symlink for 64 bit libraries.
22665            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22666                final String nativeLibPath = app.nativeLibraryDir;
22667                try {
22668                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22669                            nativeLibPath, userId);
22670                } catch (InstallerException e) {
22671                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22672                }
22673            }
22674        }
22675    }
22676
22677    /**
22678     * For system apps on non-FBE devices, this method migrates any existing
22679     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22680     * requested by the app.
22681     */
22682    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22683        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22684                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22685            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22686                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22687            try {
22688                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22689                        storageTarget);
22690            } catch (InstallerException e) {
22691                logCriticalInfo(Log.WARN,
22692                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22693            }
22694            return true;
22695        } else {
22696            return false;
22697        }
22698    }
22699
22700    public PackageFreezer freezePackage(String packageName, String killReason) {
22701        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22702    }
22703
22704    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22705        return new PackageFreezer(packageName, userId, killReason);
22706    }
22707
22708    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22709            String killReason) {
22710        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22711    }
22712
22713    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22714            String killReason) {
22715        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22716            return new PackageFreezer();
22717        } else {
22718            return freezePackage(packageName, userId, killReason);
22719        }
22720    }
22721
22722    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22723            String killReason) {
22724        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22725    }
22726
22727    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22728            String killReason) {
22729        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22730            return new PackageFreezer();
22731        } else {
22732            return freezePackage(packageName, userId, killReason);
22733        }
22734    }
22735
22736    /**
22737     * Class that freezes and kills the given package upon creation, and
22738     * unfreezes it upon closing. This is typically used when doing surgery on
22739     * app code/data to prevent the app from running while you're working.
22740     */
22741    private class PackageFreezer implements AutoCloseable {
22742        private final String mPackageName;
22743        private final PackageFreezer[] mChildren;
22744
22745        private final boolean mWeFroze;
22746
22747        private final AtomicBoolean mClosed = new AtomicBoolean();
22748        private final CloseGuard mCloseGuard = CloseGuard.get();
22749
22750        /**
22751         * Create and return a stub freezer that doesn't actually do anything,
22752         * typically used when someone requested
22753         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22754         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22755         */
22756        public PackageFreezer() {
22757            mPackageName = null;
22758            mChildren = null;
22759            mWeFroze = false;
22760            mCloseGuard.open("close");
22761        }
22762
22763        public PackageFreezer(String packageName, int userId, String killReason) {
22764            synchronized (mPackages) {
22765                mPackageName = packageName;
22766                mWeFroze = mFrozenPackages.add(mPackageName);
22767
22768                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22769                if (ps != null) {
22770                    killApplication(ps.name, ps.appId, userId, killReason);
22771                }
22772
22773                final PackageParser.Package p = mPackages.get(packageName);
22774                if (p != null && p.childPackages != null) {
22775                    final int N = p.childPackages.size();
22776                    mChildren = new PackageFreezer[N];
22777                    for (int i = 0; i < N; i++) {
22778                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22779                                userId, killReason);
22780                    }
22781                } else {
22782                    mChildren = null;
22783                }
22784            }
22785            mCloseGuard.open("close");
22786        }
22787
22788        @Override
22789        protected void finalize() throws Throwable {
22790            try {
22791                if (mCloseGuard != null) {
22792                    mCloseGuard.warnIfOpen();
22793                }
22794
22795                close();
22796            } finally {
22797                super.finalize();
22798            }
22799        }
22800
22801        @Override
22802        public void close() {
22803            mCloseGuard.close();
22804            if (mClosed.compareAndSet(false, true)) {
22805                synchronized (mPackages) {
22806                    if (mWeFroze) {
22807                        mFrozenPackages.remove(mPackageName);
22808                    }
22809
22810                    if (mChildren != null) {
22811                        for (PackageFreezer freezer : mChildren) {
22812                            freezer.close();
22813                        }
22814                    }
22815                }
22816            }
22817        }
22818    }
22819
22820    /**
22821     * Verify that given package is currently frozen.
22822     */
22823    private void checkPackageFrozen(String packageName) {
22824        synchronized (mPackages) {
22825            if (!mFrozenPackages.contains(packageName)) {
22826                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22827            }
22828        }
22829    }
22830
22831    @Override
22832    public int movePackage(final String packageName, final String volumeUuid) {
22833        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22834
22835        final int callingUid = Binder.getCallingUid();
22836        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22837        final int moveId = mNextMoveId.getAndIncrement();
22838        mHandler.post(new Runnable() {
22839            @Override
22840            public void run() {
22841                try {
22842                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22843                } catch (PackageManagerException e) {
22844                    Slog.w(TAG, "Failed to move " + packageName, e);
22845                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22846                }
22847            }
22848        });
22849        return moveId;
22850    }
22851
22852    private void movePackageInternal(final String packageName, final String volumeUuid,
22853            final int moveId, final int callingUid, UserHandle user)
22854                    throws PackageManagerException {
22855        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22856        final PackageManager pm = mContext.getPackageManager();
22857
22858        final boolean currentAsec;
22859        final String currentVolumeUuid;
22860        final File codeFile;
22861        final String installerPackageName;
22862        final String packageAbiOverride;
22863        final int appId;
22864        final String seinfo;
22865        final String label;
22866        final int targetSdkVersion;
22867        final PackageFreezer freezer;
22868        final int[] installedUserIds;
22869
22870        // reader
22871        synchronized (mPackages) {
22872            final PackageParser.Package pkg = mPackages.get(packageName);
22873            final PackageSetting ps = mSettings.mPackages.get(packageName);
22874            if (pkg == null
22875                    || ps == null
22876                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22877                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22878            }
22879            if (pkg.applicationInfo.isSystemApp()) {
22880                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22881                        "Cannot move system application");
22882            }
22883
22884            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22885            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22886                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22887            if (isInternalStorage && !allow3rdPartyOnInternal) {
22888                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22889                        "3rd party apps are not allowed on internal storage");
22890            }
22891
22892            if (pkg.applicationInfo.isExternalAsec()) {
22893                currentAsec = true;
22894                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22895            } else if (pkg.applicationInfo.isForwardLocked()) {
22896                currentAsec = true;
22897                currentVolumeUuid = "forward_locked";
22898            } else {
22899                currentAsec = false;
22900                currentVolumeUuid = ps.volumeUuid;
22901
22902                final File probe = new File(pkg.codePath);
22903                final File probeOat = new File(probe, "oat");
22904                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22905                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22906                            "Move only supported for modern cluster style installs");
22907                }
22908            }
22909
22910            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22911                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22912                        "Package already moved to " + volumeUuid);
22913            }
22914            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22915                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22916                        "Device admin cannot be moved");
22917            }
22918
22919            if (mFrozenPackages.contains(packageName)) {
22920                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22921                        "Failed to move already frozen package");
22922            }
22923
22924            codeFile = new File(pkg.codePath);
22925            installerPackageName = ps.installerPackageName;
22926            packageAbiOverride = ps.cpuAbiOverrideString;
22927            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22928            seinfo = pkg.applicationInfo.seInfo;
22929            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22930            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22931            freezer = freezePackage(packageName, "movePackageInternal");
22932            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22933        }
22934
22935        final Bundle extras = new Bundle();
22936        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22937        extras.putString(Intent.EXTRA_TITLE, label);
22938        mMoveCallbacks.notifyCreated(moveId, extras);
22939
22940        int installFlags;
22941        final boolean moveCompleteApp;
22942        final File measurePath;
22943
22944        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22945            installFlags = INSTALL_INTERNAL;
22946            moveCompleteApp = !currentAsec;
22947            measurePath = Environment.getDataAppDirectory(volumeUuid);
22948        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22949            installFlags = INSTALL_EXTERNAL;
22950            moveCompleteApp = false;
22951            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22952        } else {
22953            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22954            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22955                    || !volume.isMountedWritable()) {
22956                freezer.close();
22957                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22958                        "Move location not mounted private volume");
22959            }
22960
22961            Preconditions.checkState(!currentAsec);
22962
22963            installFlags = INSTALL_INTERNAL;
22964            moveCompleteApp = true;
22965            measurePath = Environment.getDataAppDirectory(volumeUuid);
22966        }
22967
22968        // If we're moving app data around, we need all the users unlocked
22969        if (moveCompleteApp) {
22970            for (int userId : installedUserIds) {
22971                if (StorageManager.isFileEncryptedNativeOrEmulated()
22972                        && !StorageManager.isUserKeyUnlocked(userId)) {
22973                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22974                            "User " + userId + " must be unlocked");
22975                }
22976            }
22977        }
22978
22979        final PackageStats stats = new PackageStats(null, -1);
22980        synchronized (mInstaller) {
22981            for (int userId : installedUserIds) {
22982                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22983                    freezer.close();
22984                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22985                            "Failed to measure package size");
22986                }
22987            }
22988        }
22989
22990        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22991                + stats.dataSize);
22992
22993        final long startFreeBytes = measurePath.getUsableSpace();
22994        final long sizeBytes;
22995        if (moveCompleteApp) {
22996            sizeBytes = stats.codeSize + stats.dataSize;
22997        } else {
22998            sizeBytes = stats.codeSize;
22999        }
23000
23001        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23002            freezer.close();
23003            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23004                    "Not enough free space to move");
23005        }
23006
23007        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23008
23009        final CountDownLatch installedLatch = new CountDownLatch(1);
23010        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23011            @Override
23012            public void onUserActionRequired(Intent intent) throws RemoteException {
23013                throw new IllegalStateException();
23014            }
23015
23016            @Override
23017            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23018                    Bundle extras) throws RemoteException {
23019                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23020                        + PackageManager.installStatusToString(returnCode, msg));
23021
23022                installedLatch.countDown();
23023                freezer.close();
23024
23025                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23026                switch (status) {
23027                    case PackageInstaller.STATUS_SUCCESS:
23028                        mMoveCallbacks.notifyStatusChanged(moveId,
23029                                PackageManager.MOVE_SUCCEEDED);
23030                        break;
23031                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23032                        mMoveCallbacks.notifyStatusChanged(moveId,
23033                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23034                        break;
23035                    default:
23036                        mMoveCallbacks.notifyStatusChanged(moveId,
23037                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23038                        break;
23039                }
23040            }
23041        };
23042
23043        final MoveInfo move;
23044        if (moveCompleteApp) {
23045            // Kick off a thread to report progress estimates
23046            new Thread() {
23047                @Override
23048                public void run() {
23049                    while (true) {
23050                        try {
23051                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23052                                break;
23053                            }
23054                        } catch (InterruptedException ignored) {
23055                        }
23056
23057                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23058                        final int progress = 10 + (int) MathUtils.constrain(
23059                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23060                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23061                    }
23062                }
23063            }.start();
23064
23065            final String dataAppName = codeFile.getName();
23066            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23067                    dataAppName, appId, seinfo, targetSdkVersion);
23068        } else {
23069            move = null;
23070        }
23071
23072        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23073
23074        final Message msg = mHandler.obtainMessage(INIT_COPY);
23075        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23076        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23077                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23078                packageAbiOverride, null /*grantedPermissions*/,
23079                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
23080        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23081        msg.obj = params;
23082
23083        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23084                System.identityHashCode(msg.obj));
23085        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23086                System.identityHashCode(msg.obj));
23087
23088        mHandler.sendMessage(msg);
23089    }
23090
23091    @Override
23092    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23093        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23094
23095        final int realMoveId = mNextMoveId.getAndIncrement();
23096        final Bundle extras = new Bundle();
23097        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23098        mMoveCallbacks.notifyCreated(realMoveId, extras);
23099
23100        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23101            @Override
23102            public void onCreated(int moveId, Bundle extras) {
23103                // Ignored
23104            }
23105
23106            @Override
23107            public void onStatusChanged(int moveId, int status, long estMillis) {
23108                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23109            }
23110        };
23111
23112        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23113        storage.setPrimaryStorageUuid(volumeUuid, callback);
23114        return realMoveId;
23115    }
23116
23117    @Override
23118    public int getMoveStatus(int moveId) {
23119        mContext.enforceCallingOrSelfPermission(
23120                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23121        return mMoveCallbacks.mLastStatus.get(moveId);
23122    }
23123
23124    @Override
23125    public void registerMoveCallback(IPackageMoveObserver callback) {
23126        mContext.enforceCallingOrSelfPermission(
23127                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23128        mMoveCallbacks.register(callback);
23129    }
23130
23131    @Override
23132    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23133        mContext.enforceCallingOrSelfPermission(
23134                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23135        mMoveCallbacks.unregister(callback);
23136    }
23137
23138    @Override
23139    public boolean setInstallLocation(int loc) {
23140        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23141                null);
23142        if (getInstallLocation() == loc) {
23143            return true;
23144        }
23145        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23146                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23147            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23148                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23149            return true;
23150        }
23151        return false;
23152   }
23153
23154    @Override
23155    public int getInstallLocation() {
23156        // allow instant app access
23157        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23158                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23159                PackageHelper.APP_INSTALL_AUTO);
23160    }
23161
23162    /** Called by UserManagerService */
23163    void cleanUpUser(UserManagerService userManager, int userHandle) {
23164        synchronized (mPackages) {
23165            mDirtyUsers.remove(userHandle);
23166            mUserNeedsBadging.delete(userHandle);
23167            mSettings.removeUserLPw(userHandle);
23168            mPendingBroadcasts.remove(userHandle);
23169            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23170            removeUnusedPackagesLPw(userManager, userHandle);
23171        }
23172    }
23173
23174    /**
23175     * We're removing userHandle and would like to remove any downloaded packages
23176     * that are no longer in use by any other user.
23177     * @param userHandle the user being removed
23178     */
23179    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23180        final boolean DEBUG_CLEAN_APKS = false;
23181        int [] users = userManager.getUserIds();
23182        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23183        while (psit.hasNext()) {
23184            PackageSetting ps = psit.next();
23185            if (ps.pkg == null) {
23186                continue;
23187            }
23188            final String packageName = ps.pkg.packageName;
23189            // Skip over if system app
23190            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23191                continue;
23192            }
23193            if (DEBUG_CLEAN_APKS) {
23194                Slog.i(TAG, "Checking package " + packageName);
23195            }
23196            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23197            if (keep) {
23198                if (DEBUG_CLEAN_APKS) {
23199                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23200                }
23201            } else {
23202                for (int i = 0; i < users.length; i++) {
23203                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23204                        keep = true;
23205                        if (DEBUG_CLEAN_APKS) {
23206                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23207                                    + users[i]);
23208                        }
23209                        break;
23210                    }
23211                }
23212            }
23213            if (!keep) {
23214                if (DEBUG_CLEAN_APKS) {
23215                    Slog.i(TAG, "  Removing package " + packageName);
23216                }
23217                mHandler.post(new Runnable() {
23218                    public void run() {
23219                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23220                                userHandle, 0);
23221                    } //end run
23222                });
23223            }
23224        }
23225    }
23226
23227    /** Called by UserManagerService */
23228    void createNewUser(int userId, String[] disallowedPackages) {
23229        synchronized (mInstallLock) {
23230            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23231        }
23232        synchronized (mPackages) {
23233            scheduleWritePackageRestrictionsLocked(userId);
23234            scheduleWritePackageListLocked(userId);
23235            applyFactoryDefaultBrowserLPw(userId);
23236            primeDomainVerificationsLPw(userId);
23237        }
23238    }
23239
23240    void onNewUserCreated(final int userId) {
23241        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23242        synchronized(mPackages) {
23243            // If permission review for legacy apps is required, we represent
23244            // dagerous permissions for such apps as always granted runtime
23245            // permissions to keep per user flag state whether review is needed.
23246            // Hence, if a new user is added we have to propagate dangerous
23247            // permission grants for these legacy apps.
23248            if (mSettings.mPermissions.mPermissionReviewRequired) {
23249// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
23250                mPermissionManager.updateAllPermissions(
23251                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
23252                        mPermissionCallback);
23253            }
23254        }
23255    }
23256
23257    @Override
23258    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23259        mContext.enforceCallingOrSelfPermission(
23260                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23261                "Only package verification agents can read the verifier device identity");
23262
23263        synchronized (mPackages) {
23264            return mSettings.getVerifierDeviceIdentityLPw();
23265        }
23266    }
23267
23268    @Override
23269    public void setPermissionEnforced(String permission, boolean enforced) {
23270        // TODO: Now that we no longer change GID for storage, this should to away.
23271        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23272                "setPermissionEnforced");
23273        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23274            synchronized (mPackages) {
23275                if (mSettings.mReadExternalStorageEnforced == null
23276                        || mSettings.mReadExternalStorageEnforced != enforced) {
23277                    mSettings.mReadExternalStorageEnforced =
23278                            enforced ? Boolean.TRUE : Boolean.FALSE;
23279                    mSettings.writeLPr();
23280                }
23281            }
23282            // kill any non-foreground processes so we restart them and
23283            // grant/revoke the GID.
23284            final IActivityManager am = ActivityManager.getService();
23285            if (am != null) {
23286                final long token = Binder.clearCallingIdentity();
23287                try {
23288                    am.killProcessesBelowForeground("setPermissionEnforcement");
23289                } catch (RemoteException e) {
23290                } finally {
23291                    Binder.restoreCallingIdentity(token);
23292                }
23293            }
23294        } else {
23295            throw new IllegalArgumentException("No selective enforcement for " + permission);
23296        }
23297    }
23298
23299    @Override
23300    @Deprecated
23301    public boolean isPermissionEnforced(String permission) {
23302        // allow instant applications
23303        return true;
23304    }
23305
23306    @Override
23307    public boolean isStorageLow() {
23308        // allow instant applications
23309        final long token = Binder.clearCallingIdentity();
23310        try {
23311            final DeviceStorageMonitorInternal
23312                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23313            if (dsm != null) {
23314                return dsm.isMemoryLow();
23315            } else {
23316                return false;
23317            }
23318        } finally {
23319            Binder.restoreCallingIdentity(token);
23320        }
23321    }
23322
23323    @Override
23324    public IPackageInstaller getPackageInstaller() {
23325        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23326            return null;
23327        }
23328        return mInstallerService;
23329    }
23330
23331    @Override
23332    public IArtManager getArtManager() {
23333        return mArtManagerService;
23334    }
23335
23336    private boolean userNeedsBadging(int userId) {
23337        int index = mUserNeedsBadging.indexOfKey(userId);
23338        if (index < 0) {
23339            final UserInfo userInfo;
23340            final long token = Binder.clearCallingIdentity();
23341            try {
23342                userInfo = sUserManager.getUserInfo(userId);
23343            } finally {
23344                Binder.restoreCallingIdentity(token);
23345            }
23346            final boolean b;
23347            if (userInfo != null && userInfo.isManagedProfile()) {
23348                b = true;
23349            } else {
23350                b = false;
23351            }
23352            mUserNeedsBadging.put(userId, b);
23353            return b;
23354        }
23355        return mUserNeedsBadging.valueAt(index);
23356    }
23357
23358    @Override
23359    public KeySet getKeySetByAlias(String packageName, String alias) {
23360        if (packageName == null || alias == null) {
23361            return null;
23362        }
23363        synchronized(mPackages) {
23364            final PackageParser.Package pkg = mPackages.get(packageName);
23365            if (pkg == null) {
23366                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23367                throw new IllegalArgumentException("Unknown package: " + packageName);
23368            }
23369            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23370            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23371                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23372                throw new IllegalArgumentException("Unknown package: " + packageName);
23373            }
23374            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23375            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23376        }
23377    }
23378
23379    @Override
23380    public KeySet getSigningKeySet(String packageName) {
23381        if (packageName == null) {
23382            return null;
23383        }
23384        synchronized(mPackages) {
23385            final int callingUid = Binder.getCallingUid();
23386            final int callingUserId = UserHandle.getUserId(callingUid);
23387            final PackageParser.Package pkg = mPackages.get(packageName);
23388            if (pkg == null) {
23389                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23390                throw new IllegalArgumentException("Unknown package: " + packageName);
23391            }
23392            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23393            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23394                // filter and pretend the package doesn't exist
23395                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23396                        + ", uid:" + callingUid);
23397                throw new IllegalArgumentException("Unknown package: " + packageName);
23398            }
23399            if (pkg.applicationInfo.uid != callingUid
23400                    && Process.SYSTEM_UID != callingUid) {
23401                throw new SecurityException("May not access signing KeySet of other apps.");
23402            }
23403            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23404            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23405        }
23406    }
23407
23408    @Override
23409    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23410        final int callingUid = Binder.getCallingUid();
23411        if (getInstantAppPackageName(callingUid) != null) {
23412            return false;
23413        }
23414        if (packageName == null || ks == null) {
23415            return false;
23416        }
23417        synchronized(mPackages) {
23418            final PackageParser.Package pkg = mPackages.get(packageName);
23419            if (pkg == null
23420                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23421                            UserHandle.getUserId(callingUid))) {
23422                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23423                throw new IllegalArgumentException("Unknown package: " + packageName);
23424            }
23425            IBinder ksh = ks.getToken();
23426            if (ksh instanceof KeySetHandle) {
23427                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23428                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23429            }
23430            return false;
23431        }
23432    }
23433
23434    @Override
23435    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23436        final int callingUid = Binder.getCallingUid();
23437        if (getInstantAppPackageName(callingUid) != null) {
23438            return false;
23439        }
23440        if (packageName == null || ks == null) {
23441            return false;
23442        }
23443        synchronized(mPackages) {
23444            final PackageParser.Package pkg = mPackages.get(packageName);
23445            if (pkg == null
23446                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23447                            UserHandle.getUserId(callingUid))) {
23448                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23449                throw new IllegalArgumentException("Unknown package: " + packageName);
23450            }
23451            IBinder ksh = ks.getToken();
23452            if (ksh instanceof KeySetHandle) {
23453                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23454                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23455            }
23456            return false;
23457        }
23458    }
23459
23460    private void deletePackageIfUnusedLPr(final String packageName) {
23461        PackageSetting ps = mSettings.mPackages.get(packageName);
23462        if (ps == null) {
23463            return;
23464        }
23465        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23466            // TODO Implement atomic delete if package is unused
23467            // It is currently possible that the package will be deleted even if it is installed
23468            // after this method returns.
23469            mHandler.post(new Runnable() {
23470                public void run() {
23471                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23472                            0, PackageManager.DELETE_ALL_USERS);
23473                }
23474            });
23475        }
23476    }
23477
23478    /**
23479     * Check and throw if the given before/after packages would be considered a
23480     * downgrade.
23481     */
23482    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23483            throws PackageManagerException {
23484        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23485            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23486                    "Update version code " + after.versionCode + " is older than current "
23487                    + before.getLongVersionCode());
23488        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23489            if (after.baseRevisionCode < before.baseRevisionCode) {
23490                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23491                        "Update base revision code " + after.baseRevisionCode
23492                        + " is older than current " + before.baseRevisionCode);
23493            }
23494
23495            if (!ArrayUtils.isEmpty(after.splitNames)) {
23496                for (int i = 0; i < after.splitNames.length; i++) {
23497                    final String splitName = after.splitNames[i];
23498                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23499                    if (j != -1) {
23500                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23501                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23502                                    "Update split " + splitName + " revision code "
23503                                    + after.splitRevisionCodes[i] + " is older than current "
23504                                    + before.splitRevisionCodes[j]);
23505                        }
23506                    }
23507                }
23508            }
23509        }
23510    }
23511
23512    private static class MoveCallbacks extends Handler {
23513        private static final int MSG_CREATED = 1;
23514        private static final int MSG_STATUS_CHANGED = 2;
23515
23516        private final RemoteCallbackList<IPackageMoveObserver>
23517                mCallbacks = new RemoteCallbackList<>();
23518
23519        private final SparseIntArray mLastStatus = new SparseIntArray();
23520
23521        public MoveCallbacks(Looper looper) {
23522            super(looper);
23523        }
23524
23525        public void register(IPackageMoveObserver callback) {
23526            mCallbacks.register(callback);
23527        }
23528
23529        public void unregister(IPackageMoveObserver callback) {
23530            mCallbacks.unregister(callback);
23531        }
23532
23533        @Override
23534        public void handleMessage(Message msg) {
23535            final SomeArgs args = (SomeArgs) msg.obj;
23536            final int n = mCallbacks.beginBroadcast();
23537            for (int i = 0; i < n; i++) {
23538                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23539                try {
23540                    invokeCallback(callback, msg.what, args);
23541                } catch (RemoteException ignored) {
23542                }
23543            }
23544            mCallbacks.finishBroadcast();
23545            args.recycle();
23546        }
23547
23548        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23549                throws RemoteException {
23550            switch (what) {
23551                case MSG_CREATED: {
23552                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23553                    break;
23554                }
23555                case MSG_STATUS_CHANGED: {
23556                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23557                    break;
23558                }
23559            }
23560        }
23561
23562        private void notifyCreated(int moveId, Bundle extras) {
23563            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23564
23565            final SomeArgs args = SomeArgs.obtain();
23566            args.argi1 = moveId;
23567            args.arg2 = extras;
23568            obtainMessage(MSG_CREATED, args).sendToTarget();
23569        }
23570
23571        private void notifyStatusChanged(int moveId, int status) {
23572            notifyStatusChanged(moveId, status, -1);
23573        }
23574
23575        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23576            Slog.v(TAG, "Move " + moveId + " status " + status);
23577
23578            final SomeArgs args = SomeArgs.obtain();
23579            args.argi1 = moveId;
23580            args.argi2 = status;
23581            args.arg3 = estMillis;
23582            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23583
23584            synchronized (mLastStatus) {
23585                mLastStatus.put(moveId, status);
23586            }
23587        }
23588    }
23589
23590    private final static class OnPermissionChangeListeners extends Handler {
23591        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23592
23593        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23594                new RemoteCallbackList<>();
23595
23596        public OnPermissionChangeListeners(Looper looper) {
23597            super(looper);
23598        }
23599
23600        @Override
23601        public void handleMessage(Message msg) {
23602            switch (msg.what) {
23603                case MSG_ON_PERMISSIONS_CHANGED: {
23604                    final int uid = msg.arg1;
23605                    handleOnPermissionsChanged(uid);
23606                } break;
23607            }
23608        }
23609
23610        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23611            mPermissionListeners.register(listener);
23612
23613        }
23614
23615        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23616            mPermissionListeners.unregister(listener);
23617        }
23618
23619        public void onPermissionsChanged(int uid) {
23620            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23621                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23622            }
23623        }
23624
23625        private void handleOnPermissionsChanged(int uid) {
23626            final int count = mPermissionListeners.beginBroadcast();
23627            try {
23628                for (int i = 0; i < count; i++) {
23629                    IOnPermissionsChangeListener callback = mPermissionListeners
23630                            .getBroadcastItem(i);
23631                    try {
23632                        callback.onPermissionsChanged(uid);
23633                    } catch (RemoteException e) {
23634                        Log.e(TAG, "Permission listener is dead", e);
23635                    }
23636                }
23637            } finally {
23638                mPermissionListeners.finishBroadcast();
23639            }
23640        }
23641    }
23642
23643    private class PackageManagerNative extends IPackageManagerNative.Stub {
23644        @Override
23645        public String[] getNamesForUids(int[] uids) throws RemoteException {
23646            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23647            // massage results so they can be parsed by the native binder
23648            for (int i = results.length - 1; i >= 0; --i) {
23649                if (results[i] == null) {
23650                    results[i] = "";
23651                }
23652            }
23653            return results;
23654        }
23655
23656        // NB: this differentiates between preloads and sideloads
23657        @Override
23658        public String getInstallerForPackage(String packageName) throws RemoteException {
23659            final String installerName = getInstallerPackageName(packageName);
23660            if (!TextUtils.isEmpty(installerName)) {
23661                return installerName;
23662            }
23663            // differentiate between preload and sideload
23664            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23665            ApplicationInfo appInfo = getApplicationInfo(packageName,
23666                                    /*flags*/ 0,
23667                                    /*userId*/ callingUser);
23668            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23669                return "preload";
23670            }
23671            return "";
23672        }
23673
23674        @Override
23675        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23676            try {
23677                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23678                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23679                if (pInfo != null) {
23680                    return pInfo.getLongVersionCode();
23681                }
23682            } catch (Exception e) {
23683            }
23684            return 0;
23685        }
23686    }
23687
23688    private class PackageManagerInternalImpl extends PackageManagerInternal {
23689        @Override
23690        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23691                int flagValues, int userId) {
23692            PackageManagerService.this.updatePermissionFlags(
23693                    permName, packageName, flagMask, flagValues, userId);
23694        }
23695
23696        @Override
23697        public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) {
23698            SigningDetails sd = getSigningDetails(packageName);
23699            if (sd == null) {
23700                return false;
23701            }
23702            return sd.hasSha256Certificate(restoringFromSigHash,
23703                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23704        }
23705
23706        @Override
23707        public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) {
23708            SigningDetails sd = getSigningDetails(packageName);
23709            if (sd == null) {
23710                return false;
23711            }
23712            return sd.hasCertificate(restoringFromSig,
23713                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23714        }
23715
23716        @Override
23717        public boolean hasSignatureCapability(int serverUid, int clientUid,
23718                @SigningDetails.CertCapabilities int capability) {
23719            SigningDetails serverSigningDetails = getSigningDetails(serverUid);
23720            SigningDetails clientSigningDetails = getSigningDetails(clientUid);
23721            return serverSigningDetails.checkCapability(clientSigningDetails, capability)
23722                    || clientSigningDetails.hasAncestorOrSelf(serverSigningDetails);
23723
23724        }
23725
23726        private SigningDetails getSigningDetails(@NonNull String packageName) {
23727            synchronized (mPackages) {
23728                PackageParser.Package p = mPackages.get(packageName);
23729                if (p == null) {
23730                    return null;
23731                }
23732                return p.mSigningDetails;
23733            }
23734        }
23735
23736        private SigningDetails getSigningDetails(int uid) {
23737            synchronized (mPackages) {
23738                final int appId = UserHandle.getAppId(uid);
23739                final Object obj = mSettings.getUserIdLPr(appId);
23740                if (obj != null) {
23741                    if (obj instanceof SharedUserSetting) {
23742                        return ((SharedUserSetting) obj).signatures.mSigningDetails;
23743                    } else if (obj instanceof PackageSetting) {
23744                        final PackageSetting ps = (PackageSetting) obj;
23745                        return ps.signatures.mSigningDetails;
23746                    }
23747                }
23748                return SigningDetails.UNKNOWN;
23749            }
23750        }
23751
23752        @Override
23753        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23754            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23755        }
23756
23757        @Override
23758        public boolean isInstantApp(String packageName, int userId) {
23759            return PackageManagerService.this.isInstantApp(packageName, userId);
23760        }
23761
23762        @Override
23763        public String getInstantAppPackageName(int uid) {
23764            return PackageManagerService.this.getInstantAppPackageName(uid);
23765        }
23766
23767        @Override
23768        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23769            synchronized (mPackages) {
23770                return PackageManagerService.this.filterAppAccessLPr(
23771                        (PackageSetting) pkg.mExtras, callingUid, userId);
23772            }
23773        }
23774
23775        @Override
23776        public PackageParser.Package getPackage(String packageName) {
23777            synchronized (mPackages) {
23778                packageName = resolveInternalPackageNameLPr(
23779                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23780                return mPackages.get(packageName);
23781            }
23782        }
23783
23784        @Override
23785        public PackageList getPackageList(PackageListObserver observer) {
23786            synchronized (mPackages) {
23787                final int N = mPackages.size();
23788                final ArrayList<String> list = new ArrayList<>(N);
23789                for (int i = 0; i < N; i++) {
23790                    list.add(mPackages.keyAt(i));
23791                }
23792                final PackageList packageList = new PackageList(list, observer);
23793                if (observer != null) {
23794                    mPackageListObservers.add(packageList);
23795                }
23796                return packageList;
23797            }
23798        }
23799
23800        @Override
23801        public void removePackageListObserver(PackageListObserver observer) {
23802            synchronized (mPackages) {
23803                mPackageListObservers.remove(observer);
23804            }
23805        }
23806
23807        @Override
23808        public PackageParser.Package getDisabledPackage(String packageName) {
23809            synchronized (mPackages) {
23810                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23811                return (ps != null) ? ps.pkg : null;
23812            }
23813        }
23814
23815        @Override
23816        public String getKnownPackageName(int knownPackage, int userId) {
23817            switch(knownPackage) {
23818                case PackageManagerInternal.PACKAGE_BROWSER:
23819                    return getDefaultBrowserPackageName(userId);
23820                case PackageManagerInternal.PACKAGE_INSTALLER:
23821                    return mRequiredInstallerPackage;
23822                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23823                    return mSetupWizardPackage;
23824                case PackageManagerInternal.PACKAGE_SYSTEM:
23825                    return "android";
23826                case PackageManagerInternal.PACKAGE_VERIFIER:
23827                    return mRequiredVerifierPackage;
23828                case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER:
23829                    return mSystemTextClassifierPackage;
23830            }
23831            return null;
23832        }
23833
23834        @Override
23835        public boolean isResolveActivityComponent(ComponentInfo component) {
23836            return mResolveActivity.packageName.equals(component.packageName)
23837                    && mResolveActivity.name.equals(component.name);
23838        }
23839
23840        @Override
23841        public void setLocationPackagesProvider(PackagesProvider provider) {
23842            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23843        }
23844
23845        @Override
23846        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23847            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23848        }
23849
23850        @Override
23851        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23852            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23853        }
23854
23855        @Override
23856        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23857            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23858        }
23859
23860        @Override
23861        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23862            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23863        }
23864
23865        @Override
23866        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23867            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23868        }
23869
23870        @Override
23871        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23872            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23873        }
23874
23875        @Override
23876        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23877            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23878        }
23879
23880        @Override
23881        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23882            synchronized (mPackages) {
23883                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23884            }
23885            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23886        }
23887
23888        @Override
23889        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23890            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23891                    packageName, userId);
23892        }
23893
23894        @Override
23895        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23896            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23897                    packageName, userId);
23898        }
23899
23900        @Override
23901        public void setKeepUninstalledPackages(final List<String> packageList) {
23902            Preconditions.checkNotNull(packageList);
23903            List<String> removedFromList = null;
23904            synchronized (mPackages) {
23905                if (mKeepUninstalledPackages != null) {
23906                    final int packagesCount = mKeepUninstalledPackages.size();
23907                    for (int i = 0; i < packagesCount; i++) {
23908                        String oldPackage = mKeepUninstalledPackages.get(i);
23909                        if (packageList != null && packageList.contains(oldPackage)) {
23910                            continue;
23911                        }
23912                        if (removedFromList == null) {
23913                            removedFromList = new ArrayList<>();
23914                        }
23915                        removedFromList.add(oldPackage);
23916                    }
23917                }
23918                mKeepUninstalledPackages = new ArrayList<>(packageList);
23919                if (removedFromList != null) {
23920                    final int removedCount = removedFromList.size();
23921                    for (int i = 0; i < removedCount; i++) {
23922                        deletePackageIfUnusedLPr(removedFromList.get(i));
23923                    }
23924                }
23925            }
23926        }
23927
23928        @Override
23929        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23930            synchronized (mPackages) {
23931                return mPermissionManager.isPermissionsReviewRequired(
23932                        mPackages.get(packageName), userId);
23933            }
23934        }
23935
23936        @Override
23937        public PackageInfo getPackageInfo(
23938                String packageName, int flags, int filterCallingUid, int userId) {
23939            return PackageManagerService.this
23940                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23941                            flags, filterCallingUid, userId);
23942        }
23943
23944        @Override
23945        public Bundle getSuspendedPackageLauncherExtras(String packageName, int userId) {
23946            synchronized (mPackages) {
23947                final PackageSetting ps = mSettings.mPackages.get(packageName);
23948                PersistableBundle launcherExtras = null;
23949                if (ps != null) {
23950                    launcherExtras = ps.readUserState(userId).suspendedLauncherExtras;
23951                }
23952                return (launcherExtras != null) ? new Bundle(launcherExtras.deepCopy()) : null;
23953            }
23954        }
23955
23956        @Override
23957        public boolean isPackageSuspended(String packageName, int userId) {
23958            synchronized (mPackages) {
23959                final PackageSetting ps = mSettings.mPackages.get(packageName);
23960                return (ps != null) ? ps.getSuspended(userId) : false;
23961            }
23962        }
23963
23964        @Override
23965        public String getSuspendingPackage(String suspendedPackage, int userId) {
23966            synchronized (mPackages) {
23967                final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
23968                return (ps != null) ? ps.readUserState(userId).suspendingPackage : null;
23969            }
23970        }
23971
23972        @Override
23973        public String getSuspendedDialogMessage(String suspendedPackage, int userId) {
23974            synchronized (mPackages) {
23975                final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
23976                return (ps != null) ? ps.readUserState(userId).dialogMessage : null;
23977            }
23978        }
23979
23980        @Override
23981        public int getPackageUid(String packageName, int flags, int userId) {
23982            return PackageManagerService.this
23983                    .getPackageUid(packageName, flags, userId);
23984        }
23985
23986        @Override
23987        public ApplicationInfo getApplicationInfo(
23988                String packageName, int flags, int filterCallingUid, int userId) {
23989            return PackageManagerService.this
23990                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23991        }
23992
23993        @Override
23994        public ActivityInfo getActivityInfo(
23995                ComponentName component, int flags, int filterCallingUid, int userId) {
23996            return PackageManagerService.this
23997                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23998        }
23999
24000        @Override
24001        public List<ResolveInfo> queryIntentActivities(
24002                Intent intent, int flags, int filterCallingUid, int userId) {
24003            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24004            return PackageManagerService.this
24005                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24006                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
24007        }
24008
24009        @Override
24010        public List<ResolveInfo> queryIntentServices(
24011                Intent intent, int flags, int callingUid, int userId) {
24012            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24013            return PackageManagerService.this
24014                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
24015                            false);
24016        }
24017
24018        @Override
24019        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24020                int userId) {
24021            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24022        }
24023
24024        @Override
24025        public ComponentName getDefaultHomeActivity(int userId) {
24026            return PackageManagerService.this.getDefaultHomeActivity(userId);
24027        }
24028
24029        @Override
24030        public void setDeviceAndProfileOwnerPackages(
24031                int deviceOwnerUserId, String deviceOwnerPackage,
24032                SparseArray<String> profileOwnerPackages) {
24033            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24034                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24035
24036            final ArraySet<Integer> usersWithPoOrDo = new ArraySet<>();
24037            if (deviceOwnerPackage != null) {
24038                usersWithPoOrDo.add(deviceOwnerUserId);
24039            }
24040            final int sz = profileOwnerPackages.size();
24041            for (int i = 0; i < sz; i++) {
24042                if (profileOwnerPackages.valueAt(i) != null) {
24043                    usersWithPoOrDo.add(profileOwnerPackages.keyAt(i));
24044                }
24045            }
24046            unsuspendForNonSystemSuspendingPackages(usersWithPoOrDo);
24047        }
24048
24049        @Override
24050        public boolean isPackageDataProtected(int userId, String packageName) {
24051            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24052        }
24053
24054        @Override
24055        public boolean isPackageStateProtected(String packageName, int userId) {
24056            return mProtectedPackages.isPackageStateProtected(userId, packageName);
24057        }
24058
24059        @Override
24060        public boolean isPackageEphemeral(int userId, String packageName) {
24061            synchronized (mPackages) {
24062                final PackageSetting ps = mSettings.mPackages.get(packageName);
24063                return ps != null ? ps.getInstantApp(userId) : false;
24064            }
24065        }
24066
24067        @Override
24068        public boolean wasPackageEverLaunched(String packageName, int userId) {
24069            synchronized (mPackages) {
24070                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24071            }
24072        }
24073
24074        @Override
24075        public void grantRuntimePermission(String packageName, String permName, int userId,
24076                boolean overridePolicy) {
24077            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
24078                    permName, packageName, overridePolicy, getCallingUid(), userId,
24079                    mPermissionCallback);
24080        }
24081
24082        @Override
24083        public void revokeRuntimePermission(String packageName, String permName, int userId,
24084                boolean overridePolicy) {
24085            mPermissionManager.revokeRuntimePermission(
24086                    permName, packageName, overridePolicy, getCallingUid(), userId,
24087                    mPermissionCallback);
24088        }
24089
24090        @Override
24091        public String getNameForUid(int uid) {
24092            return PackageManagerService.this.getNameForUid(uid);
24093        }
24094
24095        @Override
24096        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24097                Intent origIntent, String resolvedType, String callingPackage,
24098                Bundle verificationBundle, int userId) {
24099            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24100                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24101                    userId);
24102        }
24103
24104        @Override
24105        public void grantEphemeralAccess(int userId, Intent intent,
24106                int targetAppId, int ephemeralAppId) {
24107            synchronized (mPackages) {
24108                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24109                        targetAppId, ephemeralAppId);
24110            }
24111        }
24112
24113        @Override
24114        public boolean isInstantAppInstallerComponent(ComponentName component) {
24115            synchronized (mPackages) {
24116                return mInstantAppInstallerActivity != null
24117                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24118            }
24119        }
24120
24121        @Override
24122        public void pruneInstantApps() {
24123            mInstantAppRegistry.pruneInstantApps();
24124        }
24125
24126        @Override
24127        public String getSetupWizardPackageName() {
24128            return mSetupWizardPackage;
24129        }
24130
24131        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24132            if (policy != null) {
24133                mExternalSourcesPolicy = policy;
24134            }
24135        }
24136
24137        @Override
24138        public boolean isPackagePersistent(String packageName) {
24139            synchronized (mPackages) {
24140                PackageParser.Package pkg = mPackages.get(packageName);
24141                return pkg != null
24142                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24143                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24144                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24145                        : false;
24146            }
24147        }
24148
24149        @Override
24150        public boolean isLegacySystemApp(Package pkg) {
24151            synchronized (mPackages) {
24152                final PackageSetting ps = (PackageSetting) pkg.mExtras;
24153                return mPromoteSystemApps
24154                        && ps.isSystem()
24155                        && mExistingSystemPackages.contains(ps.name);
24156            }
24157        }
24158
24159        @Override
24160        public List<PackageInfo> getOverlayPackages(int userId) {
24161            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24162            synchronized (mPackages) {
24163                for (PackageParser.Package p : mPackages.values()) {
24164                    if (p.mOverlayTarget != null) {
24165                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24166                        if (pkg != null) {
24167                            overlayPackages.add(pkg);
24168                        }
24169                    }
24170                }
24171            }
24172            return overlayPackages;
24173        }
24174
24175        @Override
24176        public List<String> getTargetPackageNames(int userId) {
24177            List<String> targetPackages = new ArrayList<>();
24178            synchronized (mPackages) {
24179                for (PackageParser.Package p : mPackages.values()) {
24180                    if (p.mOverlayTarget == null) {
24181                        targetPackages.add(p.packageName);
24182                    }
24183                }
24184            }
24185            return targetPackages;
24186        }
24187
24188        @Override
24189        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24190                @Nullable List<String> overlayPackageNames) {
24191            synchronized (mPackages) {
24192                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24193                    Slog.e(TAG, "failed to find package " + targetPackageName);
24194                    return false;
24195                }
24196                ArrayList<String> overlayPaths = null;
24197                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24198                    final int N = overlayPackageNames.size();
24199                    overlayPaths = new ArrayList<>(N);
24200                    for (int i = 0; i < N; i++) {
24201                        final String packageName = overlayPackageNames.get(i);
24202                        final PackageParser.Package pkg = mPackages.get(packageName);
24203                        if (pkg == null) {
24204                            Slog.e(TAG, "failed to find package " + packageName);
24205                            return false;
24206                        }
24207                        overlayPaths.add(pkg.baseCodePath);
24208                    }
24209                }
24210
24211                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24212                ps.setOverlayPaths(overlayPaths, userId);
24213                return true;
24214            }
24215        }
24216
24217        @Override
24218        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24219                int flags, int userId, boolean resolveForStart, int filterCallingUid) {
24220            return resolveIntentInternal(
24221                    intent, resolvedType, flags, userId, resolveForStart, filterCallingUid);
24222        }
24223
24224        @Override
24225        public ResolveInfo resolveService(Intent intent, String resolvedType,
24226                int flags, int userId, int callingUid) {
24227            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24228        }
24229
24230        @Override
24231        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
24232            return PackageManagerService.this.resolveContentProviderInternal(
24233                    name, flags, userId);
24234        }
24235
24236        @Override
24237        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24238            synchronized (mPackages) {
24239                mIsolatedOwners.put(isolatedUid, ownerUid);
24240            }
24241        }
24242
24243        @Override
24244        public void removeIsolatedUid(int isolatedUid) {
24245            synchronized (mPackages) {
24246                mIsolatedOwners.delete(isolatedUid);
24247            }
24248        }
24249
24250        @Override
24251        public int getUidTargetSdkVersion(int uid) {
24252            synchronized (mPackages) {
24253                return getUidTargetSdkVersionLockedLPr(uid);
24254            }
24255        }
24256
24257        @Override
24258        public int getPackageTargetSdkVersion(String packageName) {
24259            synchronized (mPackages) {
24260                return getPackageTargetSdkVersionLockedLPr(packageName);
24261            }
24262        }
24263
24264        @Override
24265        public boolean canAccessInstantApps(int callingUid, int userId) {
24266            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24267        }
24268
24269        @Override
24270        public boolean canAccessComponent(int callingUid, ComponentName component, int userId) {
24271            synchronized (mPackages) {
24272                final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
24273                return !PackageManagerService.this.filterAppAccessLPr(
24274                        ps, callingUid, component, TYPE_UNKNOWN, userId);
24275            }
24276        }
24277
24278        @Override
24279        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
24280            synchronized (mPackages) {
24281                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
24282            }
24283        }
24284
24285        @Override
24286        public void notifyPackageUse(String packageName, int reason) {
24287            synchronized (mPackages) {
24288                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
24289            }
24290        }
24291    }
24292
24293    @Override
24294    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24295        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24296        synchronized (mPackages) {
24297            final long identity = Binder.clearCallingIdentity();
24298            try {
24299                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
24300                        packageNames, userId);
24301            } finally {
24302                Binder.restoreCallingIdentity(identity);
24303            }
24304        }
24305    }
24306
24307    @Override
24308    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24309        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24310        synchronized (mPackages) {
24311            final long identity = Binder.clearCallingIdentity();
24312            try {
24313                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
24314                        packageNames, userId);
24315            } finally {
24316                Binder.restoreCallingIdentity(identity);
24317            }
24318        }
24319    }
24320
24321    @Override
24322    public void grantDefaultPermissionsToEnabledTelephonyDataServices(
24323            String[] packageNames, int userId) {
24324        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledTelephonyDataServices");
24325        synchronized (mPackages) {
24326            Binder.withCleanCallingIdentity( () -> {
24327                mDefaultPermissionPolicy.
24328                        grantDefaultPermissionsToEnabledTelephonyDataServices(
24329                                packageNames, userId);
24330            });
24331        }
24332    }
24333
24334    @Override
24335    public void revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24336            String[] packageNames, int userId) {
24337        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromDisabledTelephonyDataServices");
24338        synchronized (mPackages) {
24339            Binder.withCleanCallingIdentity( () -> {
24340                mDefaultPermissionPolicy.
24341                        revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24342                                packageNames, userId);
24343            });
24344        }
24345    }
24346
24347    @Override
24348    public void grantDefaultPermissionsToActiveLuiApp(String packageName, int userId) {
24349        enforceSystemOrPhoneCaller("grantDefaultPermissionsToActiveLuiApp");
24350        synchronized (mPackages) {
24351            final long identity = Binder.clearCallingIdentity();
24352            try {
24353                mDefaultPermissionPolicy.grantDefaultPermissionsToActiveLuiApp(
24354                        packageName, userId);
24355            } finally {
24356                Binder.restoreCallingIdentity(identity);
24357            }
24358        }
24359    }
24360
24361    @Override
24362    public void revokeDefaultPermissionsFromLuiApps(String[] packageNames, int userId) {
24363        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromLuiApps");
24364        synchronized (mPackages) {
24365            final long identity = Binder.clearCallingIdentity();
24366            try {
24367                mDefaultPermissionPolicy.revokeDefaultPermissionsFromLuiApps(packageNames, userId);
24368            } finally {
24369                Binder.restoreCallingIdentity(identity);
24370            }
24371        }
24372    }
24373
24374    private static void enforceSystemOrPhoneCaller(String tag) {
24375        int callingUid = Binder.getCallingUid();
24376        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24377            throw new SecurityException(
24378                    "Cannot call " + tag + " from UID " + callingUid);
24379        }
24380    }
24381
24382    boolean isHistoricalPackageUsageAvailable() {
24383        return mPackageUsage.isHistoricalPackageUsageAvailable();
24384    }
24385
24386    /**
24387     * Return a <b>copy</b> of the collection of packages known to the package manager.
24388     * @return A copy of the values of mPackages.
24389     */
24390    Collection<PackageParser.Package> getPackages() {
24391        synchronized (mPackages) {
24392            return new ArrayList<>(mPackages.values());
24393        }
24394    }
24395
24396    /**
24397     * Logs process start information (including base APK hash) to the security log.
24398     * @hide
24399     */
24400    @Override
24401    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24402            String apkFile, int pid) {
24403        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24404            return;
24405        }
24406        if (!SecurityLog.isLoggingEnabled()) {
24407            return;
24408        }
24409        Bundle data = new Bundle();
24410        data.putLong("startTimestamp", System.currentTimeMillis());
24411        data.putString("processName", processName);
24412        data.putInt("uid", uid);
24413        data.putString("seinfo", seinfo);
24414        data.putString("apkFile", apkFile);
24415        data.putInt("pid", pid);
24416        Message msg = mProcessLoggingHandler.obtainMessage(
24417                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24418        msg.setData(data);
24419        mProcessLoggingHandler.sendMessage(msg);
24420    }
24421
24422    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24423        return mCompilerStats.getPackageStats(pkgName);
24424    }
24425
24426    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24427        return getOrCreateCompilerPackageStats(pkg.packageName);
24428    }
24429
24430    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24431        return mCompilerStats.getOrCreatePackageStats(pkgName);
24432    }
24433
24434    public void deleteCompilerPackageStats(String pkgName) {
24435        mCompilerStats.deletePackageStats(pkgName);
24436    }
24437
24438    @Override
24439    public int getInstallReason(String packageName, int userId) {
24440        final int callingUid = Binder.getCallingUid();
24441        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24442                true /* requireFullPermission */, false /* checkShell */,
24443                "get install reason");
24444        synchronized (mPackages) {
24445            final PackageSetting ps = mSettings.mPackages.get(packageName);
24446            if (filterAppAccessLPr(ps, callingUid, userId)) {
24447                return PackageManager.INSTALL_REASON_UNKNOWN;
24448            }
24449            if (ps != null) {
24450                return ps.getInstallReason(userId);
24451            }
24452        }
24453        return PackageManager.INSTALL_REASON_UNKNOWN;
24454    }
24455
24456    @Override
24457    public boolean canRequestPackageInstalls(String packageName, int userId) {
24458        return canRequestPackageInstallsInternal(packageName, 0, userId,
24459                true /* throwIfPermNotDeclared*/);
24460    }
24461
24462    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24463            boolean throwIfPermNotDeclared) {
24464        int callingUid = Binder.getCallingUid();
24465        int uid = getPackageUid(packageName, 0, userId);
24466        if (callingUid != uid && callingUid != Process.ROOT_UID
24467                && callingUid != Process.SYSTEM_UID) {
24468            throw new SecurityException(
24469                    "Caller uid " + callingUid + " does not own package " + packageName);
24470        }
24471        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24472        if (info == null) {
24473            return false;
24474        }
24475        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24476            return false;
24477        }
24478        if (isInstantApp(packageName, userId)) {
24479            return false;
24480        }
24481        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24482        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24483        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24484            if (throwIfPermNotDeclared) {
24485                throw new SecurityException("Need to declare " + appOpPermission
24486                        + " to call this api");
24487            } else {
24488                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24489                return false;
24490            }
24491        }
24492        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24493            return false;
24494        }
24495        if (mExternalSourcesPolicy != null) {
24496            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24497            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24498                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24499            }
24500        }
24501        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24502    }
24503
24504    @Override
24505    public ComponentName getInstantAppResolverSettingsComponent() {
24506        return mInstantAppResolverSettingsComponent;
24507    }
24508
24509    @Override
24510    public ComponentName getInstantAppInstallerComponent() {
24511        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24512            return null;
24513        }
24514        return mInstantAppInstallerActivity == null
24515                ? null : mInstantAppInstallerActivity.getComponentName();
24516    }
24517
24518    @Override
24519    public String getInstantAppAndroidId(String packageName, int userId) {
24520        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24521                "getInstantAppAndroidId");
24522        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24523                true /* requireFullPermission */, false /* checkShell */,
24524                "getInstantAppAndroidId");
24525        // Make sure the target is an Instant App.
24526        if (!isInstantApp(packageName, userId)) {
24527            return null;
24528        }
24529        synchronized (mPackages) {
24530            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24531        }
24532    }
24533
24534    boolean canHaveOatDir(String packageName) {
24535        synchronized (mPackages) {
24536            PackageParser.Package p = mPackages.get(packageName);
24537            if (p == null) {
24538                return false;
24539            }
24540            return p.canHaveOatDir();
24541        }
24542    }
24543
24544    private String getOatDir(PackageParser.Package pkg) {
24545        if (!pkg.canHaveOatDir()) {
24546            return null;
24547        }
24548        File codePath = new File(pkg.codePath);
24549        if (codePath.isDirectory()) {
24550            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24551        }
24552        return null;
24553    }
24554
24555    void deleteOatArtifactsOfPackage(String packageName) {
24556        final String[] instructionSets;
24557        final List<String> codePaths;
24558        final String oatDir;
24559        final PackageParser.Package pkg;
24560        synchronized (mPackages) {
24561            pkg = mPackages.get(packageName);
24562        }
24563        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24564        codePaths = pkg.getAllCodePaths();
24565        oatDir = getOatDir(pkg);
24566
24567        for (String codePath : codePaths) {
24568            for (String isa : instructionSets) {
24569                try {
24570                    mInstaller.deleteOdex(codePath, isa, oatDir);
24571                } catch (InstallerException e) {
24572                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24573                }
24574            }
24575        }
24576    }
24577
24578    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24579        Set<String> unusedPackages = new HashSet<>();
24580        long currentTimeInMillis = System.currentTimeMillis();
24581        synchronized (mPackages) {
24582            for (PackageParser.Package pkg : mPackages.values()) {
24583                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24584                if (ps == null) {
24585                    continue;
24586                }
24587                PackageDexUsage.PackageUseInfo packageUseInfo =
24588                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24589                if (PackageManagerServiceUtils
24590                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24591                                downgradeTimeThresholdMillis, packageUseInfo,
24592                                pkg.getLatestPackageUseTimeInMills(),
24593                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24594                    unusedPackages.add(pkg.packageName);
24595                }
24596            }
24597        }
24598        return unusedPackages;
24599    }
24600
24601    @Override
24602    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24603            int userId) {
24604        final int callingUid = Binder.getCallingUid();
24605        final int callingAppId = UserHandle.getAppId(callingUid);
24606
24607        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24608                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24609
24610        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24611                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24612            throw new SecurityException("Caller must have the "
24613                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24614        }
24615
24616        synchronized(mPackages) {
24617            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24618            scheduleWritePackageRestrictionsLocked(userId);
24619        }
24620    }
24621
24622    @Nullable
24623    @Override
24624    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24625        final int callingUid = Binder.getCallingUid();
24626        final int callingAppId = UserHandle.getAppId(callingUid);
24627
24628        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24629                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24630
24631        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24632                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24633            throw new SecurityException("Caller must have the "
24634                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24635        }
24636
24637        synchronized(mPackages) {
24638            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24639        }
24640    }
24641
24642    @Override
24643    public boolean isPackageStateProtected(@NonNull String packageName, @UserIdInt int userId) {
24644        final int callingUid = Binder.getCallingUid();
24645        final int callingAppId = UserHandle.getAppId(callingUid);
24646
24647        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24648                false /*requireFullPermission*/, true /*checkShell*/, "isPackageStateProtected");
24649
24650        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID
24651                && checkUidPermission(MANAGE_DEVICE_ADMINS, callingUid) != PERMISSION_GRANTED) {
24652            throw new SecurityException("Caller must have the "
24653                    + MANAGE_DEVICE_ADMINS + " permission.");
24654        }
24655
24656        return mProtectedPackages.isPackageStateProtected(userId, packageName);
24657    }
24658}
24659
24660interface PackageSender {
24661    /**
24662     * @param userIds User IDs where the action occurred on a full application
24663     * @param instantUserIds User IDs where the action occurred on an instant application
24664     */
24665    void sendPackageBroadcast(final String action, final String pkg,
24666        final Bundle extras, final int flags, final String targetPkg,
24667        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24668    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24669        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24670    void notifyPackageAdded(String packageName);
24671    void notifyPackageRemoved(String packageName);
24672}
24673