PackageManagerService.java revision 1df26b9b26ba3c6474765e6caf9d2045835995cd
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;
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendElement;
96import static com.android.internal.util.ArrayUtils.appendInt;
97import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
100import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
101import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
104import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
105import static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
106import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
107import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
108import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
109import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
110import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
111import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
115
116import android.Manifest;
117import android.annotation.IntDef;
118import android.annotation.NonNull;
119import android.annotation.Nullable;
120import android.annotation.UserIdInt;
121import android.app.ActivityManager;
122import android.app.ActivityManagerInternal;
123import android.app.AppOpsManager;
124import android.app.IActivityManager;
125import android.app.ResourcesManager;
126import android.app.admin.IDevicePolicyManager;
127import android.app.admin.SecurityLog;
128import android.app.backup.IBackupManager;
129import android.content.BroadcastReceiver;
130import android.content.ComponentName;
131import android.content.ContentResolver;
132import android.content.Context;
133import android.content.IIntentReceiver;
134import android.content.Intent;
135import android.content.IntentFilter;
136import android.content.IntentSender;
137import android.content.IntentSender.SendIntentException;
138import android.content.ServiceConnection;
139import android.content.pm.ActivityInfo;
140import android.content.pm.ApplicationInfo;
141import android.content.pm.AppsQueryHelper;
142import android.content.pm.AuxiliaryResolveInfo;
143import android.content.pm.ChangedPackages;
144import android.content.pm.ComponentInfo;
145import android.content.pm.FallbackCategoryProvider;
146import android.content.pm.FeatureInfo;
147import android.content.pm.IDexModuleRegisterCallback;
148import android.content.pm.IOnPermissionsChangeListener;
149import android.content.pm.IPackageDataObserver;
150import android.content.pm.IPackageDeleteObserver;
151import android.content.pm.IPackageDeleteObserver2;
152import android.content.pm.IPackageInstallObserver2;
153import android.content.pm.IPackageInstaller;
154import android.content.pm.IPackageManager;
155import android.content.pm.IPackageManagerNative;
156import android.content.pm.IPackageMoveObserver;
157import android.content.pm.IPackageStatsObserver;
158import android.content.pm.InstantAppInfo;
159import android.content.pm.InstantAppRequest;
160import android.content.pm.InstantAppResolveInfo;
161import android.content.pm.InstrumentationInfo;
162import android.content.pm.IntentFilterVerificationInfo;
163import android.content.pm.KeySet;
164import android.content.pm.PackageCleanItem;
165import android.content.pm.PackageInfo;
166import android.content.pm.PackageInfoLite;
167import android.content.pm.PackageInstaller;
168import android.content.pm.PackageList;
169import android.content.pm.PackageManager;
170import android.content.pm.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.app.SuspendedAppActivity;
279import com.android.internal.content.NativeLibraryHelper;
280import com.android.internal.content.PackageHelper;
281import com.android.internal.logging.MetricsLogger;
282import com.android.internal.os.IParcelFileDescriptorFactory;
283import com.android.internal.os.SomeArgs;
284import com.android.internal.os.Zygote;
285import com.android.internal.telephony.CarrierAppUtils;
286import com.android.internal.util.ArrayUtils;
287import com.android.internal.util.ConcurrentUtils;
288import com.android.internal.util.DumpUtils;
289import com.android.internal.util.FastXmlSerializer;
290import com.android.internal.util.IndentingPrintWriter;
291import com.android.internal.util.Preconditions;
292import com.android.internal.util.XmlUtils;
293import com.android.server.AttributeCache;
294import com.android.server.DeviceIdleController;
295import com.android.server.EventLogTags;
296import com.android.server.FgThread;
297import com.android.server.IntentResolver;
298import com.android.server.LocalServices;
299import com.android.server.LockGuard;
300import com.android.server.ServiceThread;
301import com.android.server.SystemConfig;
302import com.android.server.SystemServerInitThreadPool;
303import com.android.server.Watchdog;
304import com.android.server.net.NetworkPolicyManagerInternal;
305import com.android.server.pm.Installer.InstallerException;
306import com.android.server.pm.Settings.DatabaseVersion;
307import com.android.server.pm.Settings.VersionInfo;
308import com.android.server.pm.dex.ArtManagerService;
309import com.android.server.pm.dex.DexLogger;
310import com.android.server.pm.dex.DexManager;
311import com.android.server.pm.dex.DexoptOptions;
312import com.android.server.pm.dex.PackageDexUsage;
313import com.android.server.pm.permission.BasePermission;
314import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
315import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
316import com.android.server.pm.permission.PermissionManagerInternal;
317import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
318import com.android.server.pm.permission.PermissionManagerService;
319import com.android.server.pm.permission.PermissionsState;
320import com.android.server.pm.permission.PermissionsState.PermissionState;
321import com.android.server.security.VerityUtils;
322import com.android.server.storage.DeviceStorageMonitorInternal;
323
324import dalvik.system.CloseGuard;
325import dalvik.system.VMRuntime;
326
327import libcore.io.IoUtils;
328
329import org.xmlpull.v1.XmlPullParser;
330import org.xmlpull.v1.XmlPullParserException;
331import org.xmlpull.v1.XmlSerializer;
332
333import java.io.BufferedOutputStream;
334import java.io.ByteArrayInputStream;
335import java.io.ByteArrayOutputStream;
336import java.io.File;
337import java.io.FileDescriptor;
338import java.io.FileInputStream;
339import java.io.FileOutputStream;
340import java.io.FilenameFilter;
341import java.io.IOException;
342import java.io.PrintWriter;
343import java.lang.annotation.Retention;
344import java.lang.annotation.RetentionPolicy;
345import java.nio.charset.StandardCharsets;
346import java.security.DigestException;
347import java.security.DigestInputStream;
348import java.security.MessageDigest;
349import java.security.NoSuchAlgorithmException;
350import java.security.PublicKey;
351import java.security.SecureRandom;
352import java.security.cert.CertificateException;
353import java.util.ArrayList;
354import java.util.Arrays;
355import java.util.Collection;
356import java.util.Collections;
357import java.util.Comparator;
358import java.util.HashMap;
359import java.util.HashSet;
360import java.util.Iterator;
361import java.util.LinkedHashSet;
362import java.util.List;
363import java.util.Map;
364import java.util.Objects;
365import java.util.Set;
366import java.util.concurrent.CountDownLatch;
367import java.util.concurrent.Future;
368import java.util.concurrent.TimeUnit;
369import java.util.concurrent.atomic.AtomicBoolean;
370import java.util.concurrent.atomic.AtomicInteger;
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 = true;
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    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
583
584    /** Canonical intent used to identify what counts as a "web browser" app */
585    private static final Intent sBrowserIntent;
586    static {
587        sBrowserIntent = new Intent();
588        sBrowserIntent.setAction(Intent.ACTION_VIEW);
589        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
590        sBrowserIntent.setData(Uri.parse("http:"));
591        sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
592    }
593
594    /**
595     * The set of all protected actions [i.e. those actions for which a high priority
596     * intent filter is disallowed].
597     */
598    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
599    static {
600        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
601        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
602        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
603        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
604    }
605
606    // Compilation reasons.
607    public static final int REASON_UNKNOWN = -1;
608    public static final int REASON_FIRST_BOOT = 0;
609    public static final int REASON_BOOT = 1;
610    public static final int REASON_INSTALL = 2;
611    public static final int REASON_BACKGROUND_DEXOPT = 3;
612    public static final int REASON_AB_OTA = 4;
613    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
614    public static final int REASON_SHARED = 6;
615
616    public static final int REASON_LAST = REASON_SHARED;
617
618    /**
619     * Version number for the package parser cache. Increment this whenever the format or
620     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
621     */
622    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
623
624    /**
625     * Whether the package parser cache is enabled.
626     */
627    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
628
629    /**
630     * Permissions required in order to receive instant application lifecycle broadcasts.
631     */
632    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
633            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
634
635    final ServiceThread mHandlerThread;
636
637    final PackageHandler mHandler;
638
639    private final ProcessLoggingHandler mProcessLoggingHandler;
640
641    /**
642     * Messages for {@link #mHandler} that need to wait for system ready before
643     * being dispatched.
644     */
645    private ArrayList<Message> mPostSystemReadyMessages;
646
647    final int mSdkVersion = Build.VERSION.SDK_INT;
648
649    final Context mContext;
650    final boolean mFactoryTest;
651    final boolean mOnlyCore;
652    final DisplayMetrics mMetrics;
653    final int mDefParseFlags;
654    final String[] mSeparateProcesses;
655    final boolean mIsUpgrade;
656    final boolean mIsPreNUpgrade;
657    final boolean mIsPreNMR1Upgrade;
658
659    // Have we told the Activity Manager to whitelist the default container service by uid yet?
660    @GuardedBy("mPackages")
661    boolean mDefaultContainerWhitelisted = false;
662
663    @GuardedBy("mPackages")
664    private boolean mDexOptDialogShown;
665
666    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
667    // LOCK HELD.  Can be called with mInstallLock held.
668    @GuardedBy("mInstallLock")
669    final Installer mInstaller;
670
671    /** Directory where installed applications are stored */
672    private static final File sAppInstallDir =
673            new File(Environment.getDataDirectory(), "app");
674    /** Directory where installed application's 32-bit native libraries are copied. */
675    private static final File sAppLib32InstallDir =
676            new File(Environment.getDataDirectory(), "app-lib");
677    /** Directory where code and non-resource assets of forward-locked applications are stored */
678    private static final File sDrmAppPrivateInstallDir =
679            new File(Environment.getDataDirectory(), "app-private");
680
681    // ----------------------------------------------------------------
682
683    // Lock for state used when installing and doing other long running
684    // operations.  Methods that must be called with this lock held have
685    // the suffix "LI".
686    final Object mInstallLock = new Object();
687
688    // ----------------------------------------------------------------
689
690    // Keys are String (package name), values are Package.  This also serves
691    // as the lock for the global state.  Methods that must be called with
692    // this lock held have the prefix "LP".
693    @GuardedBy("mPackages")
694    final ArrayMap<String, PackageParser.Package> mPackages =
695            new ArrayMap<String, PackageParser.Package>();
696
697    final ArrayMap<String, Set<String>> mKnownCodebase =
698            new ArrayMap<String, Set<String>>();
699
700    // Keys are isolated uids and values are the uid of the application
701    // that created the isolated proccess.
702    @GuardedBy("mPackages")
703    final SparseIntArray mIsolatedOwners = new SparseIntArray();
704
705    /**
706     * Tracks new system packages [received in an OTA] that we expect to
707     * find updated user-installed versions. Keys are package name, values
708     * are package location.
709     */
710    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
711    /**
712     * Tracks high priority intent filters for protected actions. During boot, certain
713     * filter actions are protected and should never be allowed to have a high priority
714     * intent filter for them. However, there is one, and only one exception -- the
715     * setup wizard. It must be able to define a high priority intent filter for these
716     * actions to ensure there are no escapes from the wizard. We need to delay processing
717     * of these during boot as we need to look at all of the system packages in order
718     * to know which component is the setup wizard.
719     */
720    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
721    /**
722     * Whether or not processing protected filters should be deferred.
723     */
724    private boolean mDeferProtectedFilters = true;
725
726    /**
727     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
728     */
729    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
730    /**
731     * Whether or not system app permissions should be promoted from install to runtime.
732     */
733    boolean mPromoteSystemApps;
734
735    @GuardedBy("mPackages")
736    final Settings mSettings;
737
738    /**
739     * Set of package names that are currently "frozen", which means active
740     * surgery is being done on the code/data for that package. The platform
741     * will refuse to launch frozen packages to avoid race conditions.
742     *
743     * @see PackageFreezer
744     */
745    @GuardedBy("mPackages")
746    final ArraySet<String> mFrozenPackages = new ArraySet<>();
747
748    final ProtectedPackages mProtectedPackages;
749
750    @GuardedBy("mLoadedVolumes")
751    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
752
753    boolean mFirstBoot;
754
755    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
756
757    @GuardedBy("mAvailableFeatures")
758    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
759
760    private final InstantAppRegistry mInstantAppRegistry;
761
762    @GuardedBy("mPackages")
763    int mChangedPackagesSequenceNumber;
764    /**
765     * List of changed [installed, removed or updated] packages.
766     * mapping from user id -> sequence number -> package name
767     */
768    @GuardedBy("mPackages")
769    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
770    /**
771     * The sequence number of the last change to a package.
772     * mapping from user id -> package name -> sequence number
773     */
774    @GuardedBy("mPackages")
775    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
776
777    @GuardedBy("mPackages")
778    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
779
780    class PackageParserCallback implements PackageParser.Callback {
781        @Override public final boolean hasFeature(String feature) {
782            return PackageManagerService.this.hasSystemFeature(feature, 0);
783        }
784
785        final List<PackageParser.Package> getStaticOverlayPackages(
786                Collection<PackageParser.Package> allPackages, String targetPackageName) {
787            if ("android".equals(targetPackageName)) {
788                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
789                // native AssetManager.
790                return null;
791            }
792
793            List<PackageParser.Package> overlayPackages = null;
794            for (PackageParser.Package p : allPackages) {
795                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
796                    if (overlayPackages == null) {
797                        overlayPackages = new ArrayList<PackageParser.Package>();
798                    }
799                    overlayPackages.add(p);
800                }
801            }
802            if (overlayPackages != null) {
803                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
804                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
805                        return p1.mOverlayPriority - p2.mOverlayPriority;
806                    }
807                };
808                Collections.sort(overlayPackages, cmp);
809            }
810            return overlayPackages;
811        }
812
813        final String[] getStaticOverlayPaths(List<PackageParser.Package> overlayPackages,
814                String targetPath) {
815            if (overlayPackages == null || overlayPackages.isEmpty()) {
816                return null;
817            }
818            List<String> overlayPathList = null;
819            for (PackageParser.Package overlayPackage : overlayPackages) {
820                if (targetPath == null) {
821                    if (overlayPathList == null) {
822                        overlayPathList = new ArrayList<String>();
823                    }
824                    overlayPathList.add(overlayPackage.baseCodePath);
825                    continue;
826                }
827
828                try {
829                    // Creates idmaps for system to parse correctly the Android manifest of the
830                    // target package.
831                    //
832                    // OverlayManagerService will update each of them with a correct gid from its
833                    // target package app id.
834                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
835                            UserHandle.getSharedAppGid(
836                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
837                    if (overlayPathList == null) {
838                        overlayPathList = new ArrayList<String>();
839                    }
840                    overlayPathList.add(overlayPackage.baseCodePath);
841                } catch (InstallerException e) {
842                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
843                            overlayPackage.baseCodePath);
844                }
845            }
846            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
847        }
848
849        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
850            List<PackageParser.Package> overlayPackages;
851            synchronized (mInstallLock) {
852                synchronized (mPackages) {
853                    overlayPackages = getStaticOverlayPackages(
854                            mPackages.values(), targetPackageName);
855                }
856                // It is safe to keep overlayPackages without holding mPackages because static overlay
857                // packages can't be uninstalled or disabled.
858                return getStaticOverlayPaths(overlayPackages, targetPath);
859            }
860        }
861
862        @Override public final String[] getOverlayApks(String targetPackageName) {
863            return getStaticOverlayPaths(targetPackageName, null);
864        }
865
866        @Override public final String[] getOverlayPaths(String targetPackageName,
867                String targetPath) {
868            return getStaticOverlayPaths(targetPackageName, targetPath);
869        }
870    }
871
872    class ParallelPackageParserCallback extends PackageParserCallback {
873        List<PackageParser.Package> mOverlayPackages = null;
874
875        void findStaticOverlayPackages() {
876            synchronized (mPackages) {
877                for (PackageParser.Package p : mPackages.values()) {
878                    if (p.mOverlayIsStatic) {
879                        if (mOverlayPackages == null) {
880                            mOverlayPackages = new ArrayList<PackageParser.Package>();
881                        }
882                        mOverlayPackages.add(p);
883                    }
884                }
885            }
886        }
887
888        @Override
889        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
890            // We can trust mOverlayPackages without holding mPackages because package uninstall
891            // can't happen while running parallel parsing.
892            // And we can call mInstaller inside getStaticOverlayPaths without holding mInstallLock
893            // because mInstallLock is held before running parallel parsing.
894            // Moreover holding mPackages or mInstallLock on each parsing thread causes dead-lock.
895            return mOverlayPackages == null ? null :
896                    getStaticOverlayPaths(
897                            getStaticOverlayPackages(mOverlayPackages, targetPackageName),
898                            targetPath);
899        }
900    }
901
902    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
903    final ParallelPackageParserCallback mParallelPackageParserCallback =
904            new ParallelPackageParserCallback();
905
906    public static final class SharedLibraryEntry {
907        public final @Nullable String path;
908        public final @Nullable String apk;
909        public final @NonNull SharedLibraryInfo info;
910
911        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
912                String declaringPackageName, long declaringPackageVersionCode) {
913            path = _path;
914            apk = _apk;
915            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
916                    declaringPackageName, declaringPackageVersionCode), null);
917        }
918    }
919
920    // Currently known shared libraries.
921    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
922    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
923            new ArrayMap<>();
924
925    // All available activities, for your resolving pleasure.
926    final ActivityIntentResolver mActivities =
927            new ActivityIntentResolver();
928
929    // All available receivers, for your resolving pleasure.
930    final ActivityIntentResolver mReceivers =
931            new ActivityIntentResolver();
932
933    // All available services, for your resolving pleasure.
934    final ServiceIntentResolver mServices = new ServiceIntentResolver();
935
936    // All available providers, for your resolving pleasure.
937    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
938
939    // Mapping from provider base names (first directory in content URI codePath)
940    // to the provider information.
941    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
942            new ArrayMap<String, PackageParser.Provider>();
943
944    // Mapping from instrumentation class names to info about them.
945    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
946            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
947
948    // Packages whose data we have transfered into another package, thus
949    // should no longer exist.
950    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
951
952    // Broadcast actions that are only available to the system.
953    @GuardedBy("mProtectedBroadcasts")
954    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
955
956    /** List of packages waiting for verification. */
957    final SparseArray<PackageVerificationState> mPendingVerification
958            = new SparseArray<PackageVerificationState>();
959
960    final PackageInstallerService mInstallerService;
961
962    final ArtManagerService mArtManagerService;
963
964    private final PackageDexOptimizer mPackageDexOptimizer;
965    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
966    // is used by other apps).
967    private final DexManager mDexManager;
968
969    private AtomicInteger mNextMoveId = new AtomicInteger();
970    private final MoveCallbacks mMoveCallbacks;
971
972    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
973
974    // Cache of users who need badging.
975    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
976
977    /** Token for keys in mPendingVerification. */
978    private int mPendingVerificationToken = 0;
979
980    volatile boolean mSystemReady;
981    volatile boolean mSafeMode;
982    volatile boolean mHasSystemUidErrors;
983    private volatile boolean mWebInstantAppsDisabled;
984
985    ApplicationInfo mAndroidApplication;
986    final ActivityInfo mResolveActivity = new ActivityInfo();
987    final ResolveInfo mResolveInfo = new ResolveInfo();
988    ComponentName mResolveComponentName;
989    PackageParser.Package mPlatformPackage;
990    ComponentName mCustomResolverComponentName;
991
992    boolean mResolverReplaced = false;
993
994    private final @Nullable ComponentName mIntentFilterVerifierComponent;
995    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
996
997    private int mIntentFilterVerificationToken = 0;
998
999    /** The service connection to the ephemeral resolver */
1000    final InstantAppResolverConnection mInstantAppResolverConnection;
1001    /** Component used to show resolver settings for Instant Apps */
1002    final ComponentName mInstantAppResolverSettingsComponent;
1003
1004    /** Activity used to install instant applications */
1005    ActivityInfo mInstantAppInstallerActivity;
1006    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1007
1008    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1009            = new SparseArray<IntentFilterVerificationState>();
1010
1011    // TODO remove this and go through mPermissonManager directly
1012    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1013    private final PermissionManagerInternal mPermissionManager;
1014
1015    // List of packages names to keep cached, even if they are uninstalled for all users
1016    private List<String> mKeepUninstalledPackages;
1017
1018    private UserManagerInternal mUserManagerInternal;
1019    private ActivityManagerInternal mActivityManagerInternal;
1020
1021    private DeviceIdleController.LocalService mDeviceIdleController;
1022
1023    private File mCacheDir;
1024
1025    private Future<?> mPrepareAppDataFuture;
1026
1027    private static class IFVerificationParams {
1028        PackageParser.Package pkg;
1029        boolean replacing;
1030        int userId;
1031        int verifierUid;
1032
1033        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1034                int _userId, int _verifierUid) {
1035            pkg = _pkg;
1036            replacing = _replacing;
1037            userId = _userId;
1038            replacing = _replacing;
1039            verifierUid = _verifierUid;
1040        }
1041    }
1042
1043    private interface IntentFilterVerifier<T extends IntentFilter> {
1044        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1045                                               T filter, String packageName);
1046        void startVerifications(int userId);
1047        void receiveVerificationResponse(int verificationId);
1048    }
1049
1050    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1051        private Context mContext;
1052        private ComponentName mIntentFilterVerifierComponent;
1053        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1054
1055        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1056            mContext = context;
1057            mIntentFilterVerifierComponent = verifierComponent;
1058        }
1059
1060        private String getDefaultScheme() {
1061            return IntentFilter.SCHEME_HTTPS;
1062        }
1063
1064        @Override
1065        public void startVerifications(int userId) {
1066            // Launch verifications requests
1067            int count = mCurrentIntentFilterVerifications.size();
1068            for (int n=0; n<count; n++) {
1069                int verificationId = mCurrentIntentFilterVerifications.get(n);
1070                final IntentFilterVerificationState ivs =
1071                        mIntentFilterVerificationStates.get(verificationId);
1072
1073                String packageName = ivs.getPackageName();
1074
1075                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1076                final int filterCount = filters.size();
1077                ArraySet<String> domainsSet = new ArraySet<>();
1078                for (int m=0; m<filterCount; m++) {
1079                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1080                    domainsSet.addAll(filter.getHostsList());
1081                }
1082                synchronized (mPackages) {
1083                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1084                            packageName, domainsSet) != null) {
1085                        scheduleWriteSettingsLocked();
1086                    }
1087                }
1088                sendVerificationRequest(verificationId, ivs);
1089            }
1090            mCurrentIntentFilterVerifications.clear();
1091        }
1092
1093        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1094            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1095            verificationIntent.putExtra(
1096                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1097                    verificationId);
1098            verificationIntent.putExtra(
1099                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1100                    getDefaultScheme());
1101            verificationIntent.putExtra(
1102                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1103                    ivs.getHostsString());
1104            verificationIntent.putExtra(
1105                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1106                    ivs.getPackageName());
1107            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1108            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1109
1110            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1111            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1112                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1113                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1114
1115            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1116            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1117                    "Sending IntentFilter verification broadcast");
1118        }
1119
1120        public void receiveVerificationResponse(int verificationId) {
1121            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1122
1123            final boolean verified = ivs.isVerified();
1124
1125            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1126            final int count = filters.size();
1127            if (DEBUG_DOMAIN_VERIFICATION) {
1128                Slog.i(TAG, "Received verification response " + verificationId
1129                        + " for " + count + " filters, verified=" + verified);
1130            }
1131            for (int n=0; n<count; n++) {
1132                PackageParser.ActivityIntentInfo filter = filters.get(n);
1133                filter.setVerified(verified);
1134
1135                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1136                        + " verified with result:" + verified + " and hosts:"
1137                        + ivs.getHostsString());
1138            }
1139
1140            mIntentFilterVerificationStates.remove(verificationId);
1141
1142            final String packageName = ivs.getPackageName();
1143            IntentFilterVerificationInfo ivi = null;
1144
1145            synchronized (mPackages) {
1146                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1147            }
1148            if (ivi == null) {
1149                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1150                        + verificationId + " packageName:" + packageName);
1151                return;
1152            }
1153            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1154                    "Updating IntentFilterVerificationInfo for package " + packageName
1155                            +" verificationId:" + verificationId);
1156
1157            synchronized (mPackages) {
1158                if (verified) {
1159                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1160                } else {
1161                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1162                }
1163                scheduleWriteSettingsLocked();
1164
1165                final int userId = ivs.getUserId();
1166                if (userId != UserHandle.USER_ALL) {
1167                    final int userStatus =
1168                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1169
1170                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1171                    boolean needUpdate = false;
1172
1173                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1174                    // already been set by the User thru the Disambiguation dialog
1175                    switch (userStatus) {
1176                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1177                            if (verified) {
1178                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1179                            } else {
1180                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1181                            }
1182                            needUpdate = true;
1183                            break;
1184
1185                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1186                            if (verified) {
1187                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1188                                needUpdate = true;
1189                            }
1190                            break;
1191
1192                        default:
1193                            // Nothing to do
1194                    }
1195
1196                    if (needUpdate) {
1197                        mSettings.updateIntentFilterVerificationStatusLPw(
1198                                packageName, updatedStatus, userId);
1199                        scheduleWritePackageRestrictionsLocked(userId);
1200                    }
1201                }
1202            }
1203        }
1204
1205        @Override
1206        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1207                    ActivityIntentInfo filter, String packageName) {
1208            if (!hasValidDomains(filter)) {
1209                return false;
1210            }
1211            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1212            if (ivs == null) {
1213                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1214                        packageName);
1215            }
1216            if (DEBUG_DOMAIN_VERIFICATION) {
1217                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1218            }
1219            ivs.addFilter(filter);
1220            return true;
1221        }
1222
1223        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1224                int userId, int verificationId, String packageName) {
1225            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1226                    verifierUid, userId, packageName);
1227            ivs.setPendingState();
1228            synchronized (mPackages) {
1229                mIntentFilterVerificationStates.append(verificationId, ivs);
1230                mCurrentIntentFilterVerifications.add(verificationId);
1231            }
1232            return ivs;
1233        }
1234    }
1235
1236    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1237        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1238                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1239                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1240    }
1241
1242    // Set of pending broadcasts for aggregating enable/disable of components.
1243    static class PendingPackageBroadcasts {
1244        // for each user id, a map of <package name -> components within that package>
1245        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1246
1247        public PendingPackageBroadcasts() {
1248            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1249        }
1250
1251        public ArrayList<String> get(int userId, String packageName) {
1252            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1253            return packages.get(packageName);
1254        }
1255
1256        public void put(int userId, String packageName, ArrayList<String> components) {
1257            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1258            packages.put(packageName, components);
1259        }
1260
1261        public void remove(int userId, String packageName) {
1262            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1263            if (packages != null) {
1264                packages.remove(packageName);
1265            }
1266        }
1267
1268        public void remove(int userId) {
1269            mUidMap.remove(userId);
1270        }
1271
1272        public int userIdCount() {
1273            return mUidMap.size();
1274        }
1275
1276        public int userIdAt(int n) {
1277            return mUidMap.keyAt(n);
1278        }
1279
1280        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1281            return mUidMap.get(userId);
1282        }
1283
1284        public int size() {
1285            // total number of pending broadcast entries across all userIds
1286            int num = 0;
1287            for (int i = 0; i< mUidMap.size(); i++) {
1288                num += mUidMap.valueAt(i).size();
1289            }
1290            return num;
1291        }
1292
1293        public void clear() {
1294            mUidMap.clear();
1295        }
1296
1297        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1298            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1299            if (map == null) {
1300                map = new ArrayMap<String, ArrayList<String>>();
1301                mUidMap.put(userId, map);
1302            }
1303            return map;
1304        }
1305    }
1306    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1307
1308    // Service Connection to remote media container service to copy
1309    // package uri's from external media onto secure containers
1310    // or internal storage.
1311    private IMediaContainerService mContainerService = null;
1312
1313    static final int SEND_PENDING_BROADCAST = 1;
1314    static final int MCS_BOUND = 3;
1315    static final int END_COPY = 4;
1316    static final int INIT_COPY = 5;
1317    static final int MCS_UNBIND = 6;
1318    static final int START_CLEANING_PACKAGE = 7;
1319    static final int FIND_INSTALL_LOC = 8;
1320    static final int POST_INSTALL = 9;
1321    static final int MCS_RECONNECT = 10;
1322    static final int MCS_GIVE_UP = 11;
1323    static final int WRITE_SETTINGS = 13;
1324    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1325    static final int PACKAGE_VERIFIED = 15;
1326    static final int CHECK_PENDING_VERIFICATION = 16;
1327    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1328    static final int INTENT_FILTER_VERIFIED = 18;
1329    static final int WRITE_PACKAGE_LIST = 19;
1330    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1331    static final int DEF_CONTAINER_BIND = 21;
1332
1333    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1334
1335    // Delay time in millisecs
1336    static final int BROADCAST_DELAY = 10 * 1000;
1337
1338    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1339            2 * 60 * 60 * 1000L; /* two hours */
1340
1341    static UserManagerService sUserManager;
1342
1343    // Stores a list of users whose package restrictions file needs to be updated
1344    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1345
1346    final private DefaultContainerConnection mDefContainerConn =
1347            new DefaultContainerConnection();
1348    class DefaultContainerConnection implements ServiceConnection {
1349        public void onServiceConnected(ComponentName name, IBinder service) {
1350            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1351            final IMediaContainerService imcs = IMediaContainerService.Stub
1352                    .asInterface(Binder.allowBlocking(service));
1353            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1354        }
1355
1356        public void onServiceDisconnected(ComponentName name) {
1357            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1358        }
1359    }
1360
1361    // Recordkeeping of restore-after-install operations that are currently in flight
1362    // between the Package Manager and the Backup Manager
1363    static class PostInstallData {
1364        public InstallArgs args;
1365        public PackageInstalledInfo res;
1366
1367        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1368            args = _a;
1369            res = _r;
1370        }
1371    }
1372
1373    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1374    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1375
1376    // XML tags for backup/restore of various bits of state
1377    private static final String TAG_PREFERRED_BACKUP = "pa";
1378    private static final String TAG_DEFAULT_APPS = "da";
1379    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1380
1381    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1382    private static final String TAG_ALL_GRANTS = "rt-grants";
1383    private static final String TAG_GRANT = "grant";
1384    private static final String ATTR_PACKAGE_NAME = "pkg";
1385
1386    private static final String TAG_PERMISSION = "perm";
1387    private static final String ATTR_PERMISSION_NAME = "name";
1388    private static final String ATTR_IS_GRANTED = "g";
1389    private static final String ATTR_USER_SET = "set";
1390    private static final String ATTR_USER_FIXED = "fixed";
1391    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1392
1393    // System/policy permission grants are not backed up
1394    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1395            FLAG_PERMISSION_POLICY_FIXED
1396            | FLAG_PERMISSION_SYSTEM_FIXED
1397            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1398
1399    // And we back up these user-adjusted states
1400    private static final int USER_RUNTIME_GRANT_MASK =
1401            FLAG_PERMISSION_USER_SET
1402            | FLAG_PERMISSION_USER_FIXED
1403            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1404
1405    final @Nullable String mRequiredVerifierPackage;
1406    final @NonNull String mRequiredInstallerPackage;
1407    final @NonNull String mRequiredUninstallerPackage;
1408    final @Nullable String mSetupWizardPackage;
1409    final @Nullable String mStorageManagerPackage;
1410    final @Nullable String mSystemTextClassifierPackage;
1411    final @NonNull String mServicesSystemSharedLibraryPackageName;
1412    final @NonNull String mSharedSystemSharedLibraryPackageName;
1413
1414    private final PackageUsage mPackageUsage = new PackageUsage();
1415    private final CompilerStats mCompilerStats = new CompilerStats();
1416
1417    class PackageHandler extends Handler {
1418        private boolean mBound = false;
1419        final ArrayList<HandlerParams> mPendingInstalls =
1420            new ArrayList<HandlerParams>();
1421
1422        private boolean connectToService() {
1423            if (DEBUG_INSTALL) Log.i(TAG, "Trying to bind to DefaultContainerService");
1424            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1425            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1426            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1427                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1428                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1429                mBound = true;
1430                return true;
1431            }
1432            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1433            return false;
1434        }
1435
1436        private void disconnectService() {
1437            mContainerService = null;
1438            mBound = false;
1439            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1440            mContext.unbindService(mDefContainerConn);
1441            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1442        }
1443
1444        PackageHandler(Looper looper) {
1445            super(looper);
1446        }
1447
1448        public void handleMessage(Message msg) {
1449            try {
1450                doHandleMessage(msg);
1451            } finally {
1452                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1453            }
1454        }
1455
1456        void doHandleMessage(Message msg) {
1457            switch (msg.what) {
1458                case DEF_CONTAINER_BIND:
1459                    if (!mBound) {
1460                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "earlyBindingMCS",
1461                                System.identityHashCode(mHandler));
1462                        if (!connectToService()) {
1463                            Slog.e(TAG, "Failed to bind to media container service");
1464                        }
1465                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "earlyBindingMCS",
1466                                System.identityHashCode(mHandler));
1467                    }
1468                    break;
1469                case INIT_COPY: {
1470                    HandlerParams params = (HandlerParams) msg.obj;
1471                    int idx = mPendingInstalls.size();
1472                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1473                    // If a bind was already initiated we dont really
1474                    // need to do anything. The pending install
1475                    // will be processed later on.
1476                    if (!mBound) {
1477                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1478                                System.identityHashCode(mHandler));
1479                        // If this is the only one pending we might
1480                        // have to bind to the service again.
1481                        if (!connectToService()) {
1482                            Slog.e(TAG, "Failed to bind to media container service");
1483                            params.serviceError();
1484                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1485                                    System.identityHashCode(mHandler));
1486                            if (params.traceMethod != null) {
1487                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1488                                        params.traceCookie);
1489                            }
1490                            return;
1491                        } else {
1492                            // Once we bind to the service, the first
1493                            // pending request will be processed.
1494                            mPendingInstalls.add(idx, params);
1495                        }
1496                    } else {
1497                        mPendingInstalls.add(idx, params);
1498                        // Already bound to the service. Just make
1499                        // sure we trigger off processing the first request.
1500                        if (idx == 0) {
1501                            mHandler.sendEmptyMessage(MCS_BOUND);
1502                        }
1503                    }
1504                    break;
1505                }
1506                case MCS_BOUND: {
1507                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1508                    if (msg.obj != null) {
1509                        mContainerService = (IMediaContainerService) msg.obj;
1510                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1511                                System.identityHashCode(mHandler));
1512                    }
1513                    if (mContainerService == null) {
1514                        if (!mBound) {
1515                            // Something seriously wrong since we are not bound and we are not
1516                            // waiting for connection. Bail out.
1517                            Slog.e(TAG, "Cannot bind to media container service");
1518                            for (HandlerParams params : mPendingInstalls) {
1519                                // Indicate service bind error
1520                                params.serviceError();
1521                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1522                                        System.identityHashCode(params));
1523                                if (params.traceMethod != null) {
1524                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1525                                            params.traceMethod, params.traceCookie);
1526                                }
1527                            }
1528                            mPendingInstalls.clear();
1529                        } else {
1530                            Slog.w(TAG, "Waiting to connect to media container service");
1531                        }
1532                    } else if (mPendingInstalls.size() > 0) {
1533                        HandlerParams params = mPendingInstalls.get(0);
1534                        if (params != null) {
1535                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1536                                    System.identityHashCode(params));
1537                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1538                            if (params.startCopy()) {
1539                                // We are done...  look for more work or to
1540                                // go idle.
1541                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1542                                        "Checking for more work or unbind...");
1543                                // Delete pending install
1544                                if (mPendingInstalls.size() > 0) {
1545                                    mPendingInstalls.remove(0);
1546                                }
1547                                if (mPendingInstalls.size() == 0) {
1548                                    if (mBound) {
1549                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1550                                                "Posting delayed MCS_UNBIND");
1551                                        removeMessages(MCS_UNBIND);
1552                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1553                                        // Unbind after a little delay, to avoid
1554                                        // continual thrashing.
1555                                        sendMessageDelayed(ubmsg, 10000);
1556                                    }
1557                                } else {
1558                                    // There are more pending requests in queue.
1559                                    // Just post MCS_BOUND message to trigger processing
1560                                    // of next pending install.
1561                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1562                                            "Posting MCS_BOUND for next work");
1563                                    mHandler.sendEmptyMessage(MCS_BOUND);
1564                                }
1565                            }
1566                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1567                        }
1568                    } else {
1569                        // Should never happen ideally.
1570                        Slog.w(TAG, "Empty queue");
1571                    }
1572                    break;
1573                }
1574                case MCS_RECONNECT: {
1575                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1576                    if (mPendingInstalls.size() > 0) {
1577                        if (mBound) {
1578                            disconnectService();
1579                        }
1580                        if (!connectToService()) {
1581                            Slog.e(TAG, "Failed to bind to media container service");
1582                            for (HandlerParams params : mPendingInstalls) {
1583                                // Indicate service bind error
1584                                params.serviceError();
1585                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1586                                        System.identityHashCode(params));
1587                            }
1588                            mPendingInstalls.clear();
1589                        }
1590                    }
1591                    break;
1592                }
1593                case MCS_UNBIND: {
1594                    // If there is no actual work left, then time to unbind.
1595                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1596
1597                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1598                        if (mBound) {
1599                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1600
1601                            disconnectService();
1602                        }
1603                    } else if (mPendingInstalls.size() > 0) {
1604                        // There are more pending requests in queue.
1605                        // Just post MCS_BOUND message to trigger processing
1606                        // of next pending install.
1607                        mHandler.sendEmptyMessage(MCS_BOUND);
1608                    }
1609
1610                    break;
1611                }
1612                case MCS_GIVE_UP: {
1613                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1614                    HandlerParams params = mPendingInstalls.remove(0);
1615                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1616                            System.identityHashCode(params));
1617                    break;
1618                }
1619                case SEND_PENDING_BROADCAST: {
1620                    String packages[];
1621                    ArrayList<String> components[];
1622                    int size = 0;
1623                    int uids[];
1624                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1625                    synchronized (mPackages) {
1626                        if (mPendingBroadcasts == null) {
1627                            return;
1628                        }
1629                        size = mPendingBroadcasts.size();
1630                        if (size <= 0) {
1631                            // Nothing to be done. Just return
1632                            return;
1633                        }
1634                        packages = new String[size];
1635                        components = new ArrayList[size];
1636                        uids = new int[size];
1637                        int i = 0;  // filling out the above arrays
1638
1639                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1640                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1641                            Iterator<Map.Entry<String, ArrayList<String>>> it
1642                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1643                                            .entrySet().iterator();
1644                            while (it.hasNext() && i < size) {
1645                                Map.Entry<String, ArrayList<String>> ent = it.next();
1646                                packages[i] = ent.getKey();
1647                                components[i] = ent.getValue();
1648                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1649                                uids[i] = (ps != null)
1650                                        ? UserHandle.getUid(packageUserId, ps.appId)
1651                                        : -1;
1652                                i++;
1653                            }
1654                        }
1655                        size = i;
1656                        mPendingBroadcasts.clear();
1657                    }
1658                    // Send broadcasts
1659                    for (int i = 0; i < size; i++) {
1660                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1661                    }
1662                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1663                    break;
1664                }
1665                case START_CLEANING_PACKAGE: {
1666                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1667                    final String packageName = (String)msg.obj;
1668                    final int userId = msg.arg1;
1669                    final boolean andCode = msg.arg2 != 0;
1670                    synchronized (mPackages) {
1671                        if (userId == UserHandle.USER_ALL) {
1672                            int[] users = sUserManager.getUserIds();
1673                            for (int user : users) {
1674                                mSettings.addPackageToCleanLPw(
1675                                        new PackageCleanItem(user, packageName, andCode));
1676                            }
1677                        } else {
1678                            mSettings.addPackageToCleanLPw(
1679                                    new PackageCleanItem(userId, packageName, andCode));
1680                        }
1681                    }
1682                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1683                    startCleaningPackages();
1684                } break;
1685                case POST_INSTALL: {
1686                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1687
1688                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1689                    final boolean didRestore = (msg.arg2 != 0);
1690                    mRunningInstalls.delete(msg.arg1);
1691
1692                    if (data != null) {
1693                        InstallArgs args = data.args;
1694                        PackageInstalledInfo parentRes = data.res;
1695
1696                        final boolean grantPermissions = (args.installFlags
1697                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1698                        final boolean killApp = (args.installFlags
1699                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1700                        final boolean virtualPreload = ((args.installFlags
1701                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1702                        final String[] grantedPermissions = args.installGrantPermissions;
1703
1704                        // Handle the parent package
1705                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1706                                virtualPreload, grantedPermissions, didRestore,
1707                                args.installerPackageName, args.observer);
1708
1709                        // Handle the child packages
1710                        final int childCount = (parentRes.addedChildPackages != null)
1711                                ? parentRes.addedChildPackages.size() : 0;
1712                        for (int i = 0; i < childCount; i++) {
1713                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1714                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1715                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1716                                    args.installerPackageName, args.observer);
1717                        }
1718
1719                        // Log tracing if needed
1720                        if (args.traceMethod != null) {
1721                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1722                                    args.traceCookie);
1723                        }
1724                    } else {
1725                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1726                    }
1727
1728                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1729                } break;
1730                case WRITE_SETTINGS: {
1731                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1732                    synchronized (mPackages) {
1733                        removeMessages(WRITE_SETTINGS);
1734                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1735                        mSettings.writeLPr();
1736                        mDirtyUsers.clear();
1737                    }
1738                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1739                } break;
1740                case WRITE_PACKAGE_RESTRICTIONS: {
1741                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1742                    synchronized (mPackages) {
1743                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1744                        for (int userId : mDirtyUsers) {
1745                            mSettings.writePackageRestrictionsLPr(userId);
1746                        }
1747                        mDirtyUsers.clear();
1748                    }
1749                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1750                } break;
1751                case WRITE_PACKAGE_LIST: {
1752                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1753                    synchronized (mPackages) {
1754                        removeMessages(WRITE_PACKAGE_LIST);
1755                        mSettings.writePackageListLPr(msg.arg1);
1756                    }
1757                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1758                } break;
1759                case CHECK_PENDING_VERIFICATION: {
1760                    final int verificationId = msg.arg1;
1761                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1762
1763                    if ((state != null) && !state.timeoutExtended()) {
1764                        final InstallArgs args = state.getInstallArgs();
1765                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1766
1767                        Slog.i(TAG, "Verification timed out for " + originUri);
1768                        mPendingVerification.remove(verificationId);
1769
1770                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1771
1772                        final UserHandle user = args.getUser();
1773                        if (getDefaultVerificationResponse(user)
1774                                == PackageManager.VERIFICATION_ALLOW) {
1775                            Slog.i(TAG, "Continuing with installation of " + originUri);
1776                            state.setVerifierResponse(Binder.getCallingUid(),
1777                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1778                            broadcastPackageVerified(verificationId, originUri,
1779                                    PackageManager.VERIFICATION_ALLOW, user);
1780                            try {
1781                                ret = args.copyApk(mContainerService, true);
1782                            } catch (RemoteException e) {
1783                                Slog.e(TAG, "Could not contact the ContainerService");
1784                            }
1785                        } else {
1786                            broadcastPackageVerified(verificationId, originUri,
1787                                    PackageManager.VERIFICATION_REJECT, user);
1788                        }
1789
1790                        Trace.asyncTraceEnd(
1791                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1792
1793                        processPendingInstall(args, ret);
1794                        mHandler.sendEmptyMessage(MCS_UNBIND);
1795                    }
1796                    break;
1797                }
1798                case PACKAGE_VERIFIED: {
1799                    final int verificationId = msg.arg1;
1800
1801                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1802                    if (state == null) {
1803                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1804                        break;
1805                    }
1806
1807                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1808
1809                    state.setVerifierResponse(response.callerUid, response.code);
1810
1811                    if (state.isVerificationComplete()) {
1812                        mPendingVerification.remove(verificationId);
1813
1814                        final InstallArgs args = state.getInstallArgs();
1815                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1816
1817                        int ret;
1818                        if (state.isInstallAllowed()) {
1819                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1820                            broadcastPackageVerified(verificationId, originUri,
1821                                    response.code, state.getInstallArgs().getUser());
1822                            try {
1823                                ret = args.copyApk(mContainerService, true);
1824                            } catch (RemoteException e) {
1825                                Slog.e(TAG, "Could not contact the ContainerService");
1826                            }
1827                        } else {
1828                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1829                        }
1830
1831                        Trace.asyncTraceEnd(
1832                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1833
1834                        processPendingInstall(args, ret);
1835                        mHandler.sendEmptyMessage(MCS_UNBIND);
1836                    }
1837
1838                    break;
1839                }
1840                case START_INTENT_FILTER_VERIFICATIONS: {
1841                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1842                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1843                            params.replacing, params.pkg);
1844                    break;
1845                }
1846                case INTENT_FILTER_VERIFIED: {
1847                    final int verificationId = msg.arg1;
1848
1849                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1850                            verificationId);
1851                    if (state == null) {
1852                        Slog.w(TAG, "Invalid IntentFilter verification token "
1853                                + verificationId + " received");
1854                        break;
1855                    }
1856
1857                    final int userId = state.getUserId();
1858
1859                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1860                            "Processing IntentFilter verification with token:"
1861                            + verificationId + " and userId:" + userId);
1862
1863                    final IntentFilterVerificationResponse response =
1864                            (IntentFilterVerificationResponse) msg.obj;
1865
1866                    state.setVerifierResponse(response.callerUid, response.code);
1867
1868                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1869                            "IntentFilter verification with token:" + verificationId
1870                            + " and userId:" + userId
1871                            + " is settings verifier response with response code:"
1872                            + response.code);
1873
1874                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1875                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1876                                + response.getFailedDomainsString());
1877                    }
1878
1879                    if (state.isVerificationComplete()) {
1880                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1881                    } else {
1882                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1883                                "IntentFilter verification with token:" + verificationId
1884                                + " was not said to be complete");
1885                    }
1886
1887                    break;
1888                }
1889                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1890                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1891                            mInstantAppResolverConnection,
1892                            (InstantAppRequest) msg.obj,
1893                            mInstantAppInstallerActivity,
1894                            mHandler);
1895                }
1896            }
1897        }
1898    }
1899
1900    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1901        @Override
1902        public void onGidsChanged(int appId, int userId) {
1903            mHandler.post(new Runnable() {
1904                @Override
1905                public void run() {
1906                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1907                }
1908            });
1909        }
1910        @Override
1911        public void onPermissionGranted(int uid, int userId) {
1912            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1913
1914            // Not critical; if this is lost, the application has to request again.
1915            synchronized (mPackages) {
1916                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1917            }
1918        }
1919        @Override
1920        public void onInstallPermissionGranted() {
1921            synchronized (mPackages) {
1922                scheduleWriteSettingsLocked();
1923            }
1924        }
1925        @Override
1926        public void onPermissionRevoked(int uid, int userId) {
1927            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1928
1929            synchronized (mPackages) {
1930                // Critical; after this call the application should never have the permission
1931                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1932            }
1933
1934            final int appId = UserHandle.getAppId(uid);
1935            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1936        }
1937        @Override
1938        public void onInstallPermissionRevoked() {
1939            synchronized (mPackages) {
1940                scheduleWriteSettingsLocked();
1941            }
1942        }
1943        @Override
1944        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1945            synchronized (mPackages) {
1946                for (int userId : updatedUserIds) {
1947                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1948                }
1949            }
1950        }
1951        @Override
1952        public void onInstallPermissionUpdated() {
1953            synchronized (mPackages) {
1954                scheduleWriteSettingsLocked();
1955            }
1956        }
1957        @Override
1958        public void onPermissionRemoved() {
1959            synchronized (mPackages) {
1960                mSettings.writeLPr();
1961            }
1962        }
1963    };
1964
1965    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1966            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1967            boolean launchedForRestore, String installerPackage,
1968            IPackageInstallObserver2 installObserver) {
1969        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1970            // Send the removed broadcasts
1971            if (res.removedInfo != null) {
1972                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1973            }
1974
1975            // Now that we successfully installed the package, grant runtime
1976            // permissions if requested before broadcasting the install. Also
1977            // for legacy apps in permission review mode we clear the permission
1978            // review flag which is used to emulate runtime permissions for
1979            // legacy apps.
1980            if (grantPermissions) {
1981                final int callingUid = Binder.getCallingUid();
1982                mPermissionManager.grantRequestedRuntimePermissions(
1983                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1984                        mPermissionCallback);
1985            }
1986
1987            final boolean update = res.removedInfo != null
1988                    && res.removedInfo.removedPackage != null;
1989            final String installerPackageName =
1990                    res.installerPackageName != null
1991                            ? res.installerPackageName
1992                            : res.removedInfo != null
1993                                    ? res.removedInfo.installerPackageName
1994                                    : null;
1995
1996            // If this is the first time we have child packages for a disabled privileged
1997            // app that had no children, we grant requested runtime permissions to the new
1998            // children if the parent on the system image had them already granted.
1999            if (res.pkg.parentPackage != null) {
2000                final int callingUid = Binder.getCallingUid();
2001                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
2002                        res.pkg, callingUid, mPermissionCallback);
2003            }
2004
2005            synchronized (mPackages) {
2006                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
2007            }
2008
2009            final String packageName = res.pkg.applicationInfo.packageName;
2010
2011            // Determine the set of users who are adding this package for
2012            // the first time vs. those who are seeing an update.
2013            int[] firstUserIds = EMPTY_INT_ARRAY;
2014            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
2015            int[] updateUserIds = EMPTY_INT_ARRAY;
2016            int[] instantUserIds = EMPTY_INT_ARRAY;
2017            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
2018            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
2019            for (int newUser : res.newUsers) {
2020                final boolean isInstantApp = ps.getInstantApp(newUser);
2021                if (allNewUsers) {
2022                    if (isInstantApp) {
2023                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2024                    } else {
2025                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2026                    }
2027                    continue;
2028                }
2029                boolean isNew = true;
2030                for (int origUser : res.origUsers) {
2031                    if (origUser == newUser) {
2032                        isNew = false;
2033                        break;
2034                    }
2035                }
2036                if (isNew) {
2037                    if (isInstantApp) {
2038                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2039                    } else {
2040                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2041                    }
2042                } else {
2043                    if (isInstantApp) {
2044                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2045                    } else {
2046                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2047                    }
2048                }
2049            }
2050
2051            // Send installed broadcasts if the package is not a static shared lib.
2052            if (res.pkg.staticSharedLibName == null) {
2053                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2054
2055                // Send added for users that see the package for the first time
2056                // sendPackageAddedForNewUsers also deals with system apps
2057                int appId = UserHandle.getAppId(res.uid);
2058                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2059                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2060                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2061
2062                // Send added for users that don't see the package for the first time
2063                Bundle extras = new Bundle(1);
2064                extras.putInt(Intent.EXTRA_UID, res.uid);
2065                if (update) {
2066                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2067                }
2068                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2069                        extras, 0 /*flags*/,
2070                        null /*targetPackage*/, null /*finishedReceiver*/,
2071                        updateUserIds, instantUserIds);
2072                if (installerPackageName != null) {
2073                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2074                            extras, 0 /*flags*/,
2075                            installerPackageName, null /*finishedReceiver*/,
2076                            updateUserIds, instantUserIds);
2077                }
2078
2079                // Send replaced for users that don't see the package for the first time
2080                if (update) {
2081                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2082                            packageName, extras, 0 /*flags*/,
2083                            null /*targetPackage*/, null /*finishedReceiver*/,
2084                            updateUserIds, instantUserIds);
2085                    if (installerPackageName != null) {
2086                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2087                                extras, 0 /*flags*/,
2088                                installerPackageName, null /*finishedReceiver*/,
2089                                updateUserIds, instantUserIds);
2090                    }
2091                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2092                            null /*package*/, null /*extras*/, 0 /*flags*/,
2093                            packageName /*targetPackage*/,
2094                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2095                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2096                    // First-install and we did a restore, so we're responsible for the
2097                    // first-launch broadcast.
2098                    if (DEBUG_BACKUP) {
2099                        Slog.i(TAG, "Post-restore of " + packageName
2100                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2101                    }
2102                    sendFirstLaunchBroadcast(packageName, installerPackage,
2103                            firstUserIds, firstInstantUserIds);
2104                }
2105
2106                // Send broadcast package appeared if forward locked/external for all users
2107                // treat asec-hosted packages like removable media on upgrade
2108                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2109                    if (DEBUG_INSTALL) {
2110                        Slog.i(TAG, "upgrading pkg " + res.pkg
2111                                + " is ASEC-hosted -> AVAILABLE");
2112                    }
2113                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2114                    ArrayList<String> pkgList = new ArrayList<>(1);
2115                    pkgList.add(packageName);
2116                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2117                }
2118            }
2119
2120            // Work that needs to happen on first install within each user
2121            if (firstUserIds != null && firstUserIds.length > 0) {
2122                synchronized (mPackages) {
2123                    for (int userId : firstUserIds) {
2124                        // If this app is a browser and it's newly-installed for some
2125                        // users, clear any default-browser state in those users. The
2126                        // app's nature doesn't depend on the user, so we can just check
2127                        // its browser nature in any user and generalize.
2128                        if (packageIsBrowser(packageName, userId)) {
2129                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2130                        }
2131
2132                        // We may also need to apply pending (restored) runtime
2133                        // permission grants within these users.
2134                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2135                    }
2136                }
2137            }
2138
2139            if (allNewUsers && !update) {
2140                notifyPackageAdded(packageName);
2141            }
2142
2143            // Log current value of "unknown sources" setting
2144            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2145                    getUnknownSourcesSettings());
2146
2147            // Remove the replaced package's older resources safely now
2148            // We delete after a gc for applications  on sdcard.
2149            if (res.removedInfo != null && res.removedInfo.args != null) {
2150                Runtime.getRuntime().gc();
2151                synchronized (mInstallLock) {
2152                    res.removedInfo.args.doPostDeleteLI(true);
2153                }
2154            } else {
2155                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2156                // and not block here.
2157                VMRuntime.getRuntime().requestConcurrentGC();
2158            }
2159
2160            // Notify DexManager that the package was installed for new users.
2161            // The updated users should already be indexed and the package code paths
2162            // should not change.
2163            // Don't notify the manager for ephemeral apps as they are not expected to
2164            // survive long enough to benefit of background optimizations.
2165            for (int userId : firstUserIds) {
2166                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2167                // There's a race currently where some install events may interleave with an uninstall.
2168                // This can lead to package info being null (b/36642664).
2169                if (info != null) {
2170                    mDexManager.notifyPackageInstalled(info, userId);
2171                }
2172            }
2173        }
2174
2175        // If someone is watching installs - notify them
2176        if (installObserver != null) {
2177            try {
2178                Bundle extras = extrasForInstallResult(res);
2179                installObserver.onPackageInstalled(res.name, res.returnCode,
2180                        res.returnMsg, extras);
2181            } catch (RemoteException e) {
2182                Slog.i(TAG, "Observer no longer exists.");
2183            }
2184        }
2185    }
2186
2187    private StorageEventListener mStorageListener = new StorageEventListener() {
2188        @Override
2189        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2190            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2191                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2192                    final String volumeUuid = vol.getFsUuid();
2193
2194                    // Clean up any users or apps that were removed or recreated
2195                    // while this volume was missing
2196                    sUserManager.reconcileUsers(volumeUuid);
2197                    reconcileApps(volumeUuid);
2198
2199                    // Clean up any install sessions that expired or were
2200                    // cancelled while this volume was missing
2201                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2202
2203                    loadPrivatePackages(vol);
2204
2205                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2206                    unloadPrivatePackages(vol);
2207                }
2208            }
2209        }
2210
2211        @Override
2212        public void onVolumeForgotten(String fsUuid) {
2213            if (TextUtils.isEmpty(fsUuid)) {
2214                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2215                return;
2216            }
2217
2218            // Remove any apps installed on the forgotten volume
2219            synchronized (mPackages) {
2220                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2221                for (PackageSetting ps : packages) {
2222                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2223                    deletePackageVersioned(new VersionedPackage(ps.name,
2224                            PackageManager.VERSION_CODE_HIGHEST),
2225                            new LegacyPackageDeleteObserver(null).getBinder(),
2226                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2227                    // Try very hard to release any references to this package
2228                    // so we don't risk the system server being killed due to
2229                    // open FDs
2230                    AttributeCache.instance().removePackage(ps.name);
2231                }
2232
2233                mSettings.onVolumeForgotten(fsUuid);
2234                mSettings.writeLPr();
2235            }
2236        }
2237    };
2238
2239    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2240        Bundle extras = null;
2241        switch (res.returnCode) {
2242            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2243                extras = new Bundle();
2244                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2245                        res.origPermission);
2246                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2247                        res.origPackage);
2248                break;
2249            }
2250            case PackageManager.INSTALL_SUCCEEDED: {
2251                extras = new Bundle();
2252                extras.putBoolean(Intent.EXTRA_REPLACING,
2253                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2254                break;
2255            }
2256        }
2257        return extras;
2258    }
2259
2260    void scheduleWriteSettingsLocked() {
2261        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2262            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2263        }
2264    }
2265
2266    void scheduleWritePackageListLocked(int userId) {
2267        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2268            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2269            msg.arg1 = userId;
2270            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2271        }
2272    }
2273
2274    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2275        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2276        scheduleWritePackageRestrictionsLocked(userId);
2277    }
2278
2279    void scheduleWritePackageRestrictionsLocked(int userId) {
2280        final int[] userIds = (userId == UserHandle.USER_ALL)
2281                ? sUserManager.getUserIds() : new int[]{userId};
2282        for (int nextUserId : userIds) {
2283            if (!sUserManager.exists(nextUserId)) return;
2284            mDirtyUsers.add(nextUserId);
2285            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2286                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2287            }
2288        }
2289    }
2290
2291    public static PackageManagerService main(Context context, Installer installer,
2292            boolean factoryTest, boolean onlyCore) {
2293        // Self-check for initial settings.
2294        PackageManagerServiceCompilerMapping.checkProperties();
2295
2296        PackageManagerService m = new PackageManagerService(context, installer,
2297                factoryTest, onlyCore);
2298        m.enableSystemUserPackages();
2299        ServiceManager.addService("package", m);
2300        final PackageManagerNative pmn = m.new PackageManagerNative();
2301        ServiceManager.addService("package_native", pmn);
2302        return m;
2303    }
2304
2305    private void enableSystemUserPackages() {
2306        if (!UserManager.isSplitSystemUser()) {
2307            return;
2308        }
2309        // For system user, enable apps based on the following conditions:
2310        // - app is whitelisted or belong to one of these groups:
2311        //   -- system app which has no launcher icons
2312        //   -- system app which has INTERACT_ACROSS_USERS permission
2313        //   -- system IME app
2314        // - app is not in the blacklist
2315        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2316        Set<String> enableApps = new ArraySet<>();
2317        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2318                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2319                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2320        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2321        enableApps.addAll(wlApps);
2322        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2323                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2324        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2325        enableApps.removeAll(blApps);
2326        Log.i(TAG, "Applications installed for system user: " + enableApps);
2327        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2328                UserHandle.SYSTEM);
2329        final int allAppsSize = allAps.size();
2330        synchronized (mPackages) {
2331            for (int i = 0; i < allAppsSize; i++) {
2332                String pName = allAps.get(i);
2333                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2334                // Should not happen, but we shouldn't be failing if it does
2335                if (pkgSetting == null) {
2336                    continue;
2337                }
2338                boolean install = enableApps.contains(pName);
2339                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2340                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2341                            + " for system user");
2342                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2343                }
2344            }
2345            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2346        }
2347    }
2348
2349    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2350        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2351                Context.DISPLAY_SERVICE);
2352        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2353    }
2354
2355    /**
2356     * Requests that files preopted on a secondary system partition be copied to the data partition
2357     * if possible.  Note that the actual copying of the files is accomplished by init for security
2358     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2359     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2360     */
2361    private static void requestCopyPreoptedFiles() {
2362        final int WAIT_TIME_MS = 100;
2363        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2364        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2365            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2366            // We will wait for up to 100 seconds.
2367            final long timeStart = SystemClock.uptimeMillis();
2368            final long timeEnd = timeStart + 100 * 1000;
2369            long timeNow = timeStart;
2370            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2371                try {
2372                    Thread.sleep(WAIT_TIME_MS);
2373                } catch (InterruptedException e) {
2374                    // Do nothing
2375                }
2376                timeNow = SystemClock.uptimeMillis();
2377                if (timeNow > timeEnd) {
2378                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2379                    Slog.wtf(TAG, "cppreopt did not finish!");
2380                    break;
2381                }
2382            }
2383
2384            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2385        }
2386    }
2387
2388    public PackageManagerService(Context context, Installer installer,
2389            boolean factoryTest, boolean onlyCore) {
2390        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2391        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2392        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2393                SystemClock.uptimeMillis());
2394
2395        if (mSdkVersion <= 0) {
2396            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2397        }
2398
2399        mContext = context;
2400
2401        mFactoryTest = factoryTest;
2402        mOnlyCore = onlyCore;
2403        mMetrics = new DisplayMetrics();
2404        mInstaller = installer;
2405
2406        // Create sub-components that provide services / data. Order here is important.
2407        synchronized (mInstallLock) {
2408        synchronized (mPackages) {
2409            // Expose private service for system components to use.
2410            LocalServices.addService(
2411                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2412            sUserManager = new UserManagerService(context, this,
2413                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2414            mPermissionManager = PermissionManagerService.create(context,
2415                    new DefaultPermissionGrantedCallback() {
2416                        @Override
2417                        public void onDefaultRuntimePermissionsGranted(int userId) {
2418                            synchronized(mPackages) {
2419                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2420                            }
2421                        }
2422                    }, mPackages /*externalLock*/);
2423            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2424            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2425        }
2426        }
2427        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2428                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2429        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2430                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2431        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2432                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2433        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2434                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2435        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2436                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2437        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2438                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2439        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2440                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2441
2442        String separateProcesses = SystemProperties.get("debug.separate_processes");
2443        if (separateProcesses != null && separateProcesses.length() > 0) {
2444            if ("*".equals(separateProcesses)) {
2445                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2446                mSeparateProcesses = null;
2447                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2448            } else {
2449                mDefParseFlags = 0;
2450                mSeparateProcesses = separateProcesses.split(",");
2451                Slog.w(TAG, "Running with debug.separate_processes: "
2452                        + separateProcesses);
2453            }
2454        } else {
2455            mDefParseFlags = 0;
2456            mSeparateProcesses = null;
2457        }
2458
2459        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2460                "*dexopt*");
2461        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2462                installer, mInstallLock);
2463        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2464                dexManagerListener);
2465        mArtManagerService = new ArtManagerService(this, installer, mInstallLock);
2466        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2467
2468        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2469                FgThread.get().getLooper());
2470
2471        getDefaultDisplayMetrics(context, mMetrics);
2472
2473        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2474        SystemConfig systemConfig = SystemConfig.getInstance();
2475        mAvailableFeatures = systemConfig.getAvailableFeatures();
2476        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2477
2478        mProtectedPackages = new ProtectedPackages(mContext);
2479
2480        synchronized (mInstallLock) {
2481        // writer
2482        synchronized (mPackages) {
2483            mHandlerThread = new ServiceThread(TAG,
2484                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2485            mHandlerThread.start();
2486            mHandler = new PackageHandler(mHandlerThread.getLooper());
2487            mProcessLoggingHandler = new ProcessLoggingHandler();
2488            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2489            mInstantAppRegistry = new InstantAppRegistry(this);
2490
2491            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2492            final int builtInLibCount = libConfig.size();
2493            for (int i = 0; i < builtInLibCount; i++) {
2494                String name = libConfig.keyAt(i);
2495                String path = libConfig.valueAt(i);
2496                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2497                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2498            }
2499
2500            SELinuxMMAC.readInstallPolicy();
2501
2502            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2503            FallbackCategoryProvider.loadFallbacks();
2504            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2505
2506            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2507            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2508            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2509
2510            // Clean up orphaned packages for which the code path doesn't exist
2511            // and they are an update to a system app - caused by bug/32321269
2512            final int packageSettingCount = mSettings.mPackages.size();
2513            for (int i = packageSettingCount - 1; i >= 0; i--) {
2514                PackageSetting ps = mSettings.mPackages.valueAt(i);
2515                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2516                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2517                    mSettings.mPackages.removeAt(i);
2518                    mSettings.enableSystemPackageLPw(ps.name);
2519                }
2520            }
2521
2522            if (mFirstBoot) {
2523                requestCopyPreoptedFiles();
2524            }
2525
2526            String customResolverActivity = Resources.getSystem().getString(
2527                    R.string.config_customResolverActivity);
2528            if (TextUtils.isEmpty(customResolverActivity)) {
2529                customResolverActivity = null;
2530            } else {
2531                mCustomResolverComponentName = ComponentName.unflattenFromString(
2532                        customResolverActivity);
2533            }
2534
2535            long startTime = SystemClock.uptimeMillis();
2536
2537            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2538                    startTime);
2539
2540            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2541            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2542
2543            if (bootClassPath == null) {
2544                Slog.w(TAG, "No BOOTCLASSPATH found!");
2545            }
2546
2547            if (systemServerClassPath == null) {
2548                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2549            }
2550
2551            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2552
2553            final VersionInfo ver = mSettings.getInternalVersion();
2554            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2555            if (mIsUpgrade) {
2556                logCriticalInfo(Log.INFO,
2557                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2558            }
2559
2560            // when upgrading from pre-M, promote system app permissions from install to runtime
2561            mPromoteSystemApps =
2562                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2563
2564            // When upgrading from pre-N, we need to handle package extraction like first boot,
2565            // as there is no profiling data available.
2566            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2567
2568            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2569
2570            // save off the names of pre-existing system packages prior to scanning; we don't
2571            // want to automatically grant runtime permissions for new system apps
2572            if (mPromoteSystemApps) {
2573                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2574                while (pkgSettingIter.hasNext()) {
2575                    PackageSetting ps = pkgSettingIter.next();
2576                    if (isSystemApp(ps)) {
2577                        mExistingSystemPackages.add(ps.name);
2578                    }
2579                }
2580            }
2581
2582            mCacheDir = preparePackageParserCache(mIsUpgrade);
2583
2584            // Set flag to monitor and not change apk file paths when
2585            // scanning install directories.
2586            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2587
2588            if (mIsUpgrade || mFirstBoot) {
2589                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2590            }
2591
2592            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2593            // For security and version matching reason, only consider
2594            // overlay packages if they reside in the right directory.
2595            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2596                    mDefParseFlags
2597                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2598                    scanFlags
2599                    | SCAN_AS_SYSTEM
2600                    | SCAN_AS_VENDOR,
2601                    0);
2602            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2603                    mDefParseFlags
2604                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2605                    scanFlags
2606                    | SCAN_AS_SYSTEM
2607                    | SCAN_AS_PRODUCT,
2608                    0);
2609
2610            mParallelPackageParserCallback.findStaticOverlayPackages();
2611
2612            // Find base frameworks (resource packages without code).
2613            scanDirTracedLI(frameworkDir,
2614                    mDefParseFlags
2615                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2616                    scanFlags
2617                    | SCAN_NO_DEX
2618                    | SCAN_AS_SYSTEM
2619                    | SCAN_AS_PRIVILEGED,
2620                    0);
2621
2622            // Collect privileged system packages.
2623            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2624            scanDirTracedLI(privilegedAppDir,
2625                    mDefParseFlags
2626                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2627                    scanFlags
2628                    | SCAN_AS_SYSTEM
2629                    | SCAN_AS_PRIVILEGED,
2630                    0);
2631
2632            // Collect ordinary system packages.
2633            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2634            scanDirTracedLI(systemAppDir,
2635                    mDefParseFlags
2636                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2637                    scanFlags
2638                    | SCAN_AS_SYSTEM,
2639                    0);
2640
2641            // Collect privileged vendor packages.
2642            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2643            try {
2644                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2645            } catch (IOException e) {
2646                // failed to look up canonical path, continue with original one
2647            }
2648            scanDirTracedLI(privilegedVendorAppDir,
2649                    mDefParseFlags
2650                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2651                    scanFlags
2652                    | SCAN_AS_SYSTEM
2653                    | SCAN_AS_VENDOR
2654                    | SCAN_AS_PRIVILEGED,
2655                    0);
2656
2657            // Collect ordinary vendor packages.
2658            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2659            try {
2660                vendorAppDir = vendorAppDir.getCanonicalFile();
2661            } catch (IOException e) {
2662                // failed to look up canonical path, continue with original one
2663            }
2664            scanDirTracedLI(vendorAppDir,
2665                    mDefParseFlags
2666                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2667                    scanFlags
2668                    | SCAN_AS_SYSTEM
2669                    | SCAN_AS_VENDOR,
2670                    0);
2671
2672            // Collect privileged odm packages. /odm is another vendor partition
2673            // other than /vendor.
2674            File privilegedOdmAppDir = new File(Environment.getOdmDirectory(),
2675                        "priv-app");
2676            try {
2677                privilegedOdmAppDir = privilegedOdmAppDir.getCanonicalFile();
2678            } catch (IOException e) {
2679                // failed to look up canonical path, continue with original one
2680            }
2681            scanDirTracedLI(privilegedOdmAppDir,
2682                    mDefParseFlags
2683                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2684                    scanFlags
2685                    | SCAN_AS_SYSTEM
2686                    | SCAN_AS_VENDOR
2687                    | SCAN_AS_PRIVILEGED,
2688                    0);
2689
2690            // Collect ordinary odm packages. /odm is another vendor partition
2691            // other than /vendor.
2692            File odmAppDir = new File(Environment.getOdmDirectory(), "app");
2693            try {
2694                odmAppDir = odmAppDir.getCanonicalFile();
2695            } catch (IOException e) {
2696                // failed to look up canonical path, continue with original one
2697            }
2698            scanDirTracedLI(odmAppDir,
2699                    mDefParseFlags
2700                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2701                    scanFlags
2702                    | SCAN_AS_SYSTEM
2703                    | SCAN_AS_VENDOR,
2704                    0);
2705
2706            // Collect all OEM packages.
2707            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2708            scanDirTracedLI(oemAppDir,
2709                    mDefParseFlags
2710                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2711                    scanFlags
2712                    | SCAN_AS_SYSTEM
2713                    | SCAN_AS_OEM,
2714                    0);
2715
2716            // Collected privileged product packages.
2717            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2718            try {
2719                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2720            } catch (IOException e) {
2721                // failed to look up canonical path, continue with original one
2722            }
2723            scanDirTracedLI(privilegedProductAppDir,
2724                    mDefParseFlags
2725                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2726                    scanFlags
2727                    | SCAN_AS_SYSTEM
2728                    | SCAN_AS_PRODUCT
2729                    | SCAN_AS_PRIVILEGED,
2730                    0);
2731
2732            // Collect ordinary product packages.
2733            File productAppDir = new File(Environment.getProductDirectory(), "app");
2734            try {
2735                productAppDir = productAppDir.getCanonicalFile();
2736            } catch (IOException e) {
2737                // failed to look up canonical path, continue with original one
2738            }
2739            scanDirTracedLI(productAppDir,
2740                    mDefParseFlags
2741                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2742                    scanFlags
2743                    | SCAN_AS_SYSTEM
2744                    | SCAN_AS_PRODUCT,
2745                    0);
2746
2747            // Prune any system packages that no longer exist.
2748            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2749            // Stub packages must either be replaced with full versions in the /data
2750            // partition or be disabled.
2751            final List<String> stubSystemApps = new ArrayList<>();
2752            if (!mOnlyCore) {
2753                // do this first before mucking with mPackages for the "expecting better" case
2754                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2755                while (pkgIterator.hasNext()) {
2756                    final PackageParser.Package pkg = pkgIterator.next();
2757                    if (pkg.isStub) {
2758                        stubSystemApps.add(pkg.packageName);
2759                    }
2760                }
2761
2762                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2763                while (psit.hasNext()) {
2764                    PackageSetting ps = psit.next();
2765
2766                    /*
2767                     * If this is not a system app, it can't be a
2768                     * disable system app.
2769                     */
2770                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2771                        continue;
2772                    }
2773
2774                    /*
2775                     * If the package is scanned, it's not erased.
2776                     */
2777                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2778                    if (scannedPkg != null) {
2779                        /*
2780                         * If the system app is both scanned and in the
2781                         * disabled packages list, then it must have been
2782                         * added via OTA. Remove it from the currently
2783                         * scanned package so the previously user-installed
2784                         * application can be scanned.
2785                         */
2786                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2787                            logCriticalInfo(Log.WARN,
2788                                    "Expecting better updated system app for " + ps.name
2789                                    + "; removing system app.  Last known"
2790                                    + " codePath=" + ps.codePathString
2791                                    + ", versionCode=" + ps.versionCode
2792                                    + "; scanned versionCode=" + scannedPkg.getLongVersionCode());
2793                            removePackageLI(scannedPkg, true);
2794                            mExpectingBetter.put(ps.name, ps.codePath);
2795                        }
2796
2797                        continue;
2798                    }
2799
2800                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2801                        psit.remove();
2802                        logCriticalInfo(Log.WARN, "System package " + ps.name
2803                                + " no longer exists; it's data will be wiped");
2804                        // Actual deletion of code and data will be handled by later
2805                        // reconciliation step
2806                    } else {
2807                        // we still have a disabled system package, but, it still might have
2808                        // been removed. check the code path still exists and check there's
2809                        // still a package. the latter can happen if an OTA keeps the same
2810                        // code path, but, changes the package name.
2811                        final PackageSetting disabledPs =
2812                                mSettings.getDisabledSystemPkgLPr(ps.name);
2813                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2814                                || disabledPs.pkg == null) {
2815                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2816                        }
2817                    }
2818                }
2819            }
2820
2821            //delete tmp files
2822            deleteTempPackageFiles();
2823
2824            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2825
2826            // Remove any shared userIDs that have no associated packages
2827            mSettings.pruneSharedUsersLPw();
2828            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2829            final int systemPackagesCount = mPackages.size();
2830            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2831                    + " ms, packageCount: " + systemPackagesCount
2832                    + " , timePerPackage: "
2833                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2834                    + " , cached: " + cachedSystemApps);
2835            if (mIsUpgrade && systemPackagesCount > 0) {
2836                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2837                        ((int) systemScanTime) / systemPackagesCount);
2838            }
2839            if (!mOnlyCore) {
2840                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2841                        SystemClock.uptimeMillis());
2842                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2843
2844                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2845                        | PackageParser.PARSE_FORWARD_LOCK,
2846                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2847
2848                // Remove disable package settings for updated system apps that were
2849                // removed via an OTA. If the update is no longer present, remove the
2850                // app completely. Otherwise, revoke their system privileges.
2851                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2852                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2853                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2854                    final String msg;
2855                    if (deletedPkg == null) {
2856                        // should have found an update, but, we didn't; remove everything
2857                        msg = "Updated system package " + deletedAppName
2858                                + " no longer exists; removing its data";
2859                        // Actual deletion of code and data will be handled by later
2860                        // reconciliation step
2861                    } else {
2862                        // found an update; revoke system privileges
2863                        msg = "Updated system package + " + deletedAppName
2864                                + " no longer exists; revoking system privileges";
2865
2866                        // Don't do anything if a stub is removed from the system image. If
2867                        // we were to remove the uncompressed version from the /data partition,
2868                        // this is where it'd be done.
2869
2870                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2871                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2872                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2873                    }
2874                    logCriticalInfo(Log.WARN, msg);
2875                }
2876
2877                /*
2878                 * Make sure all system apps that we expected to appear on
2879                 * the userdata partition actually showed up. If they never
2880                 * appeared, crawl back and revive the system version.
2881                 */
2882                for (int i = 0; i < mExpectingBetter.size(); i++) {
2883                    final String packageName = mExpectingBetter.keyAt(i);
2884                    if (!mPackages.containsKey(packageName)) {
2885                        final File scanFile = mExpectingBetter.valueAt(i);
2886
2887                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2888                                + " but never showed up; reverting to system");
2889
2890                        final @ParseFlags int reparseFlags;
2891                        final @ScanFlags int rescanFlags;
2892                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2893                            reparseFlags =
2894                                    mDefParseFlags |
2895                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2896                            rescanFlags =
2897                                    scanFlags
2898                                    | SCAN_AS_SYSTEM
2899                                    | SCAN_AS_PRIVILEGED;
2900                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2901                            reparseFlags =
2902                                    mDefParseFlags |
2903                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2904                            rescanFlags =
2905                                    scanFlags
2906                                    | SCAN_AS_SYSTEM;
2907                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)
2908                                || FileUtils.contains(privilegedOdmAppDir, scanFile)) {
2909                            reparseFlags =
2910                                    mDefParseFlags |
2911                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2912                            rescanFlags =
2913                                    scanFlags
2914                                    | SCAN_AS_SYSTEM
2915                                    | SCAN_AS_VENDOR
2916                                    | SCAN_AS_PRIVILEGED;
2917                        } else if (FileUtils.contains(vendorAppDir, scanFile)
2918                                || FileUtils.contains(odmAppDir, scanFile)) {
2919                            reparseFlags =
2920                                    mDefParseFlags |
2921                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2922                            rescanFlags =
2923                                    scanFlags
2924                                    | SCAN_AS_SYSTEM
2925                                    | SCAN_AS_VENDOR;
2926                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2927                            reparseFlags =
2928                                    mDefParseFlags |
2929                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2930                            rescanFlags =
2931                                    scanFlags
2932                                    | SCAN_AS_SYSTEM
2933                                    | SCAN_AS_OEM;
2934                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2935                            reparseFlags =
2936                                    mDefParseFlags |
2937                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2938                            rescanFlags =
2939                                    scanFlags
2940                                    | SCAN_AS_SYSTEM
2941                                    | SCAN_AS_PRODUCT
2942                                    | SCAN_AS_PRIVILEGED;
2943                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2944                            reparseFlags =
2945                                    mDefParseFlags |
2946                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2947                            rescanFlags =
2948                                    scanFlags
2949                                    | SCAN_AS_SYSTEM
2950                                    | SCAN_AS_PRODUCT;
2951                        } else {
2952                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2953                            continue;
2954                        }
2955
2956                        mSettings.enableSystemPackageLPw(packageName);
2957
2958                        try {
2959                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2960                        } catch (PackageManagerException e) {
2961                            Slog.e(TAG, "Failed to parse original system package: "
2962                                    + e.getMessage());
2963                        }
2964                    }
2965                }
2966
2967                // Uncompress and install any stubbed system applications.
2968                // This must be done last to ensure all stubs are replaced or disabled.
2969                decompressSystemApplications(stubSystemApps, scanFlags);
2970
2971                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2972                                - cachedSystemApps;
2973
2974                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2975                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2976                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2977                        + " ms, packageCount: " + dataPackagesCount
2978                        + " , timePerPackage: "
2979                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2980                        + " , cached: " + cachedNonSystemApps);
2981                if (mIsUpgrade && dataPackagesCount > 0) {
2982                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2983                            ((int) dataScanTime) / dataPackagesCount);
2984                }
2985            }
2986            mExpectingBetter.clear();
2987
2988            // Resolve the storage manager.
2989            mStorageManagerPackage = getStorageManagerPackageName();
2990
2991            // Resolve protected action filters. Only the setup wizard is allowed to
2992            // have a high priority filter for these actions.
2993            mSetupWizardPackage = getSetupWizardPackageName();
2994            if (mProtectedFilters.size() > 0) {
2995                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2996                    Slog.i(TAG, "No setup wizard;"
2997                        + " All protected intents capped to priority 0");
2998                }
2999                for (ActivityIntentInfo filter : mProtectedFilters) {
3000                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
3001                        if (DEBUG_FILTERS) {
3002                            Slog.i(TAG, "Found setup wizard;"
3003                                + " allow priority " + filter.getPriority() + ";"
3004                                + " package: " + filter.activity.info.packageName
3005                                + " activity: " + filter.activity.className
3006                                + " priority: " + filter.getPriority());
3007                        }
3008                        // skip setup wizard; allow it to keep the high priority filter
3009                        continue;
3010                    }
3011                    if (DEBUG_FILTERS) {
3012                        Slog.i(TAG, "Protected action; cap priority to 0;"
3013                                + " package: " + filter.activity.info.packageName
3014                                + " activity: " + filter.activity.className
3015                                + " origPrio: " + filter.getPriority());
3016                    }
3017                    filter.setPriority(0);
3018                }
3019            }
3020
3021            mSystemTextClassifierPackage = getSystemTextClassifierPackageName();
3022
3023            mDeferProtectedFilters = false;
3024            mProtectedFilters.clear();
3025
3026            // Now that we know all of the shared libraries, update all clients to have
3027            // the correct library paths.
3028            updateAllSharedLibrariesLPw(null);
3029
3030            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
3031                // NOTE: We ignore potential failures here during a system scan (like
3032                // the rest of the commands above) because there's precious little we
3033                // can do about it. A settings error is reported, though.
3034                final List<String> changedAbiCodePath =
3035                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
3036                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
3037                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
3038                        final String codePathString = changedAbiCodePath.get(i);
3039                        try {
3040                            mInstaller.rmdex(codePathString,
3041                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
3042                        } catch (InstallerException ignored) {
3043                        }
3044                    }
3045                }
3046                // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same
3047                // SELinux domain.
3048                setting.fixSeInfoLocked();
3049            }
3050
3051            // Now that we know all the packages we are keeping,
3052            // read and update their last usage times.
3053            mPackageUsage.read(mPackages);
3054            mCompilerStats.read();
3055
3056            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
3057                    SystemClock.uptimeMillis());
3058            Slog.i(TAG, "Time to scan packages: "
3059                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
3060                    + " seconds");
3061
3062            // If the platform SDK has changed since the last time we booted,
3063            // we need to re-grant app permission to catch any new ones that
3064            // appear.  This is really a hack, and means that apps can in some
3065            // cases get permissions that the user didn't initially explicitly
3066            // allow...  it would be nice to have some better way to handle
3067            // this situation.
3068            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3069            if (sdkUpdated) {
3070                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3071                        + mSdkVersion + "; regranting permissions for internal storage");
3072            }
3073            mPermissionManager.updateAllPermissions(
3074                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3075                    mPermissionCallback);
3076            ver.sdkVersion = mSdkVersion;
3077
3078            // If this is the first boot or an update from pre-M, and it is a normal
3079            // boot, then we need to initialize the default preferred apps across
3080            // all defined users.
3081            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3082                for (UserInfo user : sUserManager.getUsers(true)) {
3083                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3084                    applyFactoryDefaultBrowserLPw(user.id);
3085                    primeDomainVerificationsLPw(user.id);
3086                }
3087            }
3088
3089            // Prepare storage for system user really early during boot,
3090            // since core system apps like SettingsProvider and SystemUI
3091            // can't wait for user to start
3092            final int storageFlags;
3093            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3094                storageFlags = StorageManager.FLAG_STORAGE_DE;
3095            } else {
3096                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3097            }
3098            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3099                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3100                    true /* onlyCoreApps */);
3101            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3102                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3103                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3104                traceLog.traceBegin("AppDataFixup");
3105                try {
3106                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3107                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3108                } catch (InstallerException e) {
3109                    Slog.w(TAG, "Trouble fixing GIDs", e);
3110                }
3111                traceLog.traceEnd();
3112
3113                traceLog.traceBegin("AppDataPrepare");
3114                if (deferPackages == null || deferPackages.isEmpty()) {
3115                    return;
3116                }
3117                int count = 0;
3118                for (String pkgName : deferPackages) {
3119                    PackageParser.Package pkg = null;
3120                    synchronized (mPackages) {
3121                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3122                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3123                            pkg = ps.pkg;
3124                        }
3125                    }
3126                    if (pkg != null) {
3127                        synchronized (mInstallLock) {
3128                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3129                                    true /* maybeMigrateAppData */);
3130                        }
3131                        count++;
3132                    }
3133                }
3134                traceLog.traceEnd();
3135                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3136            }, "prepareAppData");
3137
3138            // If this is first boot after an OTA, and a normal boot, then
3139            // we need to clear code cache directories.
3140            // Note that we do *not* clear the application profiles. These remain valid
3141            // across OTAs and are used to drive profile verification (post OTA) and
3142            // profile compilation (without waiting to collect a fresh set of profiles).
3143            if (mIsUpgrade && !onlyCore) {
3144                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3145                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3146                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3147                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3148                        // No apps are running this early, so no need to freeze
3149                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3150                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3151                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3152                    }
3153                }
3154                ver.fingerprint = Build.FINGERPRINT;
3155            }
3156
3157            checkDefaultBrowser();
3158
3159            // clear only after permissions and other defaults have been updated
3160            mExistingSystemPackages.clear();
3161            mPromoteSystemApps = false;
3162
3163            // All the changes are done during package scanning.
3164            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3165
3166            // can downgrade to reader
3167            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3168            mSettings.writeLPr();
3169            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3170            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3171                    SystemClock.uptimeMillis());
3172
3173            if (!mOnlyCore) {
3174                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3175                mRequiredInstallerPackage = getRequiredInstallerLPr();
3176                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3177                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3178                if (mIntentFilterVerifierComponent != null) {
3179                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3180                            mIntentFilterVerifierComponent);
3181                } else {
3182                    mIntentFilterVerifier = null;
3183                }
3184                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3185                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3186                        SharedLibraryInfo.VERSION_UNDEFINED);
3187                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3188                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3189                        SharedLibraryInfo.VERSION_UNDEFINED);
3190            } else {
3191                mRequiredVerifierPackage = null;
3192                mRequiredInstallerPackage = null;
3193                mRequiredUninstallerPackage = null;
3194                mIntentFilterVerifierComponent = null;
3195                mIntentFilterVerifier = null;
3196                mServicesSystemSharedLibraryPackageName = null;
3197                mSharedSystemSharedLibraryPackageName = null;
3198            }
3199
3200            mInstallerService = new PackageInstallerService(context, this);
3201            final Pair<ComponentName, String> instantAppResolverComponent =
3202                    getInstantAppResolverLPr();
3203            if (instantAppResolverComponent != null) {
3204                if (DEBUG_INSTANT) {
3205                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3206                }
3207                mInstantAppResolverConnection = new InstantAppResolverConnection(
3208                        mContext, instantAppResolverComponent.first,
3209                        instantAppResolverComponent.second);
3210                mInstantAppResolverSettingsComponent =
3211                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3212            } else {
3213                mInstantAppResolverConnection = null;
3214                mInstantAppResolverSettingsComponent = null;
3215            }
3216            updateInstantAppInstallerLocked(null);
3217
3218            // Read and update the usage of dex files.
3219            // Do this at the end of PM init so that all the packages have their
3220            // data directory reconciled.
3221            // At this point we know the code paths of the packages, so we can validate
3222            // the disk file and build the internal cache.
3223            // The usage file is expected to be small so loading and verifying it
3224            // should take a fairly small time compare to the other activities (e.g. package
3225            // scanning).
3226            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3227            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3228            for (int userId : currentUserIds) {
3229                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3230            }
3231            mDexManager.load(userPackages);
3232            if (mIsUpgrade) {
3233                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3234                        (int) (SystemClock.uptimeMillis() - startTime));
3235            }
3236        } // synchronized (mPackages)
3237        } // synchronized (mInstallLock)
3238
3239        // Now after opening every single application zip, make sure they
3240        // are all flushed.  Not really needed, but keeps things nice and
3241        // tidy.
3242        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3243        Runtime.getRuntime().gc();
3244        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3245
3246        // The initial scanning above does many calls into installd while
3247        // holding the mPackages lock, but we're mostly interested in yelling
3248        // once we have a booted system.
3249        mInstaller.setWarnIfHeld(mPackages);
3250
3251        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3252    }
3253
3254    /**
3255     * Uncompress and install stub applications.
3256     * <p>In order to save space on the system partition, some applications are shipped in a
3257     * compressed form. In addition the compressed bits for the full application, the
3258     * system image contains a tiny stub comprised of only the Android manifest.
3259     * <p>During the first boot, attempt to uncompress and install the full application. If
3260     * the application can't be installed for any reason, disable the stub and prevent
3261     * uncompressing the full application during future boots.
3262     * <p>In order to forcefully attempt an installation of a full application, go to app
3263     * settings and enable the application.
3264     */
3265    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3266        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3267            final String pkgName = stubSystemApps.get(i);
3268            // skip if the system package is already disabled
3269            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3270                stubSystemApps.remove(i);
3271                continue;
3272            }
3273            // skip if the package isn't installed (?!); this should never happen
3274            final PackageParser.Package pkg = mPackages.get(pkgName);
3275            if (pkg == null) {
3276                stubSystemApps.remove(i);
3277                continue;
3278            }
3279            // skip if the package has been disabled by the user
3280            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3281            if (ps != null) {
3282                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3283                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3284                    stubSystemApps.remove(i);
3285                    continue;
3286                }
3287            }
3288
3289            if (DEBUG_COMPRESSION) {
3290                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3291            }
3292
3293            // uncompress the binary to its eventual destination on /data
3294            final File scanFile = decompressPackage(pkg);
3295            if (scanFile == null) {
3296                continue;
3297            }
3298
3299            // install the package to replace the stub on /system
3300            try {
3301                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3302                removePackageLI(pkg, true /*chatty*/);
3303                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3304                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3305                        UserHandle.USER_SYSTEM, "android");
3306                stubSystemApps.remove(i);
3307                continue;
3308            } catch (PackageManagerException e) {
3309                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3310            }
3311
3312            // any failed attempt to install the package will be cleaned up later
3313        }
3314
3315        // disable any stub still left; these failed to install the full application
3316        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3317            final String pkgName = stubSystemApps.get(i);
3318            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3319            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3320                    UserHandle.USER_SYSTEM, "android");
3321            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3322        }
3323    }
3324
3325    /**
3326     * Decompresses the given package on the system image onto
3327     * the /data partition.
3328     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3329     */
3330    private File decompressPackage(PackageParser.Package pkg) {
3331        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3332        if (compressedFiles == null || compressedFiles.length == 0) {
3333            if (DEBUG_COMPRESSION) {
3334                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3335            }
3336            return null;
3337        }
3338        final File dstCodePath =
3339                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3340        int ret = PackageManager.INSTALL_SUCCEEDED;
3341        try {
3342            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3343            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3344            for (File srcFile : compressedFiles) {
3345                final String srcFileName = srcFile.getName();
3346                final String dstFileName = srcFileName.substring(
3347                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3348                final File dstFile = new File(dstCodePath, dstFileName);
3349                ret = decompressFile(srcFile, dstFile);
3350                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3351                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3352                            + "; pkg: " + pkg.packageName
3353                            + ", file: " + dstFileName);
3354                    break;
3355                }
3356            }
3357        } catch (ErrnoException e) {
3358            logCriticalInfo(Log.ERROR, "Failed to decompress"
3359                    + "; pkg: " + pkg.packageName
3360                    + ", err: " + e.errno);
3361        }
3362        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3363            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3364            NativeLibraryHelper.Handle handle = null;
3365            try {
3366                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3367                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3368                        null /*abiOverride*/);
3369            } catch (IOException e) {
3370                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3371                        + "; pkg: " + pkg.packageName);
3372                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3373            } finally {
3374                IoUtils.closeQuietly(handle);
3375            }
3376        }
3377        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3378            if (dstCodePath == null || !dstCodePath.exists()) {
3379                return null;
3380            }
3381            removeCodePathLI(dstCodePath);
3382            return null;
3383        }
3384
3385        return dstCodePath;
3386    }
3387
3388    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3389        // we're only interested in updating the installer appliction when 1) it's not
3390        // already set or 2) the modified package is the installer
3391        if (mInstantAppInstallerActivity != null
3392                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3393                        .equals(modifiedPackage)) {
3394            return;
3395        }
3396        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3397    }
3398
3399    private static File preparePackageParserCache(boolean isUpgrade) {
3400        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3401            return null;
3402        }
3403
3404        // Disable package parsing on eng builds to allow for faster incremental development.
3405        if (Build.IS_ENG) {
3406            return null;
3407        }
3408
3409        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3410            Slog.i(TAG, "Disabling package parser cache due to system property.");
3411            return null;
3412        }
3413
3414        // The base directory for the package parser cache lives under /data/system/.
3415        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3416                "package_cache");
3417        if (cacheBaseDir == null) {
3418            return null;
3419        }
3420
3421        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3422        // This also serves to "GC" unused entries when the package cache version changes (which
3423        // can only happen during upgrades).
3424        if (isUpgrade) {
3425            FileUtils.deleteContents(cacheBaseDir);
3426        }
3427
3428
3429        // Return the versioned package cache directory. This is something like
3430        // "/data/system/package_cache/1"
3431        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3432
3433        if (cacheDir == null) {
3434            // Something went wrong. Attempt to delete everything and return.
3435            Slog.wtf(TAG, "Cache directory cannot be created - wiping base dir " + cacheBaseDir);
3436            FileUtils.deleteContentsAndDir(cacheBaseDir);
3437            return null;
3438        }
3439
3440        // The following is a workaround to aid development on non-numbered userdebug
3441        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3442        // the system partition is newer.
3443        //
3444        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3445        // that starts with "eng." to signify that this is an engineering build and not
3446        // destined for release.
3447        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3448            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3449
3450            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3451            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3452            // in general and should not be used for production changes. In this specific case,
3453            // we know that they will work.
3454            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3455            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3456                FileUtils.deleteContents(cacheBaseDir);
3457                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3458            }
3459        }
3460
3461        return cacheDir;
3462    }
3463
3464    @Override
3465    public boolean isFirstBoot() {
3466        // allow instant applications
3467        return mFirstBoot;
3468    }
3469
3470    @Override
3471    public boolean isOnlyCoreApps() {
3472        // allow instant applications
3473        return mOnlyCore;
3474    }
3475
3476    @Override
3477    public boolean isUpgrade() {
3478        // allow instant applications
3479        // The system property allows testing ota flow when upgraded to the same image.
3480        return mIsUpgrade || SystemProperties.getBoolean(
3481                "persist.pm.mock-upgrade", false /* default */);
3482    }
3483
3484    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3485        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3486
3487        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3488                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3489                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3490        if (matches.size() == 1) {
3491            return matches.get(0).getComponentInfo().packageName;
3492        } else if (matches.size() == 0) {
3493            Log.e(TAG, "There should probably be a verifier, but, none were found");
3494            return null;
3495        }
3496        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3497    }
3498
3499    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3500        synchronized (mPackages) {
3501            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3502            if (libraryEntry == null) {
3503                throw new IllegalStateException("Missing required shared library:" + name);
3504            }
3505            return libraryEntry.apk;
3506        }
3507    }
3508
3509    private @NonNull String getRequiredInstallerLPr() {
3510        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3511        intent.addCategory(Intent.CATEGORY_DEFAULT);
3512        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3513
3514        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3515                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3516                UserHandle.USER_SYSTEM);
3517        if (matches.size() == 1) {
3518            ResolveInfo resolveInfo = matches.get(0);
3519            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3520                throw new RuntimeException("The installer must be a privileged app");
3521            }
3522            return matches.get(0).getComponentInfo().packageName;
3523        } else {
3524            throw new RuntimeException("There must be exactly one installer; found " + matches);
3525        }
3526    }
3527
3528    private @NonNull String getRequiredUninstallerLPr() {
3529        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3530        intent.addCategory(Intent.CATEGORY_DEFAULT);
3531        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3532
3533        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3534                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3535                UserHandle.USER_SYSTEM);
3536        if (resolveInfo == null ||
3537                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3538            throw new RuntimeException("There must be exactly one uninstaller; found "
3539                    + resolveInfo);
3540        }
3541        return resolveInfo.getComponentInfo().packageName;
3542    }
3543
3544    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3545        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3546
3547        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3548                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3549                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3550        ResolveInfo best = null;
3551        final int N = matches.size();
3552        for (int i = 0; i < N; i++) {
3553            final ResolveInfo cur = matches.get(i);
3554            final String packageName = cur.getComponentInfo().packageName;
3555            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3556                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3557                continue;
3558            }
3559
3560            if (best == null || cur.priority > best.priority) {
3561                best = cur;
3562            }
3563        }
3564
3565        if (best != null) {
3566            return best.getComponentInfo().getComponentName();
3567        }
3568        Slog.w(TAG, "Intent filter verifier not found");
3569        return null;
3570    }
3571
3572    @Override
3573    public @Nullable ComponentName getInstantAppResolverComponent() {
3574        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3575            return null;
3576        }
3577        synchronized (mPackages) {
3578            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3579            if (instantAppResolver == null) {
3580                return null;
3581            }
3582            return instantAppResolver.first;
3583        }
3584    }
3585
3586    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3587        final String[] packageArray =
3588                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3589        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3590            if (DEBUG_INSTANT) {
3591                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3592            }
3593            return null;
3594        }
3595
3596        final int callingUid = Binder.getCallingUid();
3597        final int resolveFlags =
3598                MATCH_DIRECT_BOOT_AWARE
3599                | MATCH_DIRECT_BOOT_UNAWARE
3600                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3601        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3602        final Intent resolverIntent = new Intent(actionName);
3603        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3604                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3605        final int N = resolvers.size();
3606        if (N == 0) {
3607            if (DEBUG_INSTANT) {
3608                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3609            }
3610            return null;
3611        }
3612
3613        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3614        for (int i = 0; i < N; i++) {
3615            final ResolveInfo info = resolvers.get(i);
3616
3617            if (info.serviceInfo == null) {
3618                continue;
3619            }
3620
3621            final String packageName = info.serviceInfo.packageName;
3622            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3623                if (DEBUG_INSTANT) {
3624                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3625                            + " pkg: " + packageName + ", info:" + info);
3626                }
3627                continue;
3628            }
3629
3630            if (DEBUG_INSTANT) {
3631                Slog.v(TAG, "Ephemeral resolver found;"
3632                        + " pkg: " + packageName + ", info:" + info);
3633            }
3634            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3635        }
3636        if (DEBUG_INSTANT) {
3637            Slog.v(TAG, "Ephemeral resolver NOT found");
3638        }
3639        return null;
3640    }
3641
3642    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3643        String[] orderedActions = Build.IS_ENG
3644                ? new String[]{
3645                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3646                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3647                : new String[]{
3648                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3649
3650        final int resolveFlags =
3651                MATCH_DIRECT_BOOT_AWARE
3652                        | MATCH_DIRECT_BOOT_UNAWARE
3653                        | Intent.FLAG_IGNORE_EPHEMERAL
3654                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3655        final Intent intent = new Intent();
3656        intent.addCategory(Intent.CATEGORY_DEFAULT);
3657        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3658        List<ResolveInfo> matches = null;
3659        for (String action : orderedActions) {
3660            intent.setAction(action);
3661            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3662                    resolveFlags, UserHandle.USER_SYSTEM);
3663            if (matches.isEmpty()) {
3664                if (DEBUG_INSTANT) {
3665                    Slog.d(TAG, "Instant App installer not found with " + action);
3666                }
3667            } else {
3668                break;
3669            }
3670        }
3671        Iterator<ResolveInfo> iter = matches.iterator();
3672        while (iter.hasNext()) {
3673            final ResolveInfo rInfo = iter.next();
3674            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3675            if (ps != null) {
3676                final PermissionsState permissionsState = ps.getPermissionsState();
3677                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3678                        || Build.IS_ENG) {
3679                    continue;
3680                }
3681            }
3682            iter.remove();
3683        }
3684        if (matches.size() == 0) {
3685            return null;
3686        } else if (matches.size() == 1) {
3687            return (ActivityInfo) matches.get(0).getComponentInfo();
3688        } else {
3689            throw new RuntimeException(
3690                    "There must be at most one ephemeral installer; found " + matches);
3691        }
3692    }
3693
3694    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3695            @NonNull ComponentName resolver) {
3696        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3697                .addCategory(Intent.CATEGORY_DEFAULT)
3698                .setPackage(resolver.getPackageName());
3699        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3700        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3701                UserHandle.USER_SYSTEM);
3702        if (matches.isEmpty()) {
3703            return null;
3704        }
3705        return matches.get(0).getComponentInfo().getComponentName();
3706    }
3707
3708    private void primeDomainVerificationsLPw(int userId) {
3709        if (DEBUG_DOMAIN_VERIFICATION) {
3710            Slog.d(TAG, "Priming domain verifications in user " + userId);
3711        }
3712
3713        SystemConfig systemConfig = SystemConfig.getInstance();
3714        ArraySet<String> packages = systemConfig.getLinkedApps();
3715
3716        for (String packageName : packages) {
3717            PackageParser.Package pkg = mPackages.get(packageName);
3718            if (pkg != null) {
3719                if (!pkg.isSystem()) {
3720                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3721                    continue;
3722                }
3723
3724                ArraySet<String> domains = null;
3725                for (PackageParser.Activity a : pkg.activities) {
3726                    for (ActivityIntentInfo filter : a.intents) {
3727                        if (hasValidDomains(filter)) {
3728                            if (domains == null) {
3729                                domains = new ArraySet<String>();
3730                            }
3731                            domains.addAll(filter.getHostsList());
3732                        }
3733                    }
3734                }
3735
3736                if (domains != null && domains.size() > 0) {
3737                    if (DEBUG_DOMAIN_VERIFICATION) {
3738                        Slog.v(TAG, "      + " + packageName);
3739                    }
3740                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3741                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3742                    // and then 'always' in the per-user state actually used for intent resolution.
3743                    final IntentFilterVerificationInfo ivi;
3744                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3745                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3746                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3747                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3748                } else {
3749                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3750                            + "' does not handle web links");
3751                }
3752            } else {
3753                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3754            }
3755        }
3756
3757        scheduleWritePackageRestrictionsLocked(userId);
3758        scheduleWriteSettingsLocked();
3759    }
3760
3761    private void applyFactoryDefaultBrowserLPw(int userId) {
3762        // The default browser app's package name is stored in a string resource,
3763        // with a product-specific overlay used for vendor customization.
3764        String browserPkg = mContext.getResources().getString(
3765                com.android.internal.R.string.default_browser);
3766        if (!TextUtils.isEmpty(browserPkg)) {
3767            // non-empty string => required to be a known package
3768            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3769            if (ps == null) {
3770                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3771                browserPkg = null;
3772            } else {
3773                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3774            }
3775        }
3776
3777        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3778        // default.  If there's more than one, just leave everything alone.
3779        if (browserPkg == null) {
3780            calculateDefaultBrowserLPw(userId);
3781        }
3782    }
3783
3784    private void calculateDefaultBrowserLPw(int userId) {
3785        List<String> allBrowsers = resolveAllBrowserApps(userId);
3786        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3787        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3788    }
3789
3790    private List<String> resolveAllBrowserApps(int userId) {
3791        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3792        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3793                PackageManager.MATCH_ALL, userId);
3794
3795        final int count = list.size();
3796        List<String> result = new ArrayList<String>(count);
3797        for (int i=0; i<count; i++) {
3798            ResolveInfo info = list.get(i);
3799            if (info.activityInfo == null
3800                    || !info.handleAllWebDataURI
3801                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3802                    || result.contains(info.activityInfo.packageName)) {
3803                continue;
3804            }
3805            result.add(info.activityInfo.packageName);
3806        }
3807
3808        return result;
3809    }
3810
3811    private boolean packageIsBrowser(String packageName, int userId) {
3812        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3813                PackageManager.MATCH_ALL, userId);
3814        final int N = list.size();
3815        for (int i = 0; i < N; i++) {
3816            ResolveInfo info = list.get(i);
3817            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3818                return true;
3819            }
3820        }
3821        return false;
3822    }
3823
3824    private void checkDefaultBrowser() {
3825        final int myUserId = UserHandle.myUserId();
3826        final String packageName = getDefaultBrowserPackageName(myUserId);
3827        if (packageName != null) {
3828            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3829            if (info == null) {
3830                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3831                synchronized (mPackages) {
3832                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3833                }
3834            }
3835        }
3836    }
3837
3838    @Override
3839    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3840            throws RemoteException {
3841        try {
3842            return super.onTransact(code, data, reply, flags);
3843        } catch (RuntimeException e) {
3844            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3845                Slog.wtf(TAG, "Package Manager Crash", e);
3846            }
3847            throw e;
3848        }
3849    }
3850
3851    static int[] appendInts(int[] cur, int[] add) {
3852        if (add == null) return cur;
3853        if (cur == null) return add;
3854        final int N = add.length;
3855        for (int i=0; i<N; i++) {
3856            cur = appendInt(cur, add[i]);
3857        }
3858        return cur;
3859    }
3860
3861    /**
3862     * Returns whether or not a full application can see an instant application.
3863     * <p>
3864     * Currently, there are three cases in which this can occur:
3865     * <ol>
3866     * <li>The calling application is a "special" process. Special processes
3867     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3868     * <li>The calling application has the permission
3869     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3870     * <li>The calling application is the default launcher on the
3871     *     system partition.</li>
3872     * </ol>
3873     */
3874    private boolean canViewInstantApps(int callingUid, int userId) {
3875        if (callingUid < Process.FIRST_APPLICATION_UID) {
3876            return true;
3877        }
3878        if (mContext.checkCallingOrSelfPermission(
3879                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3880            return true;
3881        }
3882        if (mContext.checkCallingOrSelfPermission(
3883                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3884            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3885            if (homeComponent != null
3886                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3887                return true;
3888            }
3889        }
3890        return false;
3891    }
3892
3893    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3894        if (!sUserManager.exists(userId)) return null;
3895        if (ps == null) {
3896            return null;
3897        }
3898        final int callingUid = Binder.getCallingUid();
3899        // Filter out ephemeral app metadata:
3900        //   * The system/shell/root can see metadata for any app
3901        //   * An installed app can see metadata for 1) other installed apps
3902        //     and 2) ephemeral apps that have explicitly interacted with it
3903        //   * Ephemeral apps can only see their own data and exposed installed apps
3904        //   * Holding a signature permission allows seeing instant apps
3905        if (filterAppAccessLPr(ps, callingUid, userId)) {
3906            return null;
3907        }
3908
3909        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3910                && ps.isSystem()) {
3911            flags |= MATCH_ANY_USER;
3912        }
3913
3914        final PackageUserState state = ps.readUserState(userId);
3915        PackageParser.Package p = ps.pkg;
3916        if (p != null) {
3917            final PermissionsState permissionsState = ps.getPermissionsState();
3918
3919            // Compute GIDs only if requested
3920            final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3921                    ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3922            // Compute granted permissions only if package has requested permissions
3923            final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3924                    ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3925
3926            PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3927                    ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3928
3929            if (packageInfo == null) {
3930                return null;
3931            }
3932
3933            packageInfo.packageName = packageInfo.applicationInfo.packageName =
3934                    resolveExternalPackageNameLPr(p);
3935
3936            return packageInfo;
3937        } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
3938            PackageInfo pi = new PackageInfo();
3939            pi.packageName = ps.name;
3940            pi.setLongVersionCode(ps.versionCode);
3941            pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
3942            pi.firstInstallTime = ps.firstInstallTime;
3943            pi.lastUpdateTime = ps.lastUpdateTime;
3944
3945            ApplicationInfo ai = new ApplicationInfo();
3946            ai.packageName = ps.name;
3947            ai.uid = UserHandle.getUid(userId, ps.appId);
3948            ai.primaryCpuAbi = ps.primaryCpuAbiString;
3949            ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
3950            ai.setVersionCode(ps.versionCode);
3951            ai.flags = ps.pkgFlags;
3952            ai.privateFlags = ps.pkgPrivateFlags;
3953            pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
3954
3955            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
3956                    + ps.name + "]. Provides a minimum info.");
3957            return pi;
3958        } else {
3959            return null;
3960        }
3961    }
3962
3963    @Override
3964    public void checkPackageStartable(String packageName, int userId) {
3965        final int callingUid = Binder.getCallingUid();
3966        if (getInstantAppPackageName(callingUid) != null) {
3967            throw new SecurityException("Instant applications don't have access to this method");
3968        }
3969        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3970        synchronized (mPackages) {
3971            final PackageSetting ps = mSettings.mPackages.get(packageName);
3972            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3973                throw new SecurityException("Package " + packageName + " was not found!");
3974            }
3975
3976            if (!ps.getInstalled(userId)) {
3977                throw new SecurityException(
3978                        "Package " + packageName + " was not installed for user " + userId + "!");
3979            }
3980
3981            if (mSafeMode && !ps.isSystem()) {
3982                throw new SecurityException("Package " + packageName + " not a system app!");
3983            }
3984
3985            if (mFrozenPackages.contains(packageName)) {
3986                throw new SecurityException("Package " + packageName + " is currently frozen!");
3987            }
3988
3989            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3990                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3991            }
3992        }
3993    }
3994
3995    @Override
3996    public boolean isPackageAvailable(String packageName, int userId) {
3997        if (!sUserManager.exists(userId)) return false;
3998        final int callingUid = Binder.getCallingUid();
3999        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4000                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
4001        synchronized (mPackages) {
4002            PackageParser.Package p = mPackages.get(packageName);
4003            if (p != null) {
4004                final PackageSetting ps = (PackageSetting) p.mExtras;
4005                if (filterAppAccessLPr(ps, callingUid, userId)) {
4006                    return false;
4007                }
4008                if (ps != null) {
4009                    final PackageUserState state = ps.readUserState(userId);
4010                    if (state != null) {
4011                        return PackageParser.isAvailable(state);
4012                    }
4013                }
4014            }
4015        }
4016        return false;
4017    }
4018
4019    @Override
4020    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
4021        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
4022                flags, Binder.getCallingUid(), userId);
4023    }
4024
4025    @Override
4026    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
4027            int flags, int userId) {
4028        return getPackageInfoInternal(versionedPackage.getPackageName(),
4029                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
4030    }
4031
4032    /**
4033     * Important: The provided filterCallingUid is used exclusively to filter out packages
4034     * that can be seen based on user state. It's typically the original caller uid prior
4035     * to clearing. Because it can only be provided by trusted code, it's value can be
4036     * trusted and will be used as-is; unlike userId which will be validated by this method.
4037     */
4038    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
4039            int flags, int filterCallingUid, int userId) {
4040        if (!sUserManager.exists(userId)) return null;
4041        flags = updateFlagsForPackage(flags, userId, packageName);
4042        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4043                false /* requireFullPermission */, false /* checkShell */, "get package info");
4044
4045        // reader
4046        synchronized (mPackages) {
4047            // Normalize package name to handle renamed packages and static libs
4048            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
4049
4050            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
4051            if (matchFactoryOnly) {
4052                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
4053                if (ps != null) {
4054                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4055                        return null;
4056                    }
4057                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4058                        return null;
4059                    }
4060                    return generatePackageInfo(ps, flags, userId);
4061                }
4062            }
4063
4064            PackageParser.Package p = mPackages.get(packageName);
4065            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
4066                return null;
4067            }
4068            if (DEBUG_PACKAGE_INFO)
4069                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4070            if (p != null) {
4071                final PackageSetting ps = (PackageSetting) p.mExtras;
4072                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4073                    return null;
4074                }
4075                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4076                    return null;
4077                }
4078                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4079            }
4080            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4081                final PackageSetting ps = mSettings.mPackages.get(packageName);
4082                if (ps == null) return null;
4083                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4084                    return null;
4085                }
4086                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4087                    return null;
4088                }
4089                return generatePackageInfo(ps, flags, userId);
4090            }
4091        }
4092        return null;
4093    }
4094
4095    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4096        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4097            return true;
4098        }
4099        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4100            return true;
4101        }
4102        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4103            return true;
4104        }
4105        return false;
4106    }
4107
4108    private boolean isComponentVisibleToInstantApp(
4109            @Nullable ComponentName component, @ComponentType int type) {
4110        if (type == TYPE_ACTIVITY) {
4111            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4112            if (activity == null) {
4113                return false;
4114            }
4115            final boolean visibleToInstantApp =
4116                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4117            final boolean explicitlyVisibleToInstantApp =
4118                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4119            return visibleToInstantApp && explicitlyVisibleToInstantApp;
4120        } else if (type == TYPE_RECEIVER) {
4121            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4122            if (activity == null) {
4123                return false;
4124            }
4125            final boolean visibleToInstantApp =
4126                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4127            final boolean explicitlyVisibleToInstantApp =
4128                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4129            return visibleToInstantApp && !explicitlyVisibleToInstantApp;
4130        } else if (type == TYPE_SERVICE) {
4131            final PackageParser.Service service = mServices.mServices.get(component);
4132            return service != null
4133                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4134                    : false;
4135        } else if (type == TYPE_PROVIDER) {
4136            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4137            return provider != null
4138                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4139                    : false;
4140        } else if (type == TYPE_UNKNOWN) {
4141            return isComponentVisibleToInstantApp(component);
4142        }
4143        return false;
4144    }
4145
4146    /**
4147     * Returns whether or not access to the application should be filtered.
4148     * <p>
4149     * Access may be limited based upon whether the calling or target applications
4150     * are instant applications.
4151     *
4152     * @see #canAccessInstantApps(int)
4153     */
4154    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4155            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4156        // if we're in an isolated process, get the real calling UID
4157        if (Process.isIsolated(callingUid)) {
4158            callingUid = mIsolatedOwners.get(callingUid);
4159        }
4160        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4161        final boolean callerIsInstantApp = instantAppPkgName != null;
4162        if (ps == null) {
4163            if (callerIsInstantApp) {
4164                // pretend the application exists, but, needs to be filtered
4165                return true;
4166            }
4167            return false;
4168        }
4169        // if the target and caller are the same application, don't filter
4170        if (isCallerSameApp(ps.name, callingUid)) {
4171            return false;
4172        }
4173        if (callerIsInstantApp) {
4174            // both caller and target are both instant, but, different applications, filter
4175            if (ps.getInstantApp(userId)) {
4176                return true;
4177            }
4178            // request for a specific component; if it hasn't been explicitly exposed through
4179            // property or instrumentation target, filter
4180            if (component != null) {
4181                final PackageParser.Instrumentation instrumentation =
4182                        mInstrumentation.get(component);
4183                if (instrumentation != null
4184                        && isCallerSameApp(instrumentation.info.targetPackage, callingUid)) {
4185                    return false;
4186                }
4187                return !isComponentVisibleToInstantApp(component, componentType);
4188            }
4189            // request for application; if no components have been explicitly exposed, filter
4190            return !ps.pkg.visibleToInstantApps;
4191        }
4192        if (ps.getInstantApp(userId)) {
4193            // caller can see all components of all instant applications, don't filter
4194            if (canViewInstantApps(callingUid, userId)) {
4195                return false;
4196            }
4197            // request for a specific instant application component, filter
4198            if (component != null) {
4199                return true;
4200            }
4201            // request for an instant application; if the caller hasn't been granted access, filter
4202            return !mInstantAppRegistry.isInstantAccessGranted(
4203                    userId, UserHandle.getAppId(callingUid), ps.appId);
4204        }
4205        return false;
4206    }
4207
4208    /**
4209     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4210     */
4211    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4212        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4213    }
4214
4215    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4216            int flags) {
4217        // Callers can access only the libs they depend on, otherwise they need to explicitly
4218        // ask for the shared libraries given the caller is allowed to access all static libs.
4219        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4220            // System/shell/root get to see all static libs
4221            final int appId = UserHandle.getAppId(uid);
4222            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4223                    || appId == Process.ROOT_UID) {
4224                return false;
4225            }
4226            // Installer gets to see all static libs.
4227            if (PackageManager.PERMISSION_GRANTED
4228                    == checkUidPermission(Manifest.permission.INSTALL_PACKAGES, uid)) {
4229                return false;
4230            }
4231        }
4232
4233        // No package means no static lib as it is always on internal storage
4234        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4235            return false;
4236        }
4237
4238        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4239                ps.pkg.staticSharedLibVersion);
4240        if (libEntry == null) {
4241            return false;
4242        }
4243
4244        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4245        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4246        if (uidPackageNames == null) {
4247            return true;
4248        }
4249
4250        for (String uidPackageName : uidPackageNames) {
4251            if (ps.name.equals(uidPackageName)) {
4252                return false;
4253            }
4254            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4255            if (uidPs != null) {
4256                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4257                        libEntry.info.getName());
4258                if (index < 0) {
4259                    continue;
4260                }
4261                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4262                    return false;
4263                }
4264            }
4265        }
4266        return true;
4267    }
4268
4269    @Override
4270    public String[] currentToCanonicalPackageNames(String[] names) {
4271        final int callingUid = Binder.getCallingUid();
4272        if (getInstantAppPackageName(callingUid) != null) {
4273            return names;
4274        }
4275        final String[] out = new String[names.length];
4276        // reader
4277        synchronized (mPackages) {
4278            final int callingUserId = UserHandle.getUserId(callingUid);
4279            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4280            for (int i=names.length-1; i>=0; i--) {
4281                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4282                boolean translateName = false;
4283                if (ps != null && ps.realName != null) {
4284                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4285                    translateName = !targetIsInstantApp
4286                            || canViewInstantApps
4287                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4288                                    UserHandle.getAppId(callingUid), ps.appId);
4289                }
4290                out[i] = translateName ? ps.realName : names[i];
4291            }
4292        }
4293        return out;
4294    }
4295
4296    @Override
4297    public String[] canonicalToCurrentPackageNames(String[] names) {
4298        final int callingUid = Binder.getCallingUid();
4299        if (getInstantAppPackageName(callingUid) != null) {
4300            return names;
4301        }
4302        final String[] out = new String[names.length];
4303        // reader
4304        synchronized (mPackages) {
4305            final int callingUserId = UserHandle.getUserId(callingUid);
4306            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4307            for (int i=names.length-1; i>=0; i--) {
4308                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4309                boolean translateName = false;
4310                if (cur != null) {
4311                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4312                    final boolean targetIsInstantApp =
4313                            ps != null && ps.getInstantApp(callingUserId);
4314                    translateName = !targetIsInstantApp
4315                            || canViewInstantApps
4316                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4317                                    UserHandle.getAppId(callingUid), ps.appId);
4318                }
4319                out[i] = translateName ? cur : names[i];
4320            }
4321        }
4322        return out;
4323    }
4324
4325    @Override
4326    public int getPackageUid(String packageName, int flags, int userId) {
4327        if (!sUserManager.exists(userId)) return -1;
4328        final int callingUid = Binder.getCallingUid();
4329        flags = updateFlagsForPackage(flags, userId, packageName);
4330        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4331                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4332
4333        // reader
4334        synchronized (mPackages) {
4335            final PackageParser.Package p = mPackages.get(packageName);
4336            if (p != null && p.isMatch(flags)) {
4337                PackageSetting ps = (PackageSetting) p.mExtras;
4338                if (filterAppAccessLPr(ps, callingUid, userId)) {
4339                    return -1;
4340                }
4341                return UserHandle.getUid(userId, p.applicationInfo.uid);
4342            }
4343            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4344                final PackageSetting ps = mSettings.mPackages.get(packageName);
4345                if (ps != null && ps.isMatch(flags)
4346                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4347                    return UserHandle.getUid(userId, ps.appId);
4348                }
4349            }
4350        }
4351
4352        return -1;
4353    }
4354
4355    @Override
4356    public int[] getPackageGids(String packageName, int flags, int userId) {
4357        if (!sUserManager.exists(userId)) return null;
4358        final int callingUid = Binder.getCallingUid();
4359        flags = updateFlagsForPackage(flags, userId, packageName);
4360        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4361                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4362
4363        // reader
4364        synchronized (mPackages) {
4365            final PackageParser.Package p = mPackages.get(packageName);
4366            if (p != null && p.isMatch(flags)) {
4367                PackageSetting ps = (PackageSetting) p.mExtras;
4368                if (filterAppAccessLPr(ps, callingUid, userId)) {
4369                    return null;
4370                }
4371                // TODO: Shouldn't this be checking for package installed state for userId and
4372                // return null?
4373                return ps.getPermissionsState().computeGids(userId);
4374            }
4375            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4376                final PackageSetting ps = mSettings.mPackages.get(packageName);
4377                if (ps != null && ps.isMatch(flags)
4378                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4379                    return ps.getPermissionsState().computeGids(userId);
4380                }
4381            }
4382        }
4383
4384        return null;
4385    }
4386
4387    @Override
4388    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4389        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4390    }
4391
4392    @Override
4393    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4394            int flags) {
4395        final List<PermissionInfo> permissionList =
4396                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4397        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4398    }
4399
4400    @Override
4401    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4402        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4403    }
4404
4405    @Override
4406    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4407        final List<PermissionGroupInfo> permissionList =
4408                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4409        return (permissionList == null)
4410                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4411    }
4412
4413    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4414            int filterCallingUid, int userId) {
4415        if (!sUserManager.exists(userId)) return null;
4416        PackageSetting ps = mSettings.mPackages.get(packageName);
4417        if (ps != null) {
4418            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4419                return null;
4420            }
4421            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4422                return null;
4423            }
4424            if (ps.pkg == null) {
4425                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4426                if (pInfo != null) {
4427                    return pInfo.applicationInfo;
4428                }
4429                return null;
4430            }
4431            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4432                    ps.readUserState(userId), userId);
4433            if (ai != null) {
4434                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4435            }
4436            return ai;
4437        }
4438        return null;
4439    }
4440
4441    @Override
4442    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4443        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4444    }
4445
4446    /**
4447     * Important: The provided filterCallingUid is used exclusively to filter out applications
4448     * that can be seen based on user state. It's typically the original caller uid prior
4449     * to clearing. Because it can only be provided by trusted code, it's value can be
4450     * trusted and will be used as-is; unlike userId which will be validated by this method.
4451     */
4452    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4453            int filterCallingUid, int userId) {
4454        if (!sUserManager.exists(userId)) return null;
4455        flags = updateFlagsForApplication(flags, userId, packageName);
4456        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4457                false /* requireFullPermission */, false /* checkShell */, "get application info");
4458
4459        // writer
4460        synchronized (mPackages) {
4461            // Normalize package name to handle renamed packages and static libs
4462            packageName = resolveInternalPackageNameLPr(packageName,
4463                    PackageManager.VERSION_CODE_HIGHEST);
4464
4465            PackageParser.Package p = mPackages.get(packageName);
4466            if (DEBUG_PACKAGE_INFO) Log.v(
4467                    TAG, "getApplicationInfo " + packageName
4468                    + ": " + p);
4469            if (p != null) {
4470                PackageSetting ps = mSettings.mPackages.get(packageName);
4471                if (ps == null) return null;
4472                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4473                    return null;
4474                }
4475                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4476                    return null;
4477                }
4478                // Note: isEnabledLP() does not apply here - always return info
4479                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4480                        p, flags, ps.readUserState(userId), userId);
4481                if (ai != null) {
4482                    ai.packageName = resolveExternalPackageNameLPr(p);
4483                }
4484                return ai;
4485            }
4486            if ("android".equals(packageName)||"system".equals(packageName)) {
4487                return mAndroidApplication;
4488            }
4489            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4490                // Already generates the external package name
4491                return generateApplicationInfoFromSettingsLPw(packageName,
4492                        flags, filterCallingUid, userId);
4493            }
4494        }
4495        return null;
4496    }
4497
4498    private String normalizePackageNameLPr(String packageName) {
4499        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4500        return normalizedPackageName != null ? normalizedPackageName : packageName;
4501    }
4502
4503    @Override
4504    public void deletePreloadsFileCache() {
4505        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4506            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4507        }
4508        File dir = Environment.getDataPreloadsFileCacheDirectory();
4509        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4510        FileUtils.deleteContents(dir);
4511    }
4512
4513    @Override
4514    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4515            final int storageFlags, final IPackageDataObserver observer) {
4516        mContext.enforceCallingOrSelfPermission(
4517                android.Manifest.permission.CLEAR_APP_CACHE, null);
4518        mHandler.post(() -> {
4519            boolean success = false;
4520            try {
4521                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4522                success = true;
4523            } catch (IOException e) {
4524                Slog.w(TAG, e);
4525            }
4526            if (observer != null) {
4527                try {
4528                    observer.onRemoveCompleted(null, success);
4529                } catch (RemoteException e) {
4530                    Slog.w(TAG, e);
4531                }
4532            }
4533        });
4534    }
4535
4536    @Override
4537    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4538            final int storageFlags, final IntentSender pi) {
4539        mContext.enforceCallingOrSelfPermission(
4540                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4541        mHandler.post(() -> {
4542            boolean success = false;
4543            try {
4544                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4545                success = true;
4546            } catch (IOException e) {
4547                Slog.w(TAG, e);
4548            }
4549            if (pi != null) {
4550                try {
4551                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4552                } catch (SendIntentException e) {
4553                    Slog.w(TAG, e);
4554                }
4555            }
4556        });
4557    }
4558
4559    /**
4560     * Blocking call to clear various types of cached data across the system
4561     * until the requested bytes are available.
4562     */
4563    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4564        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4565        final File file = storage.findPathForUuid(volumeUuid);
4566        if (file.getUsableSpace() >= bytes) return;
4567
4568        if (ENABLE_FREE_CACHE_V2) {
4569            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4570                    volumeUuid);
4571            final boolean aggressive = (storageFlags
4572                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4573            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4574
4575            // 1. Pre-flight to determine if we have any chance to succeed
4576            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4577            if (internalVolume && (aggressive || SystemProperties
4578                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4579                deletePreloadsFileCache();
4580                if (file.getUsableSpace() >= bytes) return;
4581            }
4582
4583            // 3. Consider parsed APK data (aggressive only)
4584            if (internalVolume && aggressive) {
4585                FileUtils.deleteContents(mCacheDir);
4586                if (file.getUsableSpace() >= bytes) return;
4587            }
4588
4589            // 4. Consider cached app data (above quotas)
4590            try {
4591                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4592                        Installer.FLAG_FREE_CACHE_V2);
4593            } catch (InstallerException ignored) {
4594            }
4595            if (file.getUsableSpace() >= bytes) return;
4596
4597            // 5. Consider shared libraries with refcount=0 and age>min cache period
4598            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4599                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4600                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4601                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4602                return;
4603            }
4604
4605            // 6. Consider dexopt output (aggressive only)
4606            // TODO: Implement
4607
4608            // 7. Consider installed instant apps unused longer than min cache period
4609            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4610                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4611                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4612                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4613                return;
4614            }
4615
4616            // 8. Consider cached app data (below quotas)
4617            try {
4618                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4619                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4620            } catch (InstallerException ignored) {
4621            }
4622            if (file.getUsableSpace() >= bytes) return;
4623
4624            // 9. Consider DropBox entries
4625            // TODO: Implement
4626
4627            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4628            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4629                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4630                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4631                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4632                return;
4633            }
4634        } else {
4635            try {
4636                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4637            } catch (InstallerException ignored) {
4638            }
4639            if (file.getUsableSpace() >= bytes) return;
4640        }
4641
4642        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4643    }
4644
4645    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4646            throws IOException {
4647        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4648        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4649
4650        List<VersionedPackage> packagesToDelete = null;
4651        final long now = System.currentTimeMillis();
4652
4653        synchronized (mPackages) {
4654            final int[] allUsers = sUserManager.getUserIds();
4655            final int libCount = mSharedLibraries.size();
4656            for (int i = 0; i < libCount; i++) {
4657                final LongSparseArray<SharedLibraryEntry> versionedLib
4658                        = mSharedLibraries.valueAt(i);
4659                if (versionedLib == null) {
4660                    continue;
4661                }
4662                final int versionCount = versionedLib.size();
4663                for (int j = 0; j < versionCount; j++) {
4664                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4665                    // Skip packages that are not static shared libs.
4666                    if (!libInfo.isStatic()) {
4667                        break;
4668                    }
4669                    // Important: We skip static shared libs used for some user since
4670                    // in such a case we need to keep the APK on the device. The check for
4671                    // a lib being used for any user is performed by the uninstall call.
4672                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4673                    // Resolve the package name - we use synthetic package names internally
4674                    final String internalPackageName = resolveInternalPackageNameLPr(
4675                            declaringPackage.getPackageName(),
4676                            declaringPackage.getLongVersionCode());
4677                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4678                    // Skip unused static shared libs cached less than the min period
4679                    // to prevent pruning a lib needed by a subsequently installed package.
4680                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4681                        continue;
4682                    }
4683                    if (packagesToDelete == null) {
4684                        packagesToDelete = new ArrayList<>();
4685                    }
4686                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4687                            declaringPackage.getLongVersionCode()));
4688                }
4689            }
4690        }
4691
4692        if (packagesToDelete != null) {
4693            final int packageCount = packagesToDelete.size();
4694            for (int i = 0; i < packageCount; i++) {
4695                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4696                // Delete the package synchronously (will fail of the lib used for any user).
4697                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4698                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4699                                == PackageManager.DELETE_SUCCEEDED) {
4700                    if (volume.getUsableSpace() >= neededSpace) {
4701                        return true;
4702                    }
4703                }
4704            }
4705        }
4706
4707        return false;
4708    }
4709
4710    /**
4711     * Update given flags based on encryption status of current user.
4712     */
4713    private int updateFlags(int flags, int userId) {
4714        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4715                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4716            // Caller expressed an explicit opinion about what encryption
4717            // aware/unaware components they want to see, so fall through and
4718            // give them what they want
4719        } else {
4720            // Caller expressed no opinion, so match based on user state
4721            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4722                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4723            } else {
4724                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4725            }
4726        }
4727        return flags;
4728    }
4729
4730    private UserManagerInternal getUserManagerInternal() {
4731        if (mUserManagerInternal == null) {
4732            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4733        }
4734        return mUserManagerInternal;
4735    }
4736
4737    private ActivityManagerInternal getActivityManagerInternal() {
4738        if (mActivityManagerInternal == null) {
4739            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4740        }
4741        return mActivityManagerInternal;
4742    }
4743
4744
4745    private DeviceIdleController.LocalService getDeviceIdleController() {
4746        if (mDeviceIdleController == null) {
4747            mDeviceIdleController =
4748                    LocalServices.getService(DeviceIdleController.LocalService.class);
4749        }
4750        return mDeviceIdleController;
4751    }
4752
4753    /**
4754     * Update given flags when being used to request {@link PackageInfo}.
4755     */
4756    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4757        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4758        boolean triaged = true;
4759        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4760                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4761            // Caller is asking for component details, so they'd better be
4762            // asking for specific encryption matching behavior, or be triaged
4763            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4764                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4765                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4766                triaged = false;
4767            }
4768        }
4769        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4770                | PackageManager.MATCH_SYSTEM_ONLY
4771                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4772            triaged = false;
4773        }
4774        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4775            mPermissionManager.enforceCrossUserPermission(
4776                    Binder.getCallingUid(), userId, false, false,
4777                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4778                    + Debug.getCallers(5));
4779        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4780                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4781            // If the caller wants all packages and has a restricted profile associated with it,
4782            // then match all users. This is to make sure that launchers that need to access work
4783            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4784            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4785            flags |= PackageManager.MATCH_ANY_USER;
4786        }
4787        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4788            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4789                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4790        }
4791        return updateFlags(flags, userId);
4792    }
4793
4794    /**
4795     * Update given flags when being used to request {@link ApplicationInfo}.
4796     */
4797    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4798        return updateFlagsForPackage(flags, userId, cookie);
4799    }
4800
4801    /**
4802     * Update given flags when being used to request {@link ComponentInfo}.
4803     */
4804    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4805        if (cookie instanceof Intent) {
4806            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4807                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4808            }
4809        }
4810
4811        boolean triaged = true;
4812        // Caller is asking for component details, so they'd better be
4813        // asking for specific encryption matching behavior, or be triaged
4814        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4815                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4816                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4817            triaged = false;
4818        }
4819        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4820            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4821                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4822        }
4823
4824        return updateFlags(flags, userId);
4825    }
4826
4827    /**
4828     * Update given intent when being used to request {@link ResolveInfo}.
4829     */
4830    private Intent updateIntentForResolve(Intent intent) {
4831        if (intent.getSelector() != null) {
4832            intent = intent.getSelector();
4833        }
4834        if (DEBUG_PREFERRED) {
4835            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4836        }
4837        return intent;
4838    }
4839
4840    /**
4841     * Update given flags when being used to request {@link ResolveInfo}.
4842     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4843     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4844     * flag set. However, this flag is only honoured in three circumstances:
4845     * <ul>
4846     * <li>when called from a system process</li>
4847     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4848     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4849     * action and a {@code android.intent.category.BROWSABLE} category</li>
4850     * </ul>
4851     */
4852    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4853        return updateFlagsForResolve(flags, userId, intent, callingUid,
4854                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4855    }
4856    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4857            boolean wantInstantApps) {
4858        return updateFlagsForResolve(flags, userId, intent, callingUid,
4859                wantInstantApps, false /*onlyExposedExplicitly*/);
4860    }
4861    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4862            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4863        // Safe mode means we shouldn't match any third-party components
4864        if (mSafeMode) {
4865            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4866        }
4867        if (getInstantAppPackageName(callingUid) != null) {
4868            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4869            if (onlyExposedExplicitly) {
4870                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4871            }
4872            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4873            flags |= PackageManager.MATCH_INSTANT;
4874        } else {
4875            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4876            final boolean allowMatchInstant = wantInstantApps
4877                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4878            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4879                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4880            if (!allowMatchInstant) {
4881                flags &= ~PackageManager.MATCH_INSTANT;
4882            }
4883        }
4884        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4885    }
4886
4887    @Override
4888    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4889        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4890    }
4891
4892    /**
4893     * Important: The provided filterCallingUid is used exclusively to filter out activities
4894     * that can be seen based on user state. It's typically the original caller uid prior
4895     * to clearing. Because it can only be provided by trusted code, it's value can be
4896     * trusted and will be used as-is; unlike userId which will be validated by this method.
4897     */
4898    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4899            int filterCallingUid, int userId) {
4900        if (!sUserManager.exists(userId)) return null;
4901        flags = updateFlagsForComponent(flags, userId, component);
4902
4903        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4904            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4905                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4906        }
4907
4908        synchronized (mPackages) {
4909            PackageParser.Activity a = mActivities.mActivities.get(component);
4910
4911            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4912            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4913                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4914                if (ps == null) return null;
4915                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4916                    return null;
4917                }
4918                return PackageParser.generateActivityInfo(
4919                        a, flags, ps.readUserState(userId), userId);
4920            }
4921            if (mResolveComponentName.equals(component)) {
4922                return PackageParser.generateActivityInfo(
4923                        mResolveActivity, flags, new PackageUserState(), userId);
4924            }
4925        }
4926        return null;
4927    }
4928
4929    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4930        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4931            return false;
4932        }
4933        final long token = Binder.clearCallingIdentity();
4934        try {
4935            final int callingUserId = UserHandle.getUserId(callingUid);
4936            if (ActivityManager.getCurrentUser() != callingUserId) {
4937                return false;
4938            }
4939            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4940        } finally {
4941            Binder.restoreCallingIdentity(token);
4942        }
4943    }
4944
4945    @Override
4946    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4947            String resolvedType) {
4948        synchronized (mPackages) {
4949            if (component.equals(mResolveComponentName)) {
4950                // The resolver supports EVERYTHING!
4951                return true;
4952            }
4953            final int callingUid = Binder.getCallingUid();
4954            final int callingUserId = UserHandle.getUserId(callingUid);
4955            PackageParser.Activity a = mActivities.mActivities.get(component);
4956            if (a == null) {
4957                return false;
4958            }
4959            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4960            if (ps == null) {
4961                return false;
4962            }
4963            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4964                return false;
4965            }
4966            for (int i=0; i<a.intents.size(); i++) {
4967                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4968                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4969                    return true;
4970                }
4971            }
4972            return false;
4973        }
4974    }
4975
4976    @Override
4977    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4978        if (!sUserManager.exists(userId)) return null;
4979        final int callingUid = Binder.getCallingUid();
4980        flags = updateFlagsForComponent(flags, userId, component);
4981        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4982                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4983        synchronized (mPackages) {
4984            PackageParser.Activity a = mReceivers.mActivities.get(component);
4985            if (DEBUG_PACKAGE_INFO) Log.v(
4986                TAG, "getReceiverInfo " + component + ": " + a);
4987            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4988                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4989                if (ps == null) return null;
4990                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4991                    return null;
4992                }
4993                return PackageParser.generateActivityInfo(
4994                        a, flags, ps.readUserState(userId), userId);
4995            }
4996        }
4997        return null;
4998    }
4999
5000    @Override
5001    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
5002            int flags, int userId) {
5003        if (!sUserManager.exists(userId)) return null;
5004        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
5005        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5006            return null;
5007        }
5008
5009        flags = updateFlagsForPackage(flags, userId, null);
5010
5011        final boolean canSeeStaticLibraries =
5012                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
5013                        == PERMISSION_GRANTED
5014                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
5015                        == PERMISSION_GRANTED
5016                || canRequestPackageInstallsInternal(packageName,
5017                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
5018                        false  /* throwIfPermNotDeclared*/)
5019                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
5020                        == PERMISSION_GRANTED;
5021
5022        synchronized (mPackages) {
5023            List<SharedLibraryInfo> result = null;
5024
5025            final int libCount = mSharedLibraries.size();
5026            for (int i = 0; i < libCount; i++) {
5027                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5028                if (versionedLib == null) {
5029                    continue;
5030                }
5031
5032                final int versionCount = versionedLib.size();
5033                for (int j = 0; j < versionCount; j++) {
5034                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5035                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5036                        break;
5037                    }
5038                    final long identity = Binder.clearCallingIdentity();
5039                    try {
5040                        PackageInfo packageInfo = getPackageInfoVersioned(
5041                                libInfo.getDeclaringPackage(), flags
5042                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5043                        if (packageInfo == null) {
5044                            continue;
5045                        }
5046                    } finally {
5047                        Binder.restoreCallingIdentity(identity);
5048                    }
5049
5050                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5051                            libInfo.getLongVersion(), libInfo.getType(),
5052                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5053                            flags, userId));
5054
5055                    if (result == null) {
5056                        result = new ArrayList<>();
5057                    }
5058                    result.add(resLibInfo);
5059                }
5060            }
5061
5062            return result != null ? new ParceledListSlice<>(result) : null;
5063        }
5064    }
5065
5066    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5067            SharedLibraryInfo libInfo, int flags, int userId) {
5068        List<VersionedPackage> versionedPackages = null;
5069        final int packageCount = mSettings.mPackages.size();
5070        for (int i = 0; i < packageCount; i++) {
5071            PackageSetting ps = mSettings.mPackages.valueAt(i);
5072
5073            if (ps == null) {
5074                continue;
5075            }
5076
5077            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5078                continue;
5079            }
5080
5081            final String libName = libInfo.getName();
5082            if (libInfo.isStatic()) {
5083                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5084                if (libIdx < 0) {
5085                    continue;
5086                }
5087                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
5088                    continue;
5089                }
5090                if (versionedPackages == null) {
5091                    versionedPackages = new ArrayList<>();
5092                }
5093                // If the dependent is a static shared lib, use the public package name
5094                String dependentPackageName = ps.name;
5095                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5096                    dependentPackageName = ps.pkg.manifestPackageName;
5097                }
5098                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5099            } else if (ps.pkg != null) {
5100                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5101                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5102                    if (versionedPackages == null) {
5103                        versionedPackages = new ArrayList<>();
5104                    }
5105                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5106                }
5107            }
5108        }
5109
5110        return versionedPackages;
5111    }
5112
5113    @Override
5114    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5115        if (!sUserManager.exists(userId)) return null;
5116        final int callingUid = Binder.getCallingUid();
5117        flags = updateFlagsForComponent(flags, userId, component);
5118        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5119                false /* requireFullPermission */, false /* checkShell */, "get service info");
5120        synchronized (mPackages) {
5121            PackageParser.Service s = mServices.mServices.get(component);
5122            if (DEBUG_PACKAGE_INFO) Log.v(
5123                TAG, "getServiceInfo " + component + ": " + s);
5124            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5125                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5126                if (ps == null) return null;
5127                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5128                    return null;
5129                }
5130                return PackageParser.generateServiceInfo(
5131                        s, flags, ps.readUserState(userId), userId);
5132            }
5133        }
5134        return null;
5135    }
5136
5137    @Override
5138    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5139        if (!sUserManager.exists(userId)) return null;
5140        final int callingUid = Binder.getCallingUid();
5141        flags = updateFlagsForComponent(flags, userId, component);
5142        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5143                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5144        synchronized (mPackages) {
5145            PackageParser.Provider p = mProviders.mProviders.get(component);
5146            if (DEBUG_PACKAGE_INFO) Log.v(
5147                TAG, "getProviderInfo " + component + ": " + p);
5148            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5149                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5150                if (ps == null) return null;
5151                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5152                    return null;
5153                }
5154                return PackageParser.generateProviderInfo(
5155                        p, flags, ps.readUserState(userId), userId);
5156            }
5157        }
5158        return null;
5159    }
5160
5161    @Override
5162    public String[] getSystemSharedLibraryNames() {
5163        // allow instant applications
5164        synchronized (mPackages) {
5165            Set<String> libs = null;
5166            final int libCount = mSharedLibraries.size();
5167            for (int i = 0; i < libCount; i++) {
5168                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5169                if (versionedLib == null) {
5170                    continue;
5171                }
5172                final int versionCount = versionedLib.size();
5173                for (int j = 0; j < versionCount; j++) {
5174                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5175                    if (!libEntry.info.isStatic()) {
5176                        if (libs == null) {
5177                            libs = new ArraySet<>();
5178                        }
5179                        libs.add(libEntry.info.getName());
5180                        break;
5181                    }
5182                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5183                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5184                            UserHandle.getUserId(Binder.getCallingUid()),
5185                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5186                        if (libs == null) {
5187                            libs = new ArraySet<>();
5188                        }
5189                        libs.add(libEntry.info.getName());
5190                        break;
5191                    }
5192                }
5193            }
5194
5195            if (libs != null) {
5196                String[] libsArray = new String[libs.size()];
5197                libs.toArray(libsArray);
5198                return libsArray;
5199            }
5200
5201            return null;
5202        }
5203    }
5204
5205    @Override
5206    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5207        // allow instant applications
5208        synchronized (mPackages) {
5209            return mServicesSystemSharedLibraryPackageName;
5210        }
5211    }
5212
5213    @Override
5214    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5215        // allow instant applications
5216        synchronized (mPackages) {
5217            return mSharedSystemSharedLibraryPackageName;
5218        }
5219    }
5220
5221    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5222        for (int i = userList.length - 1; i >= 0; --i) {
5223            final int userId = userList[i];
5224            // don't add instant app to the list of updates
5225            if (pkgSetting.getInstantApp(userId)) {
5226                continue;
5227            }
5228            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5229            if (changedPackages == null) {
5230                changedPackages = new SparseArray<>();
5231                mChangedPackages.put(userId, changedPackages);
5232            }
5233            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5234            if (sequenceNumbers == null) {
5235                sequenceNumbers = new HashMap<>();
5236                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5237            }
5238            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5239            if (sequenceNumber != null) {
5240                changedPackages.remove(sequenceNumber);
5241            }
5242            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5243            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5244        }
5245        mChangedPackagesSequenceNumber++;
5246    }
5247
5248    @Override
5249    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5250        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5251            return null;
5252        }
5253        synchronized (mPackages) {
5254            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5255                return null;
5256            }
5257            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5258            if (changedPackages == null) {
5259                return null;
5260            }
5261            final List<String> packageNames =
5262                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5263            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5264                final String packageName = changedPackages.get(i);
5265                if (packageName != null) {
5266                    packageNames.add(packageName);
5267                }
5268            }
5269            return packageNames.isEmpty()
5270                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5271        }
5272    }
5273
5274    @Override
5275    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5276        // allow instant applications
5277        ArrayList<FeatureInfo> res;
5278        synchronized (mAvailableFeatures) {
5279            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5280            res.addAll(mAvailableFeatures.values());
5281        }
5282        final FeatureInfo fi = new FeatureInfo();
5283        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5284                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5285        res.add(fi);
5286
5287        return new ParceledListSlice<>(res);
5288    }
5289
5290    @Override
5291    public boolean hasSystemFeature(String name, int version) {
5292        // allow instant applications
5293        synchronized (mAvailableFeatures) {
5294            final FeatureInfo feat = mAvailableFeatures.get(name);
5295            if (feat == null) {
5296                return false;
5297            } else {
5298                return feat.version >= version;
5299            }
5300        }
5301    }
5302
5303    @Override
5304    public int checkPermission(String permName, String pkgName, int userId) {
5305        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5306    }
5307
5308    @Override
5309    public int checkUidPermission(String permName, int uid) {
5310        synchronized (mPackages) {
5311            final String[] packageNames = getPackagesForUid(uid);
5312            final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0)
5313                    ? mPackages.get(packageNames[0])
5314                    : null;
5315            return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid());
5316        }
5317    }
5318
5319    @Override
5320    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5321        if (UserHandle.getCallingUserId() != userId) {
5322            mContext.enforceCallingPermission(
5323                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5324                    "isPermissionRevokedByPolicy for user " + userId);
5325        }
5326
5327        if (checkPermission(permission, packageName, userId)
5328                == PackageManager.PERMISSION_GRANTED) {
5329            return false;
5330        }
5331
5332        final int callingUid = Binder.getCallingUid();
5333        if (getInstantAppPackageName(callingUid) != null) {
5334            if (!isCallerSameApp(packageName, callingUid)) {
5335                return false;
5336            }
5337        } else {
5338            if (isInstantApp(packageName, userId)) {
5339                return false;
5340            }
5341        }
5342
5343        final long identity = Binder.clearCallingIdentity();
5344        try {
5345            final int flags = getPermissionFlags(permission, packageName, userId);
5346            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5347        } finally {
5348            Binder.restoreCallingIdentity(identity);
5349        }
5350    }
5351
5352    @Override
5353    public String getPermissionControllerPackageName() {
5354        synchronized (mPackages) {
5355            return mRequiredInstallerPackage;
5356        }
5357    }
5358
5359    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5360        return mPermissionManager.addDynamicPermission(
5361                info, async, getCallingUid(), new PermissionCallback() {
5362                    @Override
5363                    public void onPermissionChanged() {
5364                        if (!async) {
5365                            mSettings.writeLPr();
5366                        } else {
5367                            scheduleWriteSettingsLocked();
5368                        }
5369                    }
5370                });
5371    }
5372
5373    @Override
5374    public boolean addPermission(PermissionInfo info) {
5375        synchronized (mPackages) {
5376            return addDynamicPermission(info, false);
5377        }
5378    }
5379
5380    @Override
5381    public boolean addPermissionAsync(PermissionInfo info) {
5382        synchronized (mPackages) {
5383            return addDynamicPermission(info, true);
5384        }
5385    }
5386
5387    @Override
5388    public void removePermission(String permName) {
5389        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5390    }
5391
5392    @Override
5393    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5394        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5395                getCallingUid(), userId, mPermissionCallback);
5396    }
5397
5398    @Override
5399    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5400        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5401                getCallingUid(), userId, mPermissionCallback);
5402    }
5403
5404    @Override
5405    public void resetRuntimePermissions() {
5406        mContext.enforceCallingOrSelfPermission(
5407                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5408                "revokeRuntimePermission");
5409
5410        int callingUid = Binder.getCallingUid();
5411        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5412            mContext.enforceCallingOrSelfPermission(
5413                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5414                    "resetRuntimePermissions");
5415        }
5416
5417        synchronized (mPackages) {
5418            mPermissionManager.updateAllPermissions(
5419                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5420                    mPermissionCallback);
5421            for (int userId : UserManagerService.getInstance().getUserIds()) {
5422                final int packageCount = mPackages.size();
5423                for (int i = 0; i < packageCount; i++) {
5424                    PackageParser.Package pkg = mPackages.valueAt(i);
5425                    if (!(pkg.mExtras instanceof PackageSetting)) {
5426                        continue;
5427                    }
5428                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5429                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5430                }
5431            }
5432        }
5433    }
5434
5435    @Override
5436    public int getPermissionFlags(String permName, String packageName, int userId) {
5437        return mPermissionManager.getPermissionFlags(
5438                permName, packageName, getCallingUid(), userId);
5439    }
5440
5441    @Override
5442    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5443            int flagValues, int userId) {
5444        mPermissionManager.updatePermissionFlags(
5445                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5446                mPermissionCallback);
5447    }
5448
5449    /**
5450     * Update the permission flags for all packages and runtime permissions of a user in order
5451     * to allow device or profile owner to remove POLICY_FIXED.
5452     */
5453    @Override
5454    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5455        synchronized (mPackages) {
5456            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5457                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5458                    mPermissionCallback);
5459            if (changed) {
5460                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5461            }
5462        }
5463    }
5464
5465    @Override
5466    public boolean shouldShowRequestPermissionRationale(String permissionName,
5467            String packageName, int userId) {
5468        if (UserHandle.getCallingUserId() != userId) {
5469            mContext.enforceCallingPermission(
5470                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5471                    "canShowRequestPermissionRationale for user " + userId);
5472        }
5473
5474        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5475        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5476            return false;
5477        }
5478
5479        if (checkPermission(permissionName, packageName, userId)
5480                == PackageManager.PERMISSION_GRANTED) {
5481            return false;
5482        }
5483
5484        final int flags;
5485
5486        final long identity = Binder.clearCallingIdentity();
5487        try {
5488            flags = getPermissionFlags(permissionName,
5489                    packageName, userId);
5490        } finally {
5491            Binder.restoreCallingIdentity(identity);
5492        }
5493
5494        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5495                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5496                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5497
5498        if ((flags & fixedFlags) != 0) {
5499            return false;
5500        }
5501
5502        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5503    }
5504
5505    @Override
5506    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5507        mContext.enforceCallingOrSelfPermission(
5508                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5509                "addOnPermissionsChangeListener");
5510
5511        synchronized (mPackages) {
5512            mOnPermissionChangeListeners.addListenerLocked(listener);
5513        }
5514    }
5515
5516    @Override
5517    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5518        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5519            throw new SecurityException("Instant applications don't have access to this method");
5520        }
5521        synchronized (mPackages) {
5522            mOnPermissionChangeListeners.removeListenerLocked(listener);
5523        }
5524    }
5525
5526    @Override
5527    public boolean isProtectedBroadcast(String actionName) {
5528        // allow instant applications
5529        synchronized (mProtectedBroadcasts) {
5530            if (mProtectedBroadcasts.contains(actionName)) {
5531                return true;
5532            } else if (actionName != null) {
5533                // TODO: remove these terrible hacks
5534                if (actionName.startsWith("android.net.netmon.lingerExpired")
5535                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5536                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5537                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5538                    return true;
5539                }
5540            }
5541        }
5542        return false;
5543    }
5544
5545    @Override
5546    public int checkSignatures(String pkg1, String pkg2) {
5547        synchronized (mPackages) {
5548            final PackageParser.Package p1 = mPackages.get(pkg1);
5549            final PackageParser.Package p2 = mPackages.get(pkg2);
5550            if (p1 == null || p1.mExtras == null
5551                    || p2 == null || p2.mExtras == null) {
5552                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5553            }
5554            final int callingUid = Binder.getCallingUid();
5555            final int callingUserId = UserHandle.getUserId(callingUid);
5556            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5557            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5558            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5559                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5560                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5561            }
5562            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5563        }
5564    }
5565
5566    @Override
5567    public int checkUidSignatures(int uid1, int uid2) {
5568        final int callingUid = Binder.getCallingUid();
5569        final int callingUserId = UserHandle.getUserId(callingUid);
5570        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5571        // Map to base uids.
5572        uid1 = UserHandle.getAppId(uid1);
5573        uid2 = UserHandle.getAppId(uid2);
5574        // reader
5575        synchronized (mPackages) {
5576            Signature[] s1;
5577            Signature[] s2;
5578            Object obj = mSettings.getUserIdLPr(uid1);
5579            if (obj != null) {
5580                if (obj instanceof SharedUserSetting) {
5581                    if (isCallerInstantApp) {
5582                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5583                    }
5584                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5585                } else if (obj instanceof PackageSetting) {
5586                    final PackageSetting ps = (PackageSetting) obj;
5587                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5588                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5589                    }
5590                    s1 = ps.signatures.mSigningDetails.signatures;
5591                } else {
5592                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5593                }
5594            } else {
5595                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5596            }
5597            obj = mSettings.getUserIdLPr(uid2);
5598            if (obj != null) {
5599                if (obj instanceof SharedUserSetting) {
5600                    if (isCallerInstantApp) {
5601                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5602                    }
5603                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5604                } else if (obj instanceof PackageSetting) {
5605                    final PackageSetting ps = (PackageSetting) obj;
5606                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5607                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5608                    }
5609                    s2 = ps.signatures.mSigningDetails.signatures;
5610                } else {
5611                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5612                }
5613            } else {
5614                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5615            }
5616            return compareSignatures(s1, s2);
5617        }
5618    }
5619
5620    @Override
5621    public boolean hasSigningCertificate(
5622            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5623
5624        synchronized (mPackages) {
5625            final PackageParser.Package p = mPackages.get(packageName);
5626            if (p == null || p.mExtras == null) {
5627                return false;
5628            }
5629            final int callingUid = Binder.getCallingUid();
5630            final int callingUserId = UserHandle.getUserId(callingUid);
5631            final PackageSetting ps = (PackageSetting) p.mExtras;
5632            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5633                return false;
5634            }
5635            switch (type) {
5636                case CERT_INPUT_RAW_X509:
5637                    return p.mSigningDetails.hasCertificate(certificate);
5638                case CERT_INPUT_SHA256:
5639                    return p.mSigningDetails.hasSha256Certificate(certificate);
5640                default:
5641                    return false;
5642            }
5643        }
5644    }
5645
5646    @Override
5647    public boolean hasUidSigningCertificate(
5648            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5649        final int callingUid = Binder.getCallingUid();
5650        final int callingUserId = UserHandle.getUserId(callingUid);
5651        // Map to base uids.
5652        uid = UserHandle.getAppId(uid);
5653        // reader
5654        synchronized (mPackages) {
5655            final PackageParser.SigningDetails signingDetails;
5656            final Object obj = mSettings.getUserIdLPr(uid);
5657            if (obj != null) {
5658                if (obj instanceof SharedUserSetting) {
5659                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5660                    if (isCallerInstantApp) {
5661                        return false;
5662                    }
5663                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5664                } else if (obj instanceof PackageSetting) {
5665                    final PackageSetting ps = (PackageSetting) obj;
5666                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5667                        return false;
5668                    }
5669                    signingDetails = ps.signatures.mSigningDetails;
5670                } else {
5671                    return false;
5672                }
5673            } else {
5674                return false;
5675            }
5676            switch (type) {
5677                case CERT_INPUT_RAW_X509:
5678                    return signingDetails.hasCertificate(certificate);
5679                case CERT_INPUT_SHA256:
5680                    return signingDetails.hasSha256Certificate(certificate);
5681                default:
5682                    return false;
5683            }
5684        }
5685    }
5686
5687    /**
5688     * This method should typically only be used when granting or revoking
5689     * permissions, since the app may immediately restart after this call.
5690     * <p>
5691     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5692     * guard your work against the app being relaunched.
5693     */
5694    private void killUid(int appId, int userId, String reason) {
5695        final long identity = Binder.clearCallingIdentity();
5696        try {
5697            IActivityManager am = ActivityManager.getService();
5698            if (am != null) {
5699                try {
5700                    am.killUid(appId, userId, reason);
5701                } catch (RemoteException e) {
5702                    /* ignore - same process */
5703                }
5704            }
5705        } finally {
5706            Binder.restoreCallingIdentity(identity);
5707        }
5708    }
5709
5710    /**
5711     * If the database version for this type of package (internal storage or
5712     * external storage) is less than the version where package signatures
5713     * were updated, return true.
5714     */
5715    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5716        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5717        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5718    }
5719
5720    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5721        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5722        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5723    }
5724
5725    @Override
5726    public List<String> getAllPackages() {
5727        final int callingUid = Binder.getCallingUid();
5728        final int callingUserId = UserHandle.getUserId(callingUid);
5729        synchronized (mPackages) {
5730            if (canViewInstantApps(callingUid, callingUserId)) {
5731                return new ArrayList<String>(mPackages.keySet());
5732            }
5733            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5734            final List<String> result = new ArrayList<>();
5735            if (instantAppPkgName != null) {
5736                // caller is an instant application; filter unexposed applications
5737                for (PackageParser.Package pkg : mPackages.values()) {
5738                    if (!pkg.visibleToInstantApps) {
5739                        continue;
5740                    }
5741                    result.add(pkg.packageName);
5742                }
5743            } else {
5744                // caller is a normal application; filter instant applications
5745                for (PackageParser.Package pkg : mPackages.values()) {
5746                    final PackageSetting ps =
5747                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5748                    if (ps != null
5749                            && ps.getInstantApp(callingUserId)
5750                            && !mInstantAppRegistry.isInstantAccessGranted(
5751                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5752                        continue;
5753                    }
5754                    result.add(pkg.packageName);
5755                }
5756            }
5757            return result;
5758        }
5759    }
5760
5761    @Override
5762    public String[] getPackagesForUid(int uid) {
5763        final int callingUid = Binder.getCallingUid();
5764        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5765        final int userId = UserHandle.getUserId(uid);
5766        uid = UserHandle.getAppId(uid);
5767        // reader
5768        synchronized (mPackages) {
5769            Object obj = mSettings.getUserIdLPr(uid);
5770            if (obj instanceof SharedUserSetting) {
5771                if (isCallerInstantApp) {
5772                    return null;
5773                }
5774                final SharedUserSetting sus = (SharedUserSetting) obj;
5775                final int N = sus.packages.size();
5776                String[] res = new String[N];
5777                final Iterator<PackageSetting> it = sus.packages.iterator();
5778                int i = 0;
5779                while (it.hasNext()) {
5780                    PackageSetting ps = it.next();
5781                    if (ps.getInstalled(userId)) {
5782                        res[i++] = ps.name;
5783                    } else {
5784                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5785                    }
5786                }
5787                return res;
5788            } else if (obj instanceof PackageSetting) {
5789                final PackageSetting ps = (PackageSetting) obj;
5790                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5791                    return new String[]{ps.name};
5792                }
5793            }
5794        }
5795        return null;
5796    }
5797
5798    @Override
5799    public String getNameForUid(int uid) {
5800        final int callingUid = Binder.getCallingUid();
5801        if (getInstantAppPackageName(callingUid) != null) {
5802            return null;
5803        }
5804        synchronized (mPackages) {
5805            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5806            if (obj instanceof SharedUserSetting) {
5807                final SharedUserSetting sus = (SharedUserSetting) obj;
5808                return sus.name + ":" + sus.userId;
5809            } else if (obj instanceof PackageSetting) {
5810                final PackageSetting ps = (PackageSetting) obj;
5811                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5812                    return null;
5813                }
5814                return ps.name;
5815            }
5816            return null;
5817        }
5818    }
5819
5820    @Override
5821    public String[] getNamesForUids(int[] uids) {
5822        if (uids == null || uids.length == 0) {
5823            return null;
5824        }
5825        final int callingUid = Binder.getCallingUid();
5826        if (getInstantAppPackageName(callingUid) != null) {
5827            return null;
5828        }
5829        final String[] names = new String[uids.length];
5830        synchronized (mPackages) {
5831            for (int i = uids.length - 1; i >= 0; i--) {
5832                final int uid = uids[i];
5833                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5834                if (obj instanceof SharedUserSetting) {
5835                    final SharedUserSetting sus = (SharedUserSetting) obj;
5836                    names[i] = "shared:" + sus.name;
5837                } else if (obj instanceof PackageSetting) {
5838                    final PackageSetting ps = (PackageSetting) obj;
5839                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5840                        names[i] = null;
5841                    } else {
5842                        names[i] = ps.name;
5843                    }
5844                } else {
5845                    names[i] = null;
5846                }
5847            }
5848        }
5849        return names;
5850    }
5851
5852    @Override
5853    public int getUidForSharedUser(String sharedUserName) {
5854        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5855            return -1;
5856        }
5857        if (sharedUserName == null) {
5858            return -1;
5859        }
5860        // reader
5861        synchronized (mPackages) {
5862            SharedUserSetting suid;
5863            try {
5864                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5865                if (suid != null) {
5866                    return suid.userId;
5867                }
5868            } catch (PackageManagerException ignore) {
5869                // can't happen, but, still need to catch it
5870            }
5871            return -1;
5872        }
5873    }
5874
5875    @Override
5876    public int getFlagsForUid(int uid) {
5877        final int callingUid = Binder.getCallingUid();
5878        if (getInstantAppPackageName(callingUid) != null) {
5879            return 0;
5880        }
5881        synchronized (mPackages) {
5882            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5883            if (obj instanceof SharedUserSetting) {
5884                final SharedUserSetting sus = (SharedUserSetting) obj;
5885                return sus.pkgFlags;
5886            } else if (obj instanceof PackageSetting) {
5887                final PackageSetting ps = (PackageSetting) obj;
5888                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5889                    return 0;
5890                }
5891                return ps.pkgFlags;
5892            }
5893        }
5894        return 0;
5895    }
5896
5897    @Override
5898    public int getPrivateFlagsForUid(int uid) {
5899        final int callingUid = Binder.getCallingUid();
5900        if (getInstantAppPackageName(callingUid) != null) {
5901            return 0;
5902        }
5903        synchronized (mPackages) {
5904            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5905            if (obj instanceof SharedUserSetting) {
5906                final SharedUserSetting sus = (SharedUserSetting) obj;
5907                return sus.pkgPrivateFlags;
5908            } else if (obj instanceof PackageSetting) {
5909                final PackageSetting ps = (PackageSetting) obj;
5910                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5911                    return 0;
5912                }
5913                return ps.pkgPrivateFlags;
5914            }
5915        }
5916        return 0;
5917    }
5918
5919    @Override
5920    public boolean isUidPrivileged(int uid) {
5921        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5922            return false;
5923        }
5924        uid = UserHandle.getAppId(uid);
5925        // reader
5926        synchronized (mPackages) {
5927            Object obj = mSettings.getUserIdLPr(uid);
5928            if (obj instanceof SharedUserSetting) {
5929                final SharedUserSetting sus = (SharedUserSetting) obj;
5930                final Iterator<PackageSetting> it = sus.packages.iterator();
5931                while (it.hasNext()) {
5932                    if (it.next().isPrivileged()) {
5933                        return true;
5934                    }
5935                }
5936            } else if (obj instanceof PackageSetting) {
5937                final PackageSetting ps = (PackageSetting) obj;
5938                return ps.isPrivileged();
5939            }
5940        }
5941        return false;
5942    }
5943
5944    @Override
5945    public String[] getAppOpPermissionPackages(String permName) {
5946        return mPermissionManager.getAppOpPermissionPackages(permName);
5947    }
5948
5949    @Override
5950    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5951            int flags, int userId) {
5952        return resolveIntentInternal(intent, resolvedType, flags, userId, false,
5953                Binder.getCallingUid());
5954    }
5955
5956    /**
5957     * Normally instant apps can only be resolved when they're visible to the caller.
5958     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5959     * since we need to allow the system to start any installed application.
5960     */
5961    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5962            int flags, int userId, boolean resolveForStart, int filterCallingUid) {
5963        try {
5964            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5965
5966            if (!sUserManager.exists(userId)) return null;
5967            final int callingUid = Binder.getCallingUid();
5968            flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart);
5969            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5970                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5971
5972            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5973            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5974                    flags, filterCallingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5975            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5976
5977            final ResolveInfo bestChoice =
5978                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5979            return bestChoice;
5980        } finally {
5981            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5982        }
5983    }
5984
5985    @Override
5986    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5987        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5988            throw new SecurityException(
5989                    "findPersistentPreferredActivity can only be run by the system");
5990        }
5991        if (!sUserManager.exists(userId)) {
5992            return null;
5993        }
5994        final int callingUid = Binder.getCallingUid();
5995        intent = updateIntentForResolve(intent);
5996        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5997        final int flags = updateFlagsForResolve(
5998                0, userId, intent, callingUid, false /*includeInstantApps*/);
5999        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6000                userId);
6001        synchronized (mPackages) {
6002            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6003                    userId);
6004        }
6005    }
6006
6007    @Override
6008    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6009            IntentFilter filter, int match, ComponentName activity) {
6010        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6011            return;
6012        }
6013        final int userId = UserHandle.getCallingUserId();
6014        if (DEBUG_PREFERRED) {
6015            Log.v(TAG, "setLastChosenActivity intent=" + intent
6016                + " resolvedType=" + resolvedType
6017                + " flags=" + flags
6018                + " filter=" + filter
6019                + " match=" + match
6020                + " activity=" + activity);
6021            filter.dump(new PrintStreamPrinter(System.out), "    ");
6022        }
6023        intent.setComponent(null);
6024        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6025                userId);
6026        // Find any earlier preferred or last chosen entries and nuke them
6027        findPreferredActivity(intent, resolvedType,
6028                flags, query, 0, false, true, false, userId);
6029        // Add the new activity as the last chosen for this filter
6030        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6031                "Setting last chosen");
6032    }
6033
6034    @Override
6035    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6036        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6037            return null;
6038        }
6039        final int userId = UserHandle.getCallingUserId();
6040        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6041        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6042                userId);
6043        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6044                false, false, false, userId);
6045    }
6046
6047    /**
6048     * Returns whether or not instant apps have been disabled remotely.
6049     */
6050    private boolean areWebInstantAppsDisabled() {
6051        return mWebInstantAppsDisabled;
6052    }
6053
6054    private boolean isInstantAppResolutionAllowed(
6055            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6056            boolean skipPackageCheck) {
6057        if (mInstantAppResolverConnection == null) {
6058            return false;
6059        }
6060        if (mInstantAppInstallerActivity == null) {
6061            return false;
6062        }
6063        if (intent.getComponent() != null) {
6064            return false;
6065        }
6066        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6067            return false;
6068        }
6069        if (!skipPackageCheck && intent.getPackage() != null) {
6070            return false;
6071        }
6072        if (!intent.isWebIntent()) {
6073            // for non web intents, we should not resolve externally if an app already exists to
6074            // handle it or if the caller didn't explicitly request it.
6075            if ((resolvedActivities != null && resolvedActivities.size() != 0)
6076                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
6077                return false;
6078            }
6079        } else {
6080            if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
6081                return false;
6082            } else if (areWebInstantAppsDisabled()) {
6083                return false;
6084            }
6085        }
6086        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6087        // Or if there's already an ephemeral app installed that handles the action
6088        synchronized (mPackages) {
6089            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6090            for (int n = 0; n < count; n++) {
6091                final ResolveInfo info = resolvedActivities.get(n);
6092                final String packageName = info.activityInfo.packageName;
6093                final PackageSetting ps = mSettings.mPackages.get(packageName);
6094                if (ps != null) {
6095                    // only check domain verification status if the app is not a browser
6096                    if (!info.handleAllWebDataURI) {
6097                        // Try to get the status from User settings first
6098                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6099                        final int status = (int) (packedStatus >> 32);
6100                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6101                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6102                            if (DEBUG_INSTANT) {
6103                                Slog.v(TAG, "DENY instant app;"
6104                                    + " pkg: " + packageName + ", status: " + status);
6105                            }
6106                            return false;
6107                        }
6108                    }
6109                    if (ps.getInstantApp(userId)) {
6110                        if (DEBUG_INSTANT) {
6111                            Slog.v(TAG, "DENY instant app installed;"
6112                                    + " pkg: " + packageName);
6113                        }
6114                        return false;
6115                    }
6116                }
6117            }
6118        }
6119        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6120        return true;
6121    }
6122
6123    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6124            Intent origIntent, String resolvedType, String callingPackage,
6125            Bundle verificationBundle, int userId) {
6126        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6127                new InstantAppRequest(responseObj, origIntent, resolvedType,
6128                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6129        mHandler.sendMessage(msg);
6130    }
6131
6132    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6133            int flags, List<ResolveInfo> query, int userId) {
6134        if (query != null) {
6135            final int N = query.size();
6136            if (N == 1) {
6137                return query.get(0);
6138            } else if (N > 1) {
6139                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6140                // If there is more than one activity with the same priority,
6141                // then let the user decide between them.
6142                ResolveInfo r0 = query.get(0);
6143                ResolveInfo r1 = query.get(1);
6144                if (DEBUG_INTENT_MATCHING || debug) {
6145                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6146                            + r1.activityInfo.name + "=" + r1.priority);
6147                }
6148                // If the first activity has a higher priority, or a different
6149                // default, then it is always desirable to pick it.
6150                if (r0.priority != r1.priority
6151                        || r0.preferredOrder != r1.preferredOrder
6152                        || r0.isDefault != r1.isDefault) {
6153                    return query.get(0);
6154                }
6155                // If we have saved a preference for a preferred activity for
6156                // this Intent, use that.
6157                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6158                        flags, query, r0.priority, true, false, debug, userId);
6159                if (ri != null) {
6160                    return ri;
6161                }
6162                // If we have an ephemeral app, use it
6163                for (int i = 0; i < N; i++) {
6164                    ri = query.get(i);
6165                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6166                        final String packageName = ri.activityInfo.packageName;
6167                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6168                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6169                        final int status = (int)(packedStatus >> 32);
6170                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6171                            return ri;
6172                        }
6173                    }
6174                }
6175                ri = new ResolveInfo(mResolveInfo);
6176                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6177                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6178                // If all of the options come from the same package, show the application's
6179                // label and icon instead of the generic resolver's.
6180                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6181                // and then throw away the ResolveInfo itself, meaning that the caller loses
6182                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6183                // a fallback for this case; we only set the target package's resources on
6184                // the ResolveInfo, not the ActivityInfo.
6185                final String intentPackage = intent.getPackage();
6186                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6187                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6188                    ri.resolvePackageName = intentPackage;
6189                    if (userNeedsBadging(userId)) {
6190                        ri.noResourceId = true;
6191                    } else {
6192                        ri.icon = appi.icon;
6193                    }
6194                    ri.iconResourceId = appi.icon;
6195                    ri.labelRes = appi.labelRes;
6196                }
6197                ri.activityInfo.applicationInfo = new ApplicationInfo(
6198                        ri.activityInfo.applicationInfo);
6199                if (userId != 0) {
6200                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6201                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6202                }
6203                // Make sure that the resolver is displayable in car mode
6204                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6205                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6206                return ri;
6207            }
6208        }
6209        return null;
6210    }
6211
6212    /**
6213     * Return true if the given list is not empty and all of its contents have
6214     * an activityInfo with the given package name.
6215     */
6216    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6217        if (ArrayUtils.isEmpty(list)) {
6218            return false;
6219        }
6220        for (int i = 0, N = list.size(); i < N; i++) {
6221            final ResolveInfo ri = list.get(i);
6222            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6223            if (ai == null || !packageName.equals(ai.packageName)) {
6224                return false;
6225            }
6226        }
6227        return true;
6228    }
6229
6230    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6231            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6232        final int N = query.size();
6233        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6234                .get(userId);
6235        // Get the list of persistent preferred activities that handle the intent
6236        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6237        List<PersistentPreferredActivity> pprefs = ppir != null
6238                ? ppir.queryIntent(intent, resolvedType,
6239                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6240                        userId)
6241                : null;
6242        if (pprefs != null && pprefs.size() > 0) {
6243            final int M = pprefs.size();
6244            for (int i=0; i<M; i++) {
6245                final PersistentPreferredActivity ppa = pprefs.get(i);
6246                if (DEBUG_PREFERRED || debug) {
6247                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6248                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6249                            + "\n  component=" + ppa.mComponent);
6250                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6251                }
6252                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6253                        flags | MATCH_DISABLED_COMPONENTS, userId);
6254                if (DEBUG_PREFERRED || debug) {
6255                    Slog.v(TAG, "Found persistent preferred activity:");
6256                    if (ai != null) {
6257                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6258                    } else {
6259                        Slog.v(TAG, "  null");
6260                    }
6261                }
6262                if (ai == null) {
6263                    // This previously registered persistent preferred activity
6264                    // component is no longer known. Ignore it and do NOT remove it.
6265                    continue;
6266                }
6267                for (int j=0; j<N; j++) {
6268                    final ResolveInfo ri = query.get(j);
6269                    if (!ri.activityInfo.applicationInfo.packageName
6270                            .equals(ai.applicationInfo.packageName)) {
6271                        continue;
6272                    }
6273                    if (!ri.activityInfo.name.equals(ai.name)) {
6274                        continue;
6275                    }
6276                    //  Found a persistent preference that can handle the intent.
6277                    if (DEBUG_PREFERRED || debug) {
6278                        Slog.v(TAG, "Returning persistent preferred activity: " +
6279                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6280                    }
6281                    return ri;
6282                }
6283            }
6284        }
6285        return null;
6286    }
6287
6288    // TODO: handle preferred activities missing while user has amnesia
6289    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6290            List<ResolveInfo> query, int priority, boolean always,
6291            boolean removeMatches, boolean debug, int userId) {
6292        if (!sUserManager.exists(userId)) return null;
6293        final int callingUid = Binder.getCallingUid();
6294        flags = updateFlagsForResolve(
6295                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6296        intent = updateIntentForResolve(intent);
6297        // writer
6298        synchronized (mPackages) {
6299            // Try to find a matching persistent preferred activity.
6300            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6301                    debug, userId);
6302
6303            // If a persistent preferred activity matched, use it.
6304            if (pri != null) {
6305                return pri;
6306            }
6307
6308            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6309            // Get the list of preferred activities that handle the intent
6310            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6311            List<PreferredActivity> prefs = pir != null
6312                    ? pir.queryIntent(intent, resolvedType,
6313                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6314                            userId)
6315                    : null;
6316            if (prefs != null && prefs.size() > 0) {
6317                boolean changed = false;
6318                try {
6319                    // First figure out how good the original match set is.
6320                    // We will only allow preferred activities that came
6321                    // from the same match quality.
6322                    int match = 0;
6323
6324                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6325
6326                    final int N = query.size();
6327                    for (int j=0; j<N; j++) {
6328                        final ResolveInfo ri = query.get(j);
6329                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6330                                + ": 0x" + Integer.toHexString(match));
6331                        if (ri.match > match) {
6332                            match = ri.match;
6333                        }
6334                    }
6335
6336                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6337                            + Integer.toHexString(match));
6338
6339                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6340                    final int M = prefs.size();
6341                    for (int i=0; i<M; i++) {
6342                        final PreferredActivity pa = prefs.get(i);
6343                        if (DEBUG_PREFERRED || debug) {
6344                            Slog.v(TAG, "Checking PreferredActivity ds="
6345                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6346                                    + "\n  component=" + pa.mPref.mComponent);
6347                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6348                        }
6349                        if (pa.mPref.mMatch != match) {
6350                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6351                                    + Integer.toHexString(pa.mPref.mMatch));
6352                            continue;
6353                        }
6354                        // If it's not an "always" type preferred activity and that's what we're
6355                        // looking for, skip it.
6356                        if (always && !pa.mPref.mAlways) {
6357                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6358                            continue;
6359                        }
6360                        final ActivityInfo ai = getActivityInfo(
6361                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6362                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6363                                userId);
6364                        if (DEBUG_PREFERRED || debug) {
6365                            Slog.v(TAG, "Found preferred activity:");
6366                            if (ai != null) {
6367                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6368                            } else {
6369                                Slog.v(TAG, "  null");
6370                            }
6371                        }
6372                        if (ai == null) {
6373                            // This previously registered preferred activity
6374                            // component is no longer known.  Most likely an update
6375                            // to the app was installed and in the new version this
6376                            // component no longer exists.  Clean it up by removing
6377                            // it from the preferred activities list, and skip it.
6378                            Slog.w(TAG, "Removing dangling preferred activity: "
6379                                    + pa.mPref.mComponent);
6380                            pir.removeFilter(pa);
6381                            changed = true;
6382                            continue;
6383                        }
6384                        for (int j=0; j<N; j++) {
6385                            final ResolveInfo ri = query.get(j);
6386                            if (!ri.activityInfo.applicationInfo.packageName
6387                                    .equals(ai.applicationInfo.packageName)) {
6388                                continue;
6389                            }
6390                            if (!ri.activityInfo.name.equals(ai.name)) {
6391                                continue;
6392                            }
6393
6394                            if (removeMatches) {
6395                                pir.removeFilter(pa);
6396                                changed = true;
6397                                if (DEBUG_PREFERRED) {
6398                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6399                                }
6400                                break;
6401                            }
6402
6403                            // Okay we found a previously set preferred or last chosen app.
6404                            // If the result set is different from when this
6405                            // was created, and is not a subset of the preferred set, we need to
6406                            // clear it and re-ask the user their preference, if we're looking for
6407                            // an "always" type entry.
6408                            if (always && !pa.mPref.sameSet(query)) {
6409                                if (pa.mPref.isSuperset(query)) {
6410                                    // some components of the set are no longer present in
6411                                    // the query, but the preferred activity can still be reused
6412                                    if (DEBUG_PREFERRED) {
6413                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6414                                                + " still valid as only non-preferred components"
6415                                                + " were removed for " + intent + " type "
6416                                                + resolvedType);
6417                                    }
6418                                    // remove obsolete components and re-add the up-to-date filter
6419                                    PreferredActivity freshPa = new PreferredActivity(pa,
6420                                            pa.mPref.mMatch,
6421                                            pa.mPref.discardObsoleteComponents(query),
6422                                            pa.mPref.mComponent,
6423                                            pa.mPref.mAlways);
6424                                    pir.removeFilter(pa);
6425                                    pir.addFilter(freshPa);
6426                                    changed = true;
6427                                } else {
6428                                    Slog.i(TAG,
6429                                            "Result set changed, dropping preferred activity for "
6430                                                    + intent + " type " + resolvedType);
6431                                    if (DEBUG_PREFERRED) {
6432                                        Slog.v(TAG, "Removing preferred activity since set changed "
6433                                                + pa.mPref.mComponent);
6434                                    }
6435                                    pir.removeFilter(pa);
6436                                    // Re-add the filter as a "last chosen" entry (!always)
6437                                    PreferredActivity lastChosen = new PreferredActivity(
6438                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6439                                    pir.addFilter(lastChosen);
6440                                    changed = true;
6441                                    return null;
6442                                }
6443                            }
6444
6445                            // Yay! Either the set matched or we're looking for the last chosen
6446                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6447                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6448                            return ri;
6449                        }
6450                    }
6451                } finally {
6452                    if (changed) {
6453                        if (DEBUG_PREFERRED) {
6454                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6455                        }
6456                        scheduleWritePackageRestrictionsLocked(userId);
6457                    }
6458                }
6459            }
6460        }
6461        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6462        return null;
6463    }
6464
6465    /*
6466     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6467     */
6468    @Override
6469    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6470            int targetUserId) {
6471        mContext.enforceCallingOrSelfPermission(
6472                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6473        List<CrossProfileIntentFilter> matches =
6474                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6475        if (matches != null) {
6476            int size = matches.size();
6477            for (int i = 0; i < size; i++) {
6478                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6479            }
6480        }
6481        if (intent.hasWebURI()) {
6482            // cross-profile app linking works only towards the parent.
6483            final int callingUid = Binder.getCallingUid();
6484            final UserInfo parent = getProfileParent(sourceUserId);
6485            synchronized(mPackages) {
6486                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6487                        false /*includeInstantApps*/);
6488                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6489                        intent, resolvedType, flags, sourceUserId, parent.id);
6490                return xpDomainInfo != null;
6491            }
6492        }
6493        return false;
6494    }
6495
6496    private UserInfo getProfileParent(int userId) {
6497        final long identity = Binder.clearCallingIdentity();
6498        try {
6499            return sUserManager.getProfileParent(userId);
6500        } finally {
6501            Binder.restoreCallingIdentity(identity);
6502        }
6503    }
6504
6505    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6506            String resolvedType, int userId) {
6507        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6508        if (resolver != null) {
6509            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6510        }
6511        return null;
6512    }
6513
6514    @Override
6515    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6516            String resolvedType, int flags, int userId) {
6517        try {
6518            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6519
6520            return new ParceledListSlice<>(
6521                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6522        } finally {
6523            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6524        }
6525    }
6526
6527    /**
6528     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6529     * instant, returns {@code null}.
6530     */
6531    private String getInstantAppPackageName(int callingUid) {
6532        synchronized (mPackages) {
6533            // If the caller is an isolated app use the owner's uid for the lookup.
6534            if (Process.isIsolated(callingUid)) {
6535                callingUid = mIsolatedOwners.get(callingUid);
6536            }
6537            final int appId = UserHandle.getAppId(callingUid);
6538            final Object obj = mSettings.getUserIdLPr(appId);
6539            if (obj instanceof PackageSetting) {
6540                final PackageSetting ps = (PackageSetting) obj;
6541                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6542                return isInstantApp ? ps.pkg.packageName : null;
6543            }
6544        }
6545        return null;
6546    }
6547
6548    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6549            String resolvedType, int flags, int userId) {
6550        return queryIntentActivitiesInternal(
6551                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6552                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6553    }
6554
6555    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6556            String resolvedType, int flags, int filterCallingUid, int userId,
6557            boolean resolveForStart, boolean allowDynamicSplits) {
6558        if (!sUserManager.exists(userId)) return Collections.emptyList();
6559        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6560        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6561                false /* requireFullPermission */, false /* checkShell */,
6562                "query intent activities");
6563        final String pkgName = intent.getPackage();
6564        ComponentName comp = intent.getComponent();
6565        if (comp == null) {
6566            if (intent.getSelector() != null) {
6567                intent = intent.getSelector();
6568                comp = intent.getComponent();
6569            }
6570        }
6571
6572        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6573                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6574        if (comp != null) {
6575            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6576            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6577            if (ai != null) {
6578                // When specifying an explicit component, we prevent the activity from being
6579                // used when either 1) the calling package is normal and the activity is within
6580                // an ephemeral application or 2) the calling package is ephemeral and the
6581                // activity is not visible to ephemeral applications.
6582                final boolean matchInstantApp =
6583                        (flags & PackageManager.MATCH_INSTANT) != 0;
6584                final boolean matchVisibleToInstantAppOnly =
6585                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6586                final boolean matchExplicitlyVisibleOnly =
6587                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6588                final boolean isCallerInstantApp =
6589                        instantAppPkgName != null;
6590                final boolean isTargetSameInstantApp =
6591                        comp.getPackageName().equals(instantAppPkgName);
6592                final boolean isTargetInstantApp =
6593                        (ai.applicationInfo.privateFlags
6594                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6595                final boolean isTargetVisibleToInstantApp =
6596                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6597                final boolean isTargetExplicitlyVisibleToInstantApp =
6598                        isTargetVisibleToInstantApp
6599                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6600                final boolean isTargetHiddenFromInstantApp =
6601                        !isTargetVisibleToInstantApp
6602                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6603                final boolean blockResolution =
6604                        !isTargetSameInstantApp
6605                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6606                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6607                                        && isTargetHiddenFromInstantApp));
6608                if (!blockResolution) {
6609                    final ResolveInfo ri = new ResolveInfo();
6610                    ri.activityInfo = ai;
6611                    list.add(ri);
6612                }
6613            }
6614            return applyPostResolutionFilter(
6615                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6616        }
6617
6618        // reader
6619        boolean sortResult = false;
6620        boolean addInstant = false;
6621        List<ResolveInfo> result;
6622        synchronized (mPackages) {
6623            if (pkgName == null) {
6624                List<CrossProfileIntentFilter> matchingFilters =
6625                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6626                // Check for results that need to skip the current profile.
6627                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6628                        resolvedType, flags, userId);
6629                if (xpResolveInfo != null) {
6630                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6631                    xpResult.add(xpResolveInfo);
6632                    return applyPostResolutionFilter(
6633                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6634                            allowDynamicSplits, filterCallingUid, userId, intent);
6635                }
6636
6637                // Check for results in the current profile.
6638                result = filterIfNotSystemUser(mActivities.queryIntent(
6639                        intent, resolvedType, flags, userId), userId);
6640                addInstant = isInstantAppResolutionAllowed(intent, result, userId,
6641                        false /*skipPackageCheck*/);
6642                // Check for cross profile results.
6643                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6644                xpResolveInfo = queryCrossProfileIntents(
6645                        matchingFilters, intent, resolvedType, flags, userId,
6646                        hasNonNegativePriorityResult);
6647                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6648                    boolean isVisibleToUser = filterIfNotSystemUser(
6649                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6650                    if (isVisibleToUser) {
6651                        result.add(xpResolveInfo);
6652                        sortResult = true;
6653                    }
6654                }
6655                if (intent.hasWebURI()) {
6656                    CrossProfileDomainInfo xpDomainInfo = null;
6657                    final UserInfo parent = getProfileParent(userId);
6658                    if (parent != null) {
6659                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6660                                flags, userId, parent.id);
6661                    }
6662                    if (xpDomainInfo != null) {
6663                        if (xpResolveInfo != null) {
6664                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6665                            // in the result.
6666                            result.remove(xpResolveInfo);
6667                        }
6668                        if (result.size() == 0 && !addInstant) {
6669                            // No result in current profile, but found candidate in parent user.
6670                            // And we are not going to add emphemeral app, so we can return the
6671                            // result straight away.
6672                            result.add(xpDomainInfo.resolveInfo);
6673                            return applyPostResolutionFilter(result, instantAppPkgName,
6674                                    allowDynamicSplits, filterCallingUid, userId, intent);
6675                        }
6676                    } else if (result.size() <= 1 && !addInstant) {
6677                        // No result in parent user and <= 1 result in current profile, and we
6678                        // are not going to add emphemeral app, so we can return the result without
6679                        // further processing.
6680                        return applyPostResolutionFilter(result, instantAppPkgName,
6681                                allowDynamicSplits, filterCallingUid, userId, intent);
6682                    }
6683                    // We have more than one candidate (combining results from current and parent
6684                    // profile), so we need filtering and sorting.
6685                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6686                            intent, flags, result, xpDomainInfo, userId);
6687                    sortResult = true;
6688                }
6689            } else {
6690                final PackageParser.Package pkg = mPackages.get(pkgName);
6691                result = null;
6692                if (pkg != null) {
6693                    result = filterIfNotSystemUser(
6694                            mActivities.queryIntentForPackage(
6695                                    intent, resolvedType, flags, pkg.activities, userId),
6696                            userId);
6697                }
6698                if (result == null || result.size() == 0) {
6699                    // the caller wants to resolve for a particular package; however, there
6700                    // were no installed results, so, try to find an ephemeral result
6701                    addInstant = isInstantAppResolutionAllowed(
6702                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6703                    if (result == null) {
6704                        result = new ArrayList<>();
6705                    }
6706                }
6707            }
6708        }
6709        if (addInstant) {
6710            result = maybeAddInstantAppInstaller(
6711                    result, intent, resolvedType, flags, userId, resolveForStart);
6712        }
6713        if (sortResult) {
6714            Collections.sort(result, mResolvePrioritySorter);
6715        }
6716        return applyPostResolutionFilter(
6717                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6718    }
6719
6720    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6721            String resolvedType, int flags, int userId, boolean resolveForStart) {
6722        // first, check to see if we've got an instant app already installed
6723        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6724        ResolveInfo localInstantApp = null;
6725        boolean blockResolution = false;
6726        if (!alreadyResolvedLocally) {
6727            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6728                    flags
6729                        | PackageManager.GET_RESOLVED_FILTER
6730                        | PackageManager.MATCH_INSTANT
6731                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6732                    userId);
6733            for (int i = instantApps.size() - 1; i >= 0; --i) {
6734                final ResolveInfo info = instantApps.get(i);
6735                final String packageName = info.activityInfo.packageName;
6736                final PackageSetting ps = mSettings.mPackages.get(packageName);
6737                if (ps.getInstantApp(userId)) {
6738                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6739                    final int status = (int)(packedStatus >> 32);
6740                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6741                        // there's a local instant application installed, but, the user has
6742                        // chosen to never use it; skip resolution and don't acknowledge
6743                        // an instant application is even available
6744                        if (DEBUG_INSTANT) {
6745                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6746                        }
6747                        blockResolution = true;
6748                        break;
6749                    } else {
6750                        // we have a locally installed instant application; skip resolution
6751                        // but acknowledge there's an instant application available
6752                        if (DEBUG_INSTANT) {
6753                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6754                        }
6755                        localInstantApp = info;
6756                        break;
6757                    }
6758                }
6759            }
6760        }
6761        // no app installed, let's see if one's available
6762        AuxiliaryResolveInfo auxiliaryResponse = null;
6763        if (!blockResolution) {
6764            if (localInstantApp == null) {
6765                // we don't have an instant app locally, resolve externally
6766                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6767                final InstantAppRequest requestObject = new InstantAppRequest(
6768                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6769                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6770                        resolveForStart);
6771                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6772                        mInstantAppResolverConnection, requestObject);
6773                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6774            } else {
6775                // we have an instant application locally, but, we can't admit that since
6776                // callers shouldn't be able to determine prior browsing. create a dummy
6777                // auxiliary response so the downstream code behaves as if there's an
6778                // instant application available externally. when it comes time to start
6779                // the instant application, we'll do the right thing.
6780                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6781                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6782                                        ai.packageName, ai.longVersionCode, null /* splitName */);
6783            }
6784        }
6785        if (intent.isWebIntent() && auxiliaryResponse == null) {
6786            return result;
6787        }
6788        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6789        if (ps == null
6790                || ps.getUserState().get(userId) == null
6791                || !ps.getUserState().get(userId).isEnabled(mInstantAppInstallerActivity, 0)) {
6792            return result;
6793        }
6794        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6795        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6796                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6797        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6798                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6799        // add a non-generic filter
6800        ephemeralInstaller.filter = new IntentFilter();
6801        if (intent.getAction() != null) {
6802            ephemeralInstaller.filter.addAction(intent.getAction());
6803        }
6804        if (intent.getData() != null && intent.getData().getPath() != null) {
6805            ephemeralInstaller.filter.addDataPath(
6806                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6807        }
6808        ephemeralInstaller.isInstantAppAvailable = true;
6809        // make sure this resolver is the default
6810        ephemeralInstaller.isDefault = true;
6811        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6812        if (DEBUG_INSTANT) {
6813            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6814        }
6815
6816        result.add(ephemeralInstaller);
6817        return result;
6818    }
6819
6820    private static class CrossProfileDomainInfo {
6821        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6822        ResolveInfo resolveInfo;
6823        /* Best domain verification status of the activities found in the other profile */
6824        int bestDomainVerificationStatus;
6825    }
6826
6827    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6828            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6829        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6830                sourceUserId)) {
6831            return null;
6832        }
6833        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6834                resolvedType, flags, parentUserId);
6835
6836        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6837            return null;
6838        }
6839        CrossProfileDomainInfo result = null;
6840        int size = resultTargetUser.size();
6841        for (int i = 0; i < size; i++) {
6842            ResolveInfo riTargetUser = resultTargetUser.get(i);
6843            // Intent filter verification is only for filters that specify a host. So don't return
6844            // those that handle all web uris.
6845            if (riTargetUser.handleAllWebDataURI) {
6846                continue;
6847            }
6848            String packageName = riTargetUser.activityInfo.packageName;
6849            PackageSetting ps = mSettings.mPackages.get(packageName);
6850            if (ps == null) {
6851                continue;
6852            }
6853            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6854            int status = (int)(verificationState >> 32);
6855            if (result == null) {
6856                result = new CrossProfileDomainInfo();
6857                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6858                        sourceUserId, parentUserId);
6859                result.bestDomainVerificationStatus = status;
6860            } else {
6861                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6862                        result.bestDomainVerificationStatus);
6863            }
6864        }
6865        // Don't consider matches with status NEVER across profiles.
6866        if (result != null && result.bestDomainVerificationStatus
6867                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6868            return null;
6869        }
6870        return result;
6871    }
6872
6873    /**
6874     * Verification statuses are ordered from the worse to the best, except for
6875     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6876     */
6877    private int bestDomainVerificationStatus(int status1, int status2) {
6878        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6879            return status2;
6880        }
6881        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6882            return status1;
6883        }
6884        return (int) MathUtils.max(status1, status2);
6885    }
6886
6887    private boolean isUserEnabled(int userId) {
6888        long callingId = Binder.clearCallingIdentity();
6889        try {
6890            UserInfo userInfo = sUserManager.getUserInfo(userId);
6891            return userInfo != null && userInfo.isEnabled();
6892        } finally {
6893            Binder.restoreCallingIdentity(callingId);
6894        }
6895    }
6896
6897    /**
6898     * Filter out activities with systemUserOnly flag set, when current user is not System.
6899     *
6900     * @return filtered list
6901     */
6902    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6903        if (userId == UserHandle.USER_SYSTEM) {
6904            return resolveInfos;
6905        }
6906        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6907            ResolveInfo info = resolveInfos.get(i);
6908            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6909                resolveInfos.remove(i);
6910            }
6911        }
6912        return resolveInfos;
6913    }
6914
6915    /**
6916     * Filters out ephemeral activities.
6917     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6918     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6919     *
6920     * @param resolveInfos The pre-filtered list of resolved activities
6921     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6922     *          is performed.
6923     * @param intent
6924     * @return A filtered list of resolved activities.
6925     */
6926    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6927            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId,
6928            Intent intent) {
6929        final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled();
6930        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6931            final ResolveInfo info = resolveInfos.get(i);
6932            // remove locally resolved instant app web results when disabled
6933            if (info.isInstantAppAvailable && blockInstant) {
6934                resolveInfos.remove(i);
6935                continue;
6936            }
6937            // allow activities that are defined in the provided package
6938            if (allowDynamicSplits
6939                    && info.activityInfo != null
6940                    && info.activityInfo.splitName != null
6941                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6942                            info.activityInfo.splitName)) {
6943                if (mInstantAppInstallerActivity == null) {
6944                    if (DEBUG_INSTALL) {
6945                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6946                    }
6947                    resolveInfos.remove(i);
6948                    continue;
6949                }
6950                if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) {
6951                    resolveInfos.remove(i);
6952                    continue;
6953                }
6954                // requested activity is defined in a split that hasn't been installed yet.
6955                // add the installer to the resolve list
6956                if (DEBUG_INSTALL) {
6957                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6958                }
6959                final ResolveInfo installerInfo = new ResolveInfo(
6960                        mInstantAppInstallerInfo);
6961                final ComponentName installFailureActivity = findInstallFailureActivity(
6962                        info.activityInfo.packageName,  filterCallingUid, userId);
6963                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6964                        installFailureActivity,
6965                        info.activityInfo.packageName,
6966                        info.activityInfo.applicationInfo.longVersionCode,
6967                        info.activityInfo.splitName);
6968                // add a non-generic filter
6969                installerInfo.filter = new IntentFilter();
6970
6971                // This resolve info may appear in the chooser UI, so let us make it
6972                // look as the one it replaces as far as the user is concerned which
6973                // requires loading the correct label and icon for the resolve info.
6974                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6975                installerInfo.labelRes = info.resolveLabelResId();
6976                installerInfo.icon = info.resolveIconResId();
6977                installerInfo.isInstantAppAvailable = true;
6978                resolveInfos.set(i, installerInfo);
6979                continue;
6980            }
6981            // caller is a full app, don't need to apply any other filtering
6982            if (ephemeralPkgName == null) {
6983                continue;
6984            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6985                // caller is same app; don't need to apply any other filtering
6986                continue;
6987            }
6988            // allow activities that have been explicitly exposed to ephemeral apps
6989            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6990            if (!isEphemeralApp
6991                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6992                continue;
6993            }
6994            resolveInfos.remove(i);
6995        }
6996        return resolveInfos;
6997    }
6998
6999    /**
7000     * Returns the activity component that can handle install failures.
7001     * <p>By default, the instant application installer handles failures. However, an
7002     * application may want to handle failures on its own. Applications do this by
7003     * creating an activity with an intent filter that handles the action
7004     * {@link Intent#ACTION_INSTALL_FAILURE}.
7005     */
7006    private @Nullable ComponentName findInstallFailureActivity(
7007            String packageName, int filterCallingUid, int userId) {
7008        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7009        failureActivityIntent.setPackage(packageName);
7010        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7011        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7012                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7013                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7014        final int NR = result.size();
7015        if (NR > 0) {
7016            for (int i = 0; i < NR; i++) {
7017                final ResolveInfo info = result.get(i);
7018                if (info.activityInfo.splitName != null) {
7019                    continue;
7020                }
7021                return new ComponentName(packageName, info.activityInfo.name);
7022            }
7023        }
7024        return null;
7025    }
7026
7027    /**
7028     * @param resolveInfos list of resolve infos in descending priority order
7029     * @return if the list contains a resolve info with non-negative priority
7030     */
7031    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7032        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7033    }
7034
7035    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7036            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7037            int userId) {
7038        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7039
7040        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7041            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7042                    candidates.size());
7043        }
7044
7045        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7046        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7047        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7048        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7049        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7050        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7051
7052        synchronized (mPackages) {
7053            final int count = candidates.size();
7054            // First, try to use linked apps. Partition the candidates into four lists:
7055            // one for the final results, one for the "do not use ever", one for "undefined status"
7056            // and finally one for "browser app type".
7057            for (int n=0; n<count; n++) {
7058                ResolveInfo info = candidates.get(n);
7059                String packageName = info.activityInfo.packageName;
7060                PackageSetting ps = mSettings.mPackages.get(packageName);
7061                if (ps != null) {
7062                    // Add to the special match all list (Browser use case)
7063                    if (info.handleAllWebDataURI) {
7064                        matchAllList.add(info);
7065                        continue;
7066                    }
7067                    // Try to get the status from User settings first
7068                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7069                    int status = (int)(packedStatus >> 32);
7070                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7071                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7072                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7073                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7074                                    + " : linkgen=" + linkGeneration);
7075                        }
7076                        // Use link-enabled generation as preferredOrder, i.e.
7077                        // prefer newly-enabled over earlier-enabled.
7078                        info.preferredOrder = linkGeneration;
7079                        alwaysList.add(info);
7080                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7081                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7082                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7083                        }
7084                        neverList.add(info);
7085                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7086                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7087                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7088                        }
7089                        alwaysAskList.add(info);
7090                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7091                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7092                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7093                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7094                        }
7095                        undefinedList.add(info);
7096                    }
7097                }
7098            }
7099
7100            // We'll want to include browser possibilities in a few cases
7101            boolean includeBrowser = false;
7102
7103            // First try to add the "always" resolution(s) for the current user, if any
7104            if (alwaysList.size() > 0) {
7105                result.addAll(alwaysList);
7106            } else {
7107                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7108                result.addAll(undefinedList);
7109                // Maybe add one for the other profile.
7110                if (xpDomainInfo != null && (
7111                        xpDomainInfo.bestDomainVerificationStatus
7112                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7113                    result.add(xpDomainInfo.resolveInfo);
7114                }
7115                includeBrowser = true;
7116            }
7117
7118            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7119            // If there were 'always' entries their preferred order has been set, so we also
7120            // back that off to make the alternatives equivalent
7121            if (alwaysAskList.size() > 0) {
7122                for (ResolveInfo i : result) {
7123                    i.preferredOrder = 0;
7124                }
7125                result.addAll(alwaysAskList);
7126                includeBrowser = true;
7127            }
7128
7129            if (includeBrowser) {
7130                // Also add browsers (all of them or only the default one)
7131                if (DEBUG_DOMAIN_VERIFICATION) {
7132                    Slog.v(TAG, "   ...including browsers in candidate set");
7133                }
7134                if ((matchFlags & MATCH_ALL) != 0) {
7135                    result.addAll(matchAllList);
7136                } else {
7137                    // Browser/generic handling case.  If there's a default browser, go straight
7138                    // to that (but only if there is no other higher-priority match).
7139                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7140                    int maxMatchPrio = 0;
7141                    ResolveInfo defaultBrowserMatch = null;
7142                    final int numCandidates = matchAllList.size();
7143                    for (int n = 0; n < numCandidates; n++) {
7144                        ResolveInfo info = matchAllList.get(n);
7145                        // track the highest overall match priority...
7146                        if (info.priority > maxMatchPrio) {
7147                            maxMatchPrio = info.priority;
7148                        }
7149                        // ...and the highest-priority default browser match
7150                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7151                            if (defaultBrowserMatch == null
7152                                    || (defaultBrowserMatch.priority < info.priority)) {
7153                                if (debug) {
7154                                    Slog.v(TAG, "Considering default browser match " + info);
7155                                }
7156                                defaultBrowserMatch = info;
7157                            }
7158                        }
7159                    }
7160                    if (defaultBrowserMatch != null
7161                            && defaultBrowserMatch.priority >= maxMatchPrio
7162                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7163                    {
7164                        if (debug) {
7165                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7166                        }
7167                        result.add(defaultBrowserMatch);
7168                    } else {
7169                        result.addAll(matchAllList);
7170                    }
7171                }
7172
7173                // If there is nothing selected, add all candidates and remove the ones that the user
7174                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7175                if (result.size() == 0) {
7176                    result.addAll(candidates);
7177                    result.removeAll(neverList);
7178                }
7179            }
7180        }
7181        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7182            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7183                    result.size());
7184            for (ResolveInfo info : result) {
7185                Slog.v(TAG, "  + " + info.activityInfo);
7186            }
7187        }
7188        return result;
7189    }
7190
7191    // Returns a packed value as a long:
7192    //
7193    // high 'int'-sized word: link status: undefined/ask/never/always.
7194    // low 'int'-sized word: relative priority among 'always' results.
7195    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7196        long result = ps.getDomainVerificationStatusForUser(userId);
7197        // if none available, get the master status
7198        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7199            if (ps.getIntentFilterVerificationInfo() != null) {
7200                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7201            }
7202        }
7203        return result;
7204    }
7205
7206    private ResolveInfo querySkipCurrentProfileIntents(
7207            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7208            int flags, int sourceUserId) {
7209        if (matchingFilters != null) {
7210            int size = matchingFilters.size();
7211            for (int i = 0; i < size; i ++) {
7212                CrossProfileIntentFilter filter = matchingFilters.get(i);
7213                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7214                    // Checking if there are activities in the target user that can handle the
7215                    // intent.
7216                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7217                            resolvedType, flags, sourceUserId);
7218                    if (resolveInfo != null) {
7219                        return resolveInfo;
7220                    }
7221                }
7222            }
7223        }
7224        return null;
7225    }
7226
7227    // Return matching ResolveInfo in target user if any.
7228    private ResolveInfo queryCrossProfileIntents(
7229            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7230            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7231        if (matchingFilters != null) {
7232            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7233            // match the same intent. For performance reasons, it is better not to
7234            // run queryIntent twice for the same userId
7235            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7236            int size = matchingFilters.size();
7237            for (int i = 0; i < size; i++) {
7238                CrossProfileIntentFilter filter = matchingFilters.get(i);
7239                int targetUserId = filter.getTargetUserId();
7240                boolean skipCurrentProfile =
7241                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7242                boolean skipCurrentProfileIfNoMatchFound =
7243                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7244                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7245                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7246                    // Checking if there are activities in the target user that can handle the
7247                    // intent.
7248                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7249                            resolvedType, flags, sourceUserId);
7250                    if (resolveInfo != null) return resolveInfo;
7251                    alreadyTriedUserIds.put(targetUserId, true);
7252                }
7253            }
7254        }
7255        return null;
7256    }
7257
7258    /**
7259     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7260     * will forward the intent to the filter's target user.
7261     * Otherwise, returns null.
7262     */
7263    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7264            String resolvedType, int flags, int sourceUserId) {
7265        int targetUserId = filter.getTargetUserId();
7266        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7267                resolvedType, flags, targetUserId);
7268        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7269            // If all the matches in the target profile are suspended, return null.
7270            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7271                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7272                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7273                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7274                            targetUserId);
7275                }
7276            }
7277        }
7278        return null;
7279    }
7280
7281    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7282            int sourceUserId, int targetUserId) {
7283        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7284        long ident = Binder.clearCallingIdentity();
7285        boolean targetIsProfile;
7286        try {
7287            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7288        } finally {
7289            Binder.restoreCallingIdentity(ident);
7290        }
7291        String className;
7292        if (targetIsProfile) {
7293            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7294        } else {
7295            className = FORWARD_INTENT_TO_PARENT;
7296        }
7297        ComponentName forwardingActivityComponentName = new ComponentName(
7298                mAndroidApplication.packageName, className);
7299        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7300                sourceUserId);
7301        if (!targetIsProfile) {
7302            forwardingActivityInfo.showUserIcon = targetUserId;
7303            forwardingResolveInfo.noResourceId = true;
7304        }
7305        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7306        forwardingResolveInfo.priority = 0;
7307        forwardingResolveInfo.preferredOrder = 0;
7308        forwardingResolveInfo.match = 0;
7309        forwardingResolveInfo.isDefault = true;
7310        forwardingResolveInfo.filter = filter;
7311        forwardingResolveInfo.targetUserId = targetUserId;
7312        return forwardingResolveInfo;
7313    }
7314
7315    @Override
7316    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7317            Intent[] specifics, String[] specificTypes, Intent intent,
7318            String resolvedType, int flags, int userId) {
7319        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7320                specificTypes, intent, resolvedType, flags, userId));
7321    }
7322
7323    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7324            Intent[] specifics, String[] specificTypes, Intent intent,
7325            String resolvedType, int flags, int userId) {
7326        if (!sUserManager.exists(userId)) return Collections.emptyList();
7327        final int callingUid = Binder.getCallingUid();
7328        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7329                false /*includeInstantApps*/);
7330        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7331                false /*requireFullPermission*/, false /*checkShell*/,
7332                "query intent activity options");
7333        final String resultsAction = intent.getAction();
7334
7335        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7336                | PackageManager.GET_RESOLVED_FILTER, userId);
7337
7338        if (DEBUG_INTENT_MATCHING) {
7339            Log.v(TAG, "Query " + intent + ": " + results);
7340        }
7341
7342        int specificsPos = 0;
7343        int N;
7344
7345        // todo: note that the algorithm used here is O(N^2).  This
7346        // isn't a problem in our current environment, but if we start running
7347        // into situations where we have more than 5 or 10 matches then this
7348        // should probably be changed to something smarter...
7349
7350        // First we go through and resolve each of the specific items
7351        // that were supplied, taking care of removing any corresponding
7352        // duplicate items in the generic resolve list.
7353        if (specifics != null) {
7354            for (int i=0; i<specifics.length; i++) {
7355                final Intent sintent = specifics[i];
7356                if (sintent == null) {
7357                    continue;
7358                }
7359
7360                if (DEBUG_INTENT_MATCHING) {
7361                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7362                }
7363
7364                String action = sintent.getAction();
7365                if (resultsAction != null && resultsAction.equals(action)) {
7366                    // If this action was explicitly requested, then don't
7367                    // remove things that have it.
7368                    action = null;
7369                }
7370
7371                ResolveInfo ri = null;
7372                ActivityInfo ai = null;
7373
7374                ComponentName comp = sintent.getComponent();
7375                if (comp == null) {
7376                    ri = resolveIntent(
7377                        sintent,
7378                        specificTypes != null ? specificTypes[i] : null,
7379                            flags, userId);
7380                    if (ri == null) {
7381                        continue;
7382                    }
7383                    if (ri == mResolveInfo) {
7384                        // ACK!  Must do something better with this.
7385                    }
7386                    ai = ri.activityInfo;
7387                    comp = new ComponentName(ai.applicationInfo.packageName,
7388                            ai.name);
7389                } else {
7390                    ai = getActivityInfo(comp, flags, userId);
7391                    if (ai == null) {
7392                        continue;
7393                    }
7394                }
7395
7396                // Look for any generic query activities that are duplicates
7397                // of this specific one, and remove them from the results.
7398                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7399                N = results.size();
7400                int j;
7401                for (j=specificsPos; j<N; j++) {
7402                    ResolveInfo sri = results.get(j);
7403                    if ((sri.activityInfo.name.equals(comp.getClassName())
7404                            && sri.activityInfo.applicationInfo.packageName.equals(
7405                                    comp.getPackageName()))
7406                        || (action != null && sri.filter.matchAction(action))) {
7407                        results.remove(j);
7408                        if (DEBUG_INTENT_MATCHING) Log.v(
7409                            TAG, "Removing duplicate item from " + j
7410                            + " due to specific " + specificsPos);
7411                        if (ri == null) {
7412                            ri = sri;
7413                        }
7414                        j--;
7415                        N--;
7416                    }
7417                }
7418
7419                // Add this specific item to its proper place.
7420                if (ri == null) {
7421                    ri = new ResolveInfo();
7422                    ri.activityInfo = ai;
7423                }
7424                results.add(specificsPos, ri);
7425                ri.specificIndex = i;
7426                specificsPos++;
7427            }
7428        }
7429
7430        // Now we go through the remaining generic results and remove any
7431        // duplicate actions that are found here.
7432        N = results.size();
7433        for (int i=specificsPos; i<N-1; i++) {
7434            final ResolveInfo rii = results.get(i);
7435            if (rii.filter == null) {
7436                continue;
7437            }
7438
7439            // Iterate over all of the actions of this result's intent
7440            // filter...  typically this should be just one.
7441            final Iterator<String> it = rii.filter.actionsIterator();
7442            if (it == null) {
7443                continue;
7444            }
7445            while (it.hasNext()) {
7446                final String action = it.next();
7447                if (resultsAction != null && resultsAction.equals(action)) {
7448                    // If this action was explicitly requested, then don't
7449                    // remove things that have it.
7450                    continue;
7451                }
7452                for (int j=i+1; j<N; j++) {
7453                    final ResolveInfo rij = results.get(j);
7454                    if (rij.filter != null && rij.filter.hasAction(action)) {
7455                        results.remove(j);
7456                        if (DEBUG_INTENT_MATCHING) Log.v(
7457                            TAG, "Removing duplicate item from " + j
7458                            + " due to action " + action + " at " + i);
7459                        j--;
7460                        N--;
7461                    }
7462                }
7463            }
7464
7465            // If the caller didn't request filter information, drop it now
7466            // so we don't have to marshall/unmarshall it.
7467            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7468                rii.filter = null;
7469            }
7470        }
7471
7472        // Filter out the caller activity if so requested.
7473        if (caller != null) {
7474            N = results.size();
7475            for (int i=0; i<N; i++) {
7476                ActivityInfo ainfo = results.get(i).activityInfo;
7477                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7478                        && caller.getClassName().equals(ainfo.name)) {
7479                    results.remove(i);
7480                    break;
7481                }
7482            }
7483        }
7484
7485        // If the caller didn't request filter information,
7486        // drop them now so we don't have to
7487        // marshall/unmarshall it.
7488        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7489            N = results.size();
7490            for (int i=0; i<N; i++) {
7491                results.get(i).filter = null;
7492            }
7493        }
7494
7495        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7496        return results;
7497    }
7498
7499    @Override
7500    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7501            String resolvedType, int flags, int userId) {
7502        return new ParceledListSlice<>(
7503                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7504                        false /*allowDynamicSplits*/));
7505    }
7506
7507    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7508            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7509        if (!sUserManager.exists(userId)) return Collections.emptyList();
7510        final int callingUid = Binder.getCallingUid();
7511        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7512                false /*requireFullPermission*/, false /*checkShell*/,
7513                "query intent receivers");
7514        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7515        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7516                false /*includeInstantApps*/);
7517        ComponentName comp = intent.getComponent();
7518        if (comp == null) {
7519            if (intent.getSelector() != null) {
7520                intent = intent.getSelector();
7521                comp = intent.getComponent();
7522            }
7523        }
7524        if (comp != null) {
7525            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7526            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7527            if (ai != null) {
7528                // When specifying an explicit component, we prevent the activity from being
7529                // used when either 1) the calling package is normal and the activity is within
7530                // an instant application or 2) the calling package is ephemeral and the
7531                // activity is not visible to instant applications.
7532                final boolean matchInstantApp =
7533                        (flags & PackageManager.MATCH_INSTANT) != 0;
7534                final boolean matchVisibleToInstantAppOnly =
7535                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7536                final boolean matchExplicitlyVisibleOnly =
7537                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7538                final boolean isCallerInstantApp =
7539                        instantAppPkgName != null;
7540                final boolean isTargetSameInstantApp =
7541                        comp.getPackageName().equals(instantAppPkgName);
7542                final boolean isTargetInstantApp =
7543                        (ai.applicationInfo.privateFlags
7544                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7545                final boolean isTargetVisibleToInstantApp =
7546                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7547                final boolean isTargetExplicitlyVisibleToInstantApp =
7548                        isTargetVisibleToInstantApp
7549                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7550                final boolean isTargetHiddenFromInstantApp =
7551                        !isTargetVisibleToInstantApp
7552                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7553                final boolean blockResolution =
7554                        !isTargetSameInstantApp
7555                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7556                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7557                                        && isTargetHiddenFromInstantApp));
7558                if (!blockResolution) {
7559                    ResolveInfo ri = new ResolveInfo();
7560                    ri.activityInfo = ai;
7561                    list.add(ri);
7562                }
7563            }
7564            return applyPostResolutionFilter(
7565                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7566        }
7567
7568        // reader
7569        synchronized (mPackages) {
7570            String pkgName = intent.getPackage();
7571            if (pkgName == null) {
7572                final List<ResolveInfo> result =
7573                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7574                return applyPostResolutionFilter(
7575                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7576            }
7577            final PackageParser.Package pkg = mPackages.get(pkgName);
7578            if (pkg != null) {
7579                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7580                        intent, resolvedType, flags, pkg.receivers, userId);
7581                return applyPostResolutionFilter(
7582                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7583            }
7584            return Collections.emptyList();
7585        }
7586    }
7587
7588    @Override
7589    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7590        final int callingUid = Binder.getCallingUid();
7591        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7592    }
7593
7594    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7595            int userId, int callingUid) {
7596        if (!sUserManager.exists(userId)) return null;
7597        flags = updateFlagsForResolve(
7598                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7599        List<ResolveInfo> query = queryIntentServicesInternal(
7600                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7601        if (query != null) {
7602            if (query.size() >= 1) {
7603                // If there is more than one service with the same priority,
7604                // just arbitrarily pick the first one.
7605                return query.get(0);
7606            }
7607        }
7608        return null;
7609    }
7610
7611    @Override
7612    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7613            String resolvedType, int flags, int userId) {
7614        final int callingUid = Binder.getCallingUid();
7615        return new ParceledListSlice<>(queryIntentServicesInternal(
7616                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7617    }
7618
7619    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7620            String resolvedType, int flags, int userId, int callingUid,
7621            boolean includeInstantApps) {
7622        if (!sUserManager.exists(userId)) return Collections.emptyList();
7623        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7624                false /*requireFullPermission*/, false /*checkShell*/,
7625                "query intent receivers");
7626        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7627        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7628        ComponentName comp = intent.getComponent();
7629        if (comp == null) {
7630            if (intent.getSelector() != null) {
7631                intent = intent.getSelector();
7632                comp = intent.getComponent();
7633            }
7634        }
7635        if (comp != null) {
7636            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7637            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7638            if (si != null) {
7639                // When specifying an explicit component, we prevent the service from being
7640                // used when either 1) the service is in an instant application and the
7641                // caller is not the same instant application or 2) the calling package is
7642                // ephemeral and the activity is not visible to ephemeral applications.
7643                final boolean matchInstantApp =
7644                        (flags & PackageManager.MATCH_INSTANT) != 0;
7645                final boolean matchVisibleToInstantAppOnly =
7646                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7647                final boolean isCallerInstantApp =
7648                        instantAppPkgName != null;
7649                final boolean isTargetSameInstantApp =
7650                        comp.getPackageName().equals(instantAppPkgName);
7651                final boolean isTargetInstantApp =
7652                        (si.applicationInfo.privateFlags
7653                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7654                final boolean isTargetHiddenFromInstantApp =
7655                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7656                final boolean blockResolution =
7657                        !isTargetSameInstantApp
7658                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7659                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7660                                        && isTargetHiddenFromInstantApp));
7661                if (!blockResolution) {
7662                    final ResolveInfo ri = new ResolveInfo();
7663                    ri.serviceInfo = si;
7664                    list.add(ri);
7665                }
7666            }
7667            return list;
7668        }
7669
7670        // reader
7671        synchronized (mPackages) {
7672            String pkgName = intent.getPackage();
7673            if (pkgName == null) {
7674                return applyPostServiceResolutionFilter(
7675                        mServices.queryIntent(intent, resolvedType, flags, userId),
7676                        instantAppPkgName);
7677            }
7678            final PackageParser.Package pkg = mPackages.get(pkgName);
7679            if (pkg != null) {
7680                return applyPostServiceResolutionFilter(
7681                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7682                                userId),
7683                        instantAppPkgName);
7684            }
7685            return Collections.emptyList();
7686        }
7687    }
7688
7689    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7690            String instantAppPkgName) {
7691        if (instantAppPkgName == null) {
7692            return resolveInfos;
7693        }
7694        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7695            final ResolveInfo info = resolveInfos.get(i);
7696            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7697            // allow services that are defined in the provided package
7698            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7699                if (info.serviceInfo.splitName != null
7700                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7701                                info.serviceInfo.splitName)) {
7702                    // requested service is defined in a split that hasn't been installed yet.
7703                    // add the installer to the resolve list
7704                    if (DEBUG_INSTANT) {
7705                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7706                    }
7707                    final ResolveInfo installerInfo = new ResolveInfo(
7708                            mInstantAppInstallerInfo);
7709                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7710                            null /* installFailureActivity */,
7711                            info.serviceInfo.packageName,
7712                            info.serviceInfo.applicationInfo.longVersionCode,
7713                            info.serviceInfo.splitName);
7714                    // add a non-generic filter
7715                    installerInfo.filter = new IntentFilter();
7716                    // load resources from the correct package
7717                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7718                    resolveInfos.set(i, installerInfo);
7719                }
7720                continue;
7721            }
7722            // allow services that have been explicitly exposed to ephemeral apps
7723            if (!isEphemeralApp
7724                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7725                continue;
7726            }
7727            resolveInfos.remove(i);
7728        }
7729        return resolveInfos;
7730    }
7731
7732    @Override
7733    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7734            String resolvedType, int flags, int userId) {
7735        return new ParceledListSlice<>(
7736                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7737    }
7738
7739    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7740            Intent intent, String resolvedType, int flags, int userId) {
7741        if (!sUserManager.exists(userId)) return Collections.emptyList();
7742        final int callingUid = Binder.getCallingUid();
7743        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7744        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7745                false /*includeInstantApps*/);
7746        ComponentName comp = intent.getComponent();
7747        if (comp == null) {
7748            if (intent.getSelector() != null) {
7749                intent = intent.getSelector();
7750                comp = intent.getComponent();
7751            }
7752        }
7753        if (comp != null) {
7754            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7755            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7756            if (pi != null) {
7757                // When specifying an explicit component, we prevent the provider from being
7758                // used when either 1) the provider is in an instant application and the
7759                // caller is not the same instant application or 2) the calling package is an
7760                // instant application and the provider is not visible to instant applications.
7761                final boolean matchInstantApp =
7762                        (flags & PackageManager.MATCH_INSTANT) != 0;
7763                final boolean matchVisibleToInstantAppOnly =
7764                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7765                final boolean isCallerInstantApp =
7766                        instantAppPkgName != null;
7767                final boolean isTargetSameInstantApp =
7768                        comp.getPackageName().equals(instantAppPkgName);
7769                final boolean isTargetInstantApp =
7770                        (pi.applicationInfo.privateFlags
7771                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7772                final boolean isTargetHiddenFromInstantApp =
7773                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7774                final boolean blockResolution =
7775                        !isTargetSameInstantApp
7776                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7777                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7778                                        && isTargetHiddenFromInstantApp));
7779                if (!blockResolution) {
7780                    final ResolveInfo ri = new ResolveInfo();
7781                    ri.providerInfo = pi;
7782                    list.add(ri);
7783                }
7784            }
7785            return list;
7786        }
7787
7788        // reader
7789        synchronized (mPackages) {
7790            String pkgName = intent.getPackage();
7791            if (pkgName == null) {
7792                return applyPostContentProviderResolutionFilter(
7793                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7794                        instantAppPkgName);
7795            }
7796            final PackageParser.Package pkg = mPackages.get(pkgName);
7797            if (pkg != null) {
7798                return applyPostContentProviderResolutionFilter(
7799                        mProviders.queryIntentForPackage(
7800                        intent, resolvedType, flags, pkg.providers, userId),
7801                        instantAppPkgName);
7802            }
7803            return Collections.emptyList();
7804        }
7805    }
7806
7807    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7808            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7809        if (instantAppPkgName == null) {
7810            return resolveInfos;
7811        }
7812        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7813            final ResolveInfo info = resolveInfos.get(i);
7814            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7815            // allow providers that are defined in the provided package
7816            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7817                if (info.providerInfo.splitName != null
7818                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7819                                info.providerInfo.splitName)) {
7820                    // requested provider is defined in a split that hasn't been installed yet.
7821                    // add the installer to the resolve list
7822                    if (DEBUG_INSTANT) {
7823                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7824                    }
7825                    final ResolveInfo installerInfo = new ResolveInfo(
7826                            mInstantAppInstallerInfo);
7827                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7828                            null /*failureActivity*/,
7829                            info.providerInfo.packageName,
7830                            info.providerInfo.applicationInfo.longVersionCode,
7831                            info.providerInfo.splitName);
7832                    // add a non-generic filter
7833                    installerInfo.filter = new IntentFilter();
7834                    // load resources from the correct package
7835                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7836                    resolveInfos.set(i, installerInfo);
7837                }
7838                continue;
7839            }
7840            // allow providers that have been explicitly exposed to instant applications
7841            if (!isEphemeralApp
7842                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7843                continue;
7844            }
7845            resolveInfos.remove(i);
7846        }
7847        return resolveInfos;
7848    }
7849
7850    @Override
7851    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7852        final int callingUid = Binder.getCallingUid();
7853        if (getInstantAppPackageName(callingUid) != null) {
7854            return ParceledListSlice.emptyList();
7855        }
7856        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7857        flags = updateFlagsForPackage(flags, userId, null);
7858        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7859        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7860                true /* requireFullPermission */, false /* checkShell */,
7861                "get installed packages");
7862
7863        // writer
7864        synchronized (mPackages) {
7865            ArrayList<PackageInfo> list;
7866            if (listUninstalled) {
7867                list = new ArrayList<>(mSettings.mPackages.size());
7868                for (PackageSetting ps : mSettings.mPackages.values()) {
7869                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7870                        continue;
7871                    }
7872                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7873                        continue;
7874                    }
7875                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7876                    if (pi != null) {
7877                        list.add(pi);
7878                    }
7879                }
7880            } else {
7881                list = new ArrayList<>(mPackages.size());
7882                for (PackageParser.Package p : mPackages.values()) {
7883                    final PackageSetting ps = (PackageSetting) p.mExtras;
7884                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7885                        continue;
7886                    }
7887                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7888                        continue;
7889                    }
7890                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7891                            p.mExtras, flags, userId);
7892                    if (pi != null) {
7893                        list.add(pi);
7894                    }
7895                }
7896            }
7897
7898            return new ParceledListSlice<>(list);
7899        }
7900    }
7901
7902    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7903            String[] permissions, boolean[] tmp, int flags, int userId) {
7904        int numMatch = 0;
7905        final PermissionsState permissionsState = ps.getPermissionsState();
7906        for (int i=0; i<permissions.length; i++) {
7907            final String permission = permissions[i];
7908            if (permissionsState.hasPermission(permission, userId)) {
7909                tmp[i] = true;
7910                numMatch++;
7911            } else {
7912                tmp[i] = false;
7913            }
7914        }
7915        if (numMatch == 0) {
7916            return;
7917        }
7918        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7919
7920        // The above might return null in cases of uninstalled apps or install-state
7921        // skew across users/profiles.
7922        if (pi != null) {
7923            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7924                if (numMatch == permissions.length) {
7925                    pi.requestedPermissions = permissions;
7926                } else {
7927                    pi.requestedPermissions = new String[numMatch];
7928                    numMatch = 0;
7929                    for (int i=0; i<permissions.length; i++) {
7930                        if (tmp[i]) {
7931                            pi.requestedPermissions[numMatch] = permissions[i];
7932                            numMatch++;
7933                        }
7934                    }
7935                }
7936            }
7937            list.add(pi);
7938        }
7939    }
7940
7941    @Override
7942    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7943            String[] permissions, int flags, int userId) {
7944        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7945        flags = updateFlagsForPackage(flags, userId, permissions);
7946        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7947                true /* requireFullPermission */, false /* checkShell */,
7948                "get packages holding permissions");
7949        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7950
7951        // writer
7952        synchronized (mPackages) {
7953            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7954            boolean[] tmpBools = new boolean[permissions.length];
7955            if (listUninstalled) {
7956                for (PackageSetting ps : mSettings.mPackages.values()) {
7957                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7958                            userId);
7959                }
7960            } else {
7961                for (PackageParser.Package pkg : mPackages.values()) {
7962                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7963                    if (ps != null) {
7964                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7965                                userId);
7966                    }
7967                }
7968            }
7969
7970            return new ParceledListSlice<PackageInfo>(list);
7971        }
7972    }
7973
7974    @Override
7975    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7976        final int callingUid = Binder.getCallingUid();
7977        if (getInstantAppPackageName(callingUid) != null) {
7978            return ParceledListSlice.emptyList();
7979        }
7980        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7981        flags = updateFlagsForApplication(flags, userId, null);
7982        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7983
7984        // writer
7985        synchronized (mPackages) {
7986            ArrayList<ApplicationInfo> list;
7987            if (listUninstalled) {
7988                list = new ArrayList<>(mSettings.mPackages.size());
7989                for (PackageSetting ps : mSettings.mPackages.values()) {
7990                    ApplicationInfo ai;
7991                    int effectiveFlags = flags;
7992                    if (ps.isSystem()) {
7993                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7994                    }
7995                    if (ps.pkg != null) {
7996                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7997                            continue;
7998                        }
7999                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8000                            continue;
8001                        }
8002                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8003                                ps.readUserState(userId), userId);
8004                        if (ai != null) {
8005                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8006                        }
8007                    } else {
8008                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8009                        // and already converts to externally visible package name
8010                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8011                                callingUid, effectiveFlags, userId);
8012                    }
8013                    if (ai != null) {
8014                        list.add(ai);
8015                    }
8016                }
8017            } else {
8018                list = new ArrayList<>(mPackages.size());
8019                for (PackageParser.Package p : mPackages.values()) {
8020                    if (p.mExtras != null) {
8021                        PackageSetting ps = (PackageSetting) p.mExtras;
8022                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8023                            continue;
8024                        }
8025                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8026                            continue;
8027                        }
8028                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8029                                ps.readUserState(userId), userId);
8030                        if (ai != null) {
8031                            ai.packageName = resolveExternalPackageNameLPr(p);
8032                            list.add(ai);
8033                        }
8034                    }
8035                }
8036            }
8037
8038            return new ParceledListSlice<>(list);
8039        }
8040    }
8041
8042    @Override
8043    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8044        if (HIDE_EPHEMERAL_APIS) {
8045            return null;
8046        }
8047        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8048            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8049                    "getEphemeralApplications");
8050        }
8051        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8052                true /* requireFullPermission */, false /* checkShell */,
8053                "getEphemeralApplications");
8054        synchronized (mPackages) {
8055            List<InstantAppInfo> instantApps = mInstantAppRegistry
8056                    .getInstantAppsLPr(userId);
8057            if (instantApps != null) {
8058                return new ParceledListSlice<>(instantApps);
8059            }
8060        }
8061        return null;
8062    }
8063
8064    @Override
8065    public boolean isInstantApp(String packageName, int userId) {
8066        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8067                true /* requireFullPermission */, false /* checkShell */,
8068                "isInstantApp");
8069        if (HIDE_EPHEMERAL_APIS) {
8070            return false;
8071        }
8072
8073        synchronized (mPackages) {
8074            int callingUid = Binder.getCallingUid();
8075            if (Process.isIsolated(callingUid)) {
8076                callingUid = mIsolatedOwners.get(callingUid);
8077            }
8078            final PackageSetting ps = mSettings.mPackages.get(packageName);
8079            PackageParser.Package pkg = mPackages.get(packageName);
8080            final boolean returnAllowed =
8081                    ps != null
8082                    && (isCallerSameApp(packageName, callingUid)
8083                            || canViewInstantApps(callingUid, userId)
8084                            || mInstantAppRegistry.isInstantAccessGranted(
8085                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8086            if (returnAllowed) {
8087                return ps.getInstantApp(userId);
8088            }
8089        }
8090        return false;
8091    }
8092
8093    @Override
8094    public byte[] getInstantAppCookie(String packageName, int userId) {
8095        if (HIDE_EPHEMERAL_APIS) {
8096            return null;
8097        }
8098
8099        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8100                true /* requireFullPermission */, false /* checkShell */,
8101                "getInstantAppCookie");
8102        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8103            return null;
8104        }
8105        synchronized (mPackages) {
8106            return mInstantAppRegistry.getInstantAppCookieLPw(
8107                    packageName, userId);
8108        }
8109    }
8110
8111    @Override
8112    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8113        if (HIDE_EPHEMERAL_APIS) {
8114            return true;
8115        }
8116
8117        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8118                true /* requireFullPermission */, true /* checkShell */,
8119                "setInstantAppCookie");
8120        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8121            return false;
8122        }
8123        synchronized (mPackages) {
8124            return mInstantAppRegistry.setInstantAppCookieLPw(
8125                    packageName, cookie, userId);
8126        }
8127    }
8128
8129    @Override
8130    public Bitmap getInstantAppIcon(String packageName, int userId) {
8131        if (HIDE_EPHEMERAL_APIS) {
8132            return null;
8133        }
8134
8135        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8136            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8137                    "getInstantAppIcon");
8138        }
8139        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8140                true /* requireFullPermission */, false /* checkShell */,
8141                "getInstantAppIcon");
8142
8143        synchronized (mPackages) {
8144            return mInstantAppRegistry.getInstantAppIconLPw(
8145                    packageName, userId);
8146        }
8147    }
8148
8149    private boolean isCallerSameApp(String packageName, int uid) {
8150        PackageParser.Package pkg = mPackages.get(packageName);
8151        return pkg != null
8152                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8153    }
8154
8155    @Override
8156    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8157        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8158            return ParceledListSlice.emptyList();
8159        }
8160        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8161    }
8162
8163    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8164        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8165
8166        // reader
8167        synchronized (mPackages) {
8168            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8169            final int userId = UserHandle.getCallingUserId();
8170            while (i.hasNext()) {
8171                final PackageParser.Package p = i.next();
8172                if (p.applicationInfo == null) continue;
8173
8174                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8175                        && !p.applicationInfo.isDirectBootAware();
8176                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8177                        && p.applicationInfo.isDirectBootAware();
8178
8179                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8180                        && (!mSafeMode || isSystemApp(p))
8181                        && (matchesUnaware || matchesAware)) {
8182                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8183                    if (ps != null) {
8184                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8185                                ps.readUserState(userId), userId);
8186                        if (ai != null) {
8187                            finalList.add(ai);
8188                        }
8189                    }
8190                }
8191            }
8192        }
8193
8194        return finalList;
8195    }
8196
8197    @Override
8198    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8199        return resolveContentProviderInternal(name, flags, userId);
8200    }
8201
8202    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8203        if (!sUserManager.exists(userId)) return null;
8204        flags = updateFlagsForComponent(flags, userId, name);
8205        final int callingUid = Binder.getCallingUid();
8206        synchronized (mPackages) {
8207            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8208            PackageSetting ps = provider != null
8209                    ? mSettings.mPackages.get(provider.owner.packageName)
8210                    : null;
8211            if (ps != null) {
8212                // provider not enabled
8213                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8214                    return null;
8215                }
8216                final ComponentName component =
8217                        new ComponentName(provider.info.packageName, provider.info.name);
8218                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8219                    return null;
8220                }
8221                return PackageParser.generateProviderInfo(
8222                        provider, flags, ps.readUserState(userId), userId);
8223            }
8224            return null;
8225        }
8226    }
8227
8228    /**
8229     * @deprecated
8230     */
8231    @Deprecated
8232    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8233        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8234            return;
8235        }
8236        // reader
8237        synchronized (mPackages) {
8238            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8239                    .entrySet().iterator();
8240            final int userId = UserHandle.getCallingUserId();
8241            while (i.hasNext()) {
8242                Map.Entry<String, PackageParser.Provider> entry = i.next();
8243                PackageParser.Provider p = entry.getValue();
8244                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8245
8246                if (ps != null && p.syncable
8247                        && (!mSafeMode || (p.info.applicationInfo.flags
8248                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8249                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8250                            ps.readUserState(userId), userId);
8251                    if (info != null) {
8252                        outNames.add(entry.getKey());
8253                        outInfo.add(info);
8254                    }
8255                }
8256            }
8257        }
8258    }
8259
8260    @Override
8261    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8262            int uid, int flags, String metaDataKey) {
8263        final int callingUid = Binder.getCallingUid();
8264        final int userId = processName != null ? UserHandle.getUserId(uid)
8265                : UserHandle.getCallingUserId();
8266        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8267        flags = updateFlagsForComponent(flags, userId, processName);
8268        ArrayList<ProviderInfo> finalList = null;
8269        // reader
8270        synchronized (mPackages) {
8271            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8272            while (i.hasNext()) {
8273                final PackageParser.Provider p = i.next();
8274                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8275                if (ps != null && p.info.authority != null
8276                        && (processName == null
8277                                || (p.info.processName.equals(processName)
8278                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8279                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8280
8281                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8282                    // parameter.
8283                    if (metaDataKey != null
8284                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8285                        continue;
8286                    }
8287                    final ComponentName component =
8288                            new ComponentName(p.info.packageName, p.info.name);
8289                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8290                        continue;
8291                    }
8292                    if (finalList == null) {
8293                        finalList = new ArrayList<ProviderInfo>(3);
8294                    }
8295                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8296                            ps.readUserState(userId), userId);
8297                    if (info != null) {
8298                        finalList.add(info);
8299                    }
8300                }
8301            }
8302        }
8303
8304        if (finalList != null) {
8305            Collections.sort(finalList, mProviderInitOrderSorter);
8306            return new ParceledListSlice<ProviderInfo>(finalList);
8307        }
8308
8309        return ParceledListSlice.emptyList();
8310    }
8311
8312    @Override
8313    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8314        // reader
8315        synchronized (mPackages) {
8316            final int callingUid = Binder.getCallingUid();
8317            final int callingUserId = UserHandle.getUserId(callingUid);
8318            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8319            if (ps == null) return null;
8320            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8321                return null;
8322            }
8323            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8324            return PackageParser.generateInstrumentationInfo(i, flags);
8325        }
8326    }
8327
8328    @Override
8329    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8330            String targetPackage, int flags) {
8331        final int callingUid = Binder.getCallingUid();
8332        final int callingUserId = UserHandle.getUserId(callingUid);
8333        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8334        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8335            return ParceledListSlice.emptyList();
8336        }
8337        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8338    }
8339
8340    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8341            int flags) {
8342        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8343
8344        // reader
8345        synchronized (mPackages) {
8346            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8347            while (i.hasNext()) {
8348                final PackageParser.Instrumentation p = i.next();
8349                if (targetPackage == null
8350                        || targetPackage.equals(p.info.targetPackage)) {
8351                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8352                            flags);
8353                    if (ii != null) {
8354                        finalList.add(ii);
8355                    }
8356                }
8357            }
8358        }
8359
8360        return finalList;
8361    }
8362
8363    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8364        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8365        try {
8366            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8367        } finally {
8368            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8369        }
8370    }
8371
8372    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8373        final File[] files = scanDir.listFiles();
8374        if (ArrayUtils.isEmpty(files)) {
8375            Log.d(TAG, "No files in app dir " + scanDir);
8376            return;
8377        }
8378
8379        if (DEBUG_PACKAGE_SCANNING) {
8380            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8381                    + " flags=0x" + Integer.toHexString(parseFlags));
8382        }
8383        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8384                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8385                mParallelPackageParserCallback)) {
8386            // Submit files for parsing in parallel
8387            int fileCount = 0;
8388            for (File file : files) {
8389                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8390                        && !PackageInstallerService.isStageName(file.getName());
8391                if (!isPackage) {
8392                    // Ignore entries which are not packages
8393                    continue;
8394                }
8395                parallelPackageParser.submit(file, parseFlags);
8396                fileCount++;
8397            }
8398
8399            // Process results one by one
8400            for (; fileCount > 0; fileCount--) {
8401                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8402                Throwable throwable = parseResult.throwable;
8403                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8404
8405                if (throwable == null) {
8406                    // TODO(toddke): move lower in the scan chain
8407                    // Static shared libraries have synthetic package names
8408                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8409                        renameStaticSharedLibraryPackage(parseResult.pkg);
8410                    }
8411                    try {
8412                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8413                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8414                                    currentTime, null);
8415                        }
8416                    } catch (PackageManagerException e) {
8417                        errorCode = e.error;
8418                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8419                    }
8420                } else if (throwable instanceof PackageParser.PackageParserException) {
8421                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8422                            throwable;
8423                    errorCode = e.error;
8424                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8425                } else {
8426                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8427                            + parseResult.scanFile, throwable);
8428                }
8429
8430                // Delete invalid userdata apps
8431                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8432                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8433                    logCriticalInfo(Log.WARN,
8434                            "Deleting invalid package at " + parseResult.scanFile);
8435                    removeCodePathLI(parseResult.scanFile);
8436                }
8437            }
8438        }
8439    }
8440
8441    public static void reportSettingsProblem(int priority, String msg) {
8442        logCriticalInfo(priority, msg);
8443    }
8444
8445    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8446            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8447        // When upgrading from pre-N MR1, verify the package time stamp using the package
8448        // directory and not the APK file.
8449        final long lastModifiedTime = mIsPreNMR1Upgrade
8450                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8451        if (ps != null && !forceCollect
8452                && ps.codePathString.equals(pkg.codePath)
8453                && ps.timeStamp == lastModifiedTime
8454                && !isCompatSignatureUpdateNeeded(pkg)
8455                && !isRecoverSignatureUpdateNeeded(pkg)) {
8456            if (ps.signatures.mSigningDetails.signatures != null
8457                    && ps.signatures.mSigningDetails.signatures.length != 0
8458                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8459                            != SignatureSchemeVersion.UNKNOWN) {
8460                // Optimization: reuse the existing cached signing data
8461                // if the package appears to be unchanged.
8462                pkg.mSigningDetails =
8463                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8464                return;
8465            }
8466
8467            Slog.w(TAG, "PackageSetting for " + ps.name
8468                    + " is missing signatures.  Collecting certs again to recover them.");
8469        } else {
8470            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8471                    (forceCollect ? " (forced)" : ""));
8472        }
8473
8474        try {
8475            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8476            PackageParser.collectCertificates(pkg, skipVerify);
8477        } catch (PackageParserException e) {
8478            throw PackageManagerException.from(e);
8479        } finally {
8480            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8481        }
8482    }
8483
8484    /**
8485     *  Traces a package scan.
8486     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8487     */
8488    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8489            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8490        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8491        try {
8492            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8493        } finally {
8494            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8495        }
8496    }
8497
8498    /**
8499     *  Scans a package and returns the newly parsed package.
8500     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8501     */
8502    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8503            long currentTime, UserHandle user) throws PackageManagerException {
8504        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8505        PackageParser pp = new PackageParser();
8506        pp.setSeparateProcesses(mSeparateProcesses);
8507        pp.setOnlyCoreApps(mOnlyCore);
8508        pp.setDisplayMetrics(mMetrics);
8509        pp.setCallback(mPackageParserCallback);
8510
8511        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8512        final PackageParser.Package pkg;
8513        try {
8514            pkg = pp.parsePackage(scanFile, parseFlags);
8515        } catch (PackageParserException e) {
8516            throw PackageManagerException.from(e);
8517        } finally {
8518            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8519        }
8520
8521        // Static shared libraries have synthetic package names
8522        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8523            renameStaticSharedLibraryPackage(pkg);
8524        }
8525
8526        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8527    }
8528
8529    /**
8530     *  Scans a package and returns the newly parsed package.
8531     *  @throws PackageManagerException on a parse error.
8532     */
8533    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8534            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8535            @Nullable UserHandle user)
8536                    throws PackageManagerException {
8537        // If the package has children and this is the first dive in the function
8538        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8539        // packages (parent and children) would be successfully scanned before the
8540        // actual scan since scanning mutates internal state and we want to atomically
8541        // install the package and its children.
8542        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8543            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8544                scanFlags |= SCAN_CHECK_ONLY;
8545            }
8546        } else {
8547            scanFlags &= ~SCAN_CHECK_ONLY;
8548        }
8549
8550        // Scan the parent
8551        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8552                scanFlags, currentTime, user);
8553
8554        // Scan the children
8555        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8556        for (int i = 0; i < childCount; i++) {
8557            PackageParser.Package childPackage = pkg.childPackages.get(i);
8558            addForInitLI(childPackage, parseFlags, scanFlags,
8559                    currentTime, user);
8560        }
8561
8562
8563        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8564            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8565        }
8566
8567        return scannedPkg;
8568    }
8569
8570    /**
8571     * Returns if full apk verification can be skipped for the whole package, including the splits.
8572     */
8573    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8574        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8575            return false;
8576        }
8577        // TODO: Allow base and splits to be verified individually.
8578        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8579            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8580                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8581                    return false;
8582                }
8583            }
8584        }
8585        return true;
8586    }
8587
8588    /**
8589     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8590     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8591     * match one in a trusted source, and should be done separately.
8592     */
8593    private boolean canSkipFullApkVerification(String apkPath) {
8594        byte[] rootHashObserved = null;
8595        try {
8596            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8597            if (rootHashObserved == null) {
8598                return false;  // APK does not contain Merkle tree root hash.
8599            }
8600            synchronized (mInstallLock) {
8601                // Returns whether the observed root hash matches what kernel has.
8602                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8603                return true;
8604            }
8605        } catch (InstallerException | IOException | DigestException |
8606                NoSuchAlgorithmException e) {
8607            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8608        }
8609        return false;
8610    }
8611
8612    /**
8613     * Adds a new package to the internal data structures during platform initialization.
8614     * <p>After adding, the package is known to the system and available for querying.
8615     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8616     * etc...], additional checks are performed. Basic verification [such as ensuring
8617     * matching signatures, checking version codes, etc...] occurs if the package is
8618     * identical to a previously known package. If the package fails a signature check,
8619     * the version installed on /data will be removed. If the version of the new package
8620     * is less than or equal than the version on /data, it will be ignored.
8621     * <p>Regardless of the package location, the results are applied to the internal
8622     * structures and the package is made available to the rest of the system.
8623     * <p>NOTE: The return value should be removed. It's the passed in package object.
8624     */
8625    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8626            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8627            @Nullable UserHandle user)
8628                    throws PackageManagerException {
8629        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8630        final String renamedPkgName;
8631        final PackageSetting disabledPkgSetting;
8632        final boolean isSystemPkgUpdated;
8633        final boolean pkgAlreadyExists;
8634        PackageSetting pkgSetting;
8635
8636        // NOTE: installPackageLI() has the same code to setup the package's
8637        // application info. This probably should be done lower in the call
8638        // stack [such as scanPackageOnly()]. However, we verify the application
8639        // info prior to that [in scanPackageNew()] and thus have to setup
8640        // the application info early.
8641        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8642        pkg.setApplicationInfoCodePath(pkg.codePath);
8643        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8644        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8645        pkg.setApplicationInfoResourcePath(pkg.codePath);
8646        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8647        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8648
8649        synchronized (mPackages) {
8650            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8651            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8652            if (realPkgName != null) {
8653                ensurePackageRenamed(pkg, renamedPkgName);
8654            }
8655            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8656            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8657            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8658            pkgAlreadyExists = pkgSetting != null;
8659            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8660            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8661            isSystemPkgUpdated = disabledPkgSetting != null;
8662
8663            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8664                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8665            }
8666
8667            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8668                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8669                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8670                    : null;
8671            if (DEBUG_PACKAGE_SCANNING
8672                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8673                    && sharedUserSetting != null) {
8674                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8675                        + " (uid=" + sharedUserSetting.userId + "):"
8676                        + " packages=" + sharedUserSetting.packages);
8677            }
8678
8679            if (scanSystemPartition) {
8680                // Potentially prune child packages. If the application on the /system
8681                // partition has been updated via OTA, but, is still disabled by a
8682                // version on /data, cycle through all of its children packages and
8683                // remove children that are no longer defined.
8684                if (isSystemPkgUpdated) {
8685                    final int scannedChildCount = (pkg.childPackages != null)
8686                            ? pkg.childPackages.size() : 0;
8687                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8688                            ? disabledPkgSetting.childPackageNames.size() : 0;
8689                    for (int i = 0; i < disabledChildCount; i++) {
8690                        String disabledChildPackageName =
8691                                disabledPkgSetting.childPackageNames.get(i);
8692                        boolean disabledPackageAvailable = false;
8693                        for (int j = 0; j < scannedChildCount; j++) {
8694                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8695                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8696                                disabledPackageAvailable = true;
8697                                break;
8698                            }
8699                        }
8700                        if (!disabledPackageAvailable) {
8701                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8702                        }
8703                    }
8704                    // we're updating the disabled package, so, scan it as the package setting
8705                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, null,
8706                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8707                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8708                            (pkg == mPlatformPackage), user);
8709                    applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage);
8710                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8711                }
8712            }
8713        }
8714
8715        final boolean newPkgChangedPaths =
8716                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8717        final boolean newPkgVersionGreater =
8718                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8719        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8720                && newPkgChangedPaths && newPkgVersionGreater;
8721        if (isSystemPkgBetter) {
8722            // The version of the application on /system is greater than the version on
8723            // /data. Switch back to the application on /system.
8724            // It's safe to assume the application on /system will correctly scan. If not,
8725            // there won't be a working copy of the application.
8726            synchronized (mPackages) {
8727                // just remove the loaded entries from package lists
8728                mPackages.remove(pkgSetting.name);
8729            }
8730
8731            logCriticalInfo(Log.WARN,
8732                    "System package updated;"
8733                    + " name: " + pkgSetting.name
8734                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8735                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8736
8737            final InstallArgs args = createInstallArgsForExisting(
8738                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8739                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8740            args.cleanUpResourcesLI();
8741            synchronized (mPackages) {
8742                mSettings.enableSystemPackageLPw(pkgSetting.name);
8743            }
8744        }
8745
8746        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8747            // The version of the application on the /system partition is less than or
8748            // equal to the version on the /data partition. Throw an exception and use
8749            // the application already installed on the /data partition.
8750            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8751                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8752                    + " better than this " + pkg.getLongVersionCode());
8753        }
8754
8755        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8756        // force re-collecting certificate.
8757        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8758                disabledPkgSetting);
8759        // Full APK verification can be skipped during certificate collection, only if the file is
8760        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8761        // cases, only data in Signing Block is verified instead of the whole file.
8762        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8763                (forceCollect && canSkipFullPackageVerification(pkg));
8764        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8765
8766        boolean shouldHideSystemApp = false;
8767        // A new application appeared on /system, but, we already have a copy of
8768        // the application installed on /data.
8769        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8770                && !pkgSetting.isSystem()) {
8771
8772            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8773                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
8774                            && !pkgSetting.signatures.mSigningDetails.checkCapability(
8775                                    pkg.mSigningDetails,
8776                                    PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
8777                logCriticalInfo(Log.WARN,
8778                        "System package signature mismatch;"
8779                        + " name: " + pkgSetting.name);
8780                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8781                        "scanPackageInternalLI")) {
8782                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8783                }
8784                pkgSetting = null;
8785            } else if (newPkgVersionGreater) {
8786                // The application on /system is newer than the application on /data.
8787                // Simply remove the application on /data [keeping application data]
8788                // and replace it with the version on /system.
8789                logCriticalInfo(Log.WARN,
8790                        "System package enabled;"
8791                        + " name: " + pkgSetting.name
8792                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8793                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8794                InstallArgs args = createInstallArgsForExisting(
8795                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8796                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8797                synchronized (mInstallLock) {
8798                    args.cleanUpResourcesLI();
8799                }
8800            } else {
8801                // The application on /system is older than the application on /data. Hide
8802                // the application on /system and the version on /data will be scanned later
8803                // and re-added like an update.
8804                shouldHideSystemApp = true;
8805                logCriticalInfo(Log.INFO,
8806                        "System package disabled;"
8807                        + " name: " + pkgSetting.name
8808                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8809                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8810            }
8811        }
8812
8813        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8814                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8815
8816        if (shouldHideSystemApp) {
8817            synchronized (mPackages) {
8818                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8819            }
8820        }
8821        return scannedPkg;
8822    }
8823
8824    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8825        // Derive the new package synthetic package name
8826        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8827                + pkg.staticSharedLibVersion);
8828    }
8829
8830    private static String fixProcessName(String defProcessName,
8831            String processName) {
8832        if (processName == null) {
8833            return defProcessName;
8834        }
8835        return processName;
8836    }
8837
8838    /**
8839     * Enforces that only the system UID or root's UID can call a method exposed
8840     * via Binder.
8841     *
8842     * @param message used as message if SecurityException is thrown
8843     * @throws SecurityException if the caller is not system or root
8844     */
8845    private static final void enforceSystemOrRoot(String message) {
8846        final int uid = Binder.getCallingUid();
8847        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8848            throw new SecurityException(message);
8849        }
8850    }
8851
8852    @Override
8853    public void performFstrimIfNeeded() {
8854        enforceSystemOrRoot("Only the system can request fstrim");
8855
8856        // Before everything else, see whether we need to fstrim.
8857        try {
8858            IStorageManager sm = PackageHelper.getStorageManager();
8859            if (sm != null) {
8860                boolean doTrim = false;
8861                final long interval = android.provider.Settings.Global.getLong(
8862                        mContext.getContentResolver(),
8863                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8864                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8865                if (interval > 0) {
8866                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8867                    if (timeSinceLast > interval) {
8868                        doTrim = true;
8869                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8870                                + "; running immediately");
8871                    }
8872                }
8873                if (doTrim) {
8874                    final boolean dexOptDialogShown;
8875                    synchronized (mPackages) {
8876                        dexOptDialogShown = mDexOptDialogShown;
8877                    }
8878                    if (!isFirstBoot() && dexOptDialogShown) {
8879                        try {
8880                            ActivityManager.getService().showBootMessage(
8881                                    mContext.getResources().getString(
8882                                            R.string.android_upgrading_fstrim), true);
8883                        } catch (RemoteException e) {
8884                        }
8885                    }
8886                    sm.runMaintenance();
8887                }
8888            } else {
8889                Slog.e(TAG, "storageManager service unavailable!");
8890            }
8891        } catch (RemoteException e) {
8892            // Can't happen; StorageManagerService is local
8893        }
8894    }
8895
8896    @Override
8897    public void updatePackagesIfNeeded() {
8898        enforceSystemOrRoot("Only the system can request package update");
8899
8900        // We need to re-extract after an OTA.
8901        boolean causeUpgrade = isUpgrade();
8902
8903        // First boot or factory reset.
8904        // Note: we also handle devices that are upgrading to N right now as if it is their
8905        //       first boot, as they do not have profile data.
8906        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8907
8908        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8909        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8910
8911        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8912            return;
8913        }
8914
8915        List<PackageParser.Package> pkgs;
8916        synchronized (mPackages) {
8917            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8918        }
8919
8920        final long startTime = System.nanoTime();
8921        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8922                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
8923                    false /* bootComplete */);
8924
8925        final int elapsedTimeSeconds =
8926                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8927
8928        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8929        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8930        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8931        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8932        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8933    }
8934
8935    /*
8936     * Return the prebuilt profile path given a package base code path.
8937     */
8938    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8939        return pkg.baseCodePath + ".prof";
8940    }
8941
8942    /**
8943     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8944     * containing statistics about the invocation. The array consists of three elements,
8945     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8946     * and {@code numberOfPackagesFailed}.
8947     */
8948    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8949            final int compilationReason, boolean bootComplete) {
8950
8951        int numberOfPackagesVisited = 0;
8952        int numberOfPackagesOptimized = 0;
8953        int numberOfPackagesSkipped = 0;
8954        int numberOfPackagesFailed = 0;
8955        final int numberOfPackagesToDexopt = pkgs.size();
8956
8957        for (PackageParser.Package pkg : pkgs) {
8958            numberOfPackagesVisited++;
8959
8960            boolean useProfileForDexopt = false;
8961
8962            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8963                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8964                // that are already compiled.
8965                File profileFile = new File(getPrebuildProfilePath(pkg));
8966                // Copy profile if it exists.
8967                if (profileFile.exists()) {
8968                    try {
8969                        // We could also do this lazily before calling dexopt in
8970                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8971                        // is that we don't have a good way to say "do this only once".
8972                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8973                                pkg.applicationInfo.uid, pkg.packageName,
8974                                ArtManager.getProfileName(null))) {
8975                            Log.e(TAG, "Installer failed to copy system profile!");
8976                        } else {
8977                            // Disabled as this causes speed-profile compilation during first boot
8978                            // even if things are already compiled.
8979                            // useProfileForDexopt = true;
8980                        }
8981                    } catch (Exception e) {
8982                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8983                                e);
8984                    }
8985                } else {
8986                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8987                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8988                    // minimize the number off apps being speed-profile compiled during first boot.
8989                    // The other paths will not change the filter.
8990                    if (disabledPs != null && disabledPs.pkg.isStub) {
8991                        // The package is the stub one, remove the stub suffix to get the normal
8992                        // package and APK names.
8993                        String systemProfilePath =
8994                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8995                        profileFile = new File(systemProfilePath);
8996                        // If we have a profile for a compressed APK, copy it to the reference
8997                        // location.
8998                        // Note that copying the profile here will cause it to override the
8999                        // reference profile every OTA even though the existing reference profile
9000                        // may have more data. We can't copy during decompression since the
9001                        // directories are not set up at that point.
9002                        if (profileFile.exists()) {
9003                            try {
9004                                // We could also do this lazily before calling dexopt in
9005                                // PackageDexOptimizer to prevent this happening on first boot. The
9006                                // issue is that we don't have a good way to say "do this only
9007                                // once".
9008                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9009                                        pkg.applicationInfo.uid, pkg.packageName,
9010                                        ArtManager.getProfileName(null))) {
9011                                    Log.e(TAG, "Failed to copy system profile for stub package!");
9012                                } else {
9013                                    useProfileForDexopt = true;
9014                                }
9015                            } catch (Exception e) {
9016                                Log.e(TAG, "Failed to copy profile " +
9017                                        profileFile.getAbsolutePath() + " ", e);
9018                            }
9019                        }
9020                    }
9021                }
9022            }
9023
9024            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9025                if (DEBUG_DEXOPT) {
9026                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9027                }
9028                numberOfPackagesSkipped++;
9029                continue;
9030            }
9031
9032            if (DEBUG_DEXOPT) {
9033                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9034                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9035            }
9036
9037            if (showDialog) {
9038                try {
9039                    ActivityManager.getService().showBootMessage(
9040                            mContext.getResources().getString(R.string.android_upgrading_apk,
9041                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9042                } catch (RemoteException e) {
9043                }
9044                synchronized (mPackages) {
9045                    mDexOptDialogShown = true;
9046                }
9047            }
9048
9049            int pkgCompilationReason = compilationReason;
9050            if (useProfileForDexopt) {
9051                // Use background dexopt mode to try and use the profile. Note that this does not
9052                // guarantee usage of the profile.
9053                pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT;
9054            }
9055
9056            // checkProfiles is false to avoid merging profiles during boot which
9057            // might interfere with background compilation (b/28612421).
9058            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9059            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9060            // trade-off worth doing to save boot time work.
9061            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9062            if (compilationReason == REASON_FIRST_BOOT) {
9063                // TODO: This doesn't cover the upgrade case, we should check for this too.
9064                dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE;
9065            }
9066            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9067                    pkg.packageName,
9068                    pkgCompilationReason,
9069                    dexoptFlags));
9070
9071            switch (primaryDexOptStaus) {
9072                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9073                    numberOfPackagesOptimized++;
9074                    break;
9075                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9076                    numberOfPackagesSkipped++;
9077                    break;
9078                case PackageDexOptimizer.DEX_OPT_FAILED:
9079                    numberOfPackagesFailed++;
9080                    break;
9081                default:
9082                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9083                    break;
9084            }
9085        }
9086
9087        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9088                numberOfPackagesFailed };
9089    }
9090
9091    @Override
9092    public void notifyPackageUse(String packageName, int reason) {
9093        synchronized (mPackages) {
9094            final int callingUid = Binder.getCallingUid();
9095            final int callingUserId = UserHandle.getUserId(callingUid);
9096            if (getInstantAppPackageName(callingUid) != null) {
9097                if (!isCallerSameApp(packageName, callingUid)) {
9098                    return;
9099                }
9100            } else {
9101                if (isInstantApp(packageName, callingUserId)) {
9102                    return;
9103                }
9104            }
9105            notifyPackageUseLocked(packageName, reason);
9106        }
9107    }
9108
9109    @GuardedBy("mPackages")
9110    private void notifyPackageUseLocked(String packageName, int reason) {
9111        final PackageParser.Package p = mPackages.get(packageName);
9112        if (p == null) {
9113            return;
9114        }
9115        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9116    }
9117
9118    @Override
9119    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9120            List<String> classPaths, String loaderIsa) {
9121        int userId = UserHandle.getCallingUserId();
9122        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9123        if (ai == null) {
9124            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9125                + loadingPackageName + ", user=" + userId);
9126            return;
9127        }
9128        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9129    }
9130
9131    @Override
9132    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9133            IDexModuleRegisterCallback callback) {
9134        int userId = UserHandle.getCallingUserId();
9135        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9136        DexManager.RegisterDexModuleResult result;
9137        if (ai == null) {
9138            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9139                     " calling user. package=" + packageName + ", user=" + userId);
9140            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9141        } else {
9142            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9143        }
9144
9145        if (callback != null) {
9146            mHandler.post(() -> {
9147                try {
9148                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9149                } catch (RemoteException e) {
9150                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9151                }
9152            });
9153        }
9154    }
9155
9156    /**
9157     * Ask the package manager to perform a dex-opt with the given compiler filter.
9158     *
9159     * Note: exposed only for the shell command to allow moving packages explicitly to a
9160     *       definite state.
9161     */
9162    @Override
9163    public boolean performDexOptMode(String packageName,
9164            boolean checkProfiles, String targetCompilerFilter, boolean force,
9165            boolean bootComplete, String splitName) {
9166        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9167                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9168                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9169        return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN,
9170                targetCompilerFilter, splitName, flags));
9171    }
9172
9173    /**
9174     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9175     * secondary dex files belonging to the given package.
9176     *
9177     * Note: exposed only for the shell command to allow moving packages explicitly to a
9178     *       definite state.
9179     */
9180    @Override
9181    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9182            boolean force) {
9183        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9184                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9185                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9186                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9187        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9188    }
9189
9190    /*package*/ boolean performDexOpt(DexoptOptions options) {
9191        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9192            return false;
9193        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9194            return false;
9195        }
9196
9197        if (options.isDexoptOnlySecondaryDex()) {
9198            return mDexManager.dexoptSecondaryDex(options);
9199        } else {
9200            int dexoptStatus = performDexOptWithStatus(options);
9201            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9202        }
9203    }
9204
9205    /**
9206     * Perform dexopt on the given package and return one of following result:
9207     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9208     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9209     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9210     */
9211    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9212        return performDexOptTraced(options);
9213    }
9214
9215    private int performDexOptTraced(DexoptOptions options) {
9216        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9217        try {
9218            return performDexOptInternal(options);
9219        } finally {
9220            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9221        }
9222    }
9223
9224    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9225    // if the package can now be considered up to date for the given filter.
9226    private int performDexOptInternal(DexoptOptions options) {
9227        PackageParser.Package p;
9228        synchronized (mPackages) {
9229            p = mPackages.get(options.getPackageName());
9230            if (p == null) {
9231                // Package could not be found. Report failure.
9232                return PackageDexOptimizer.DEX_OPT_FAILED;
9233            }
9234            mPackageUsage.maybeWriteAsync(mPackages);
9235            mCompilerStats.maybeWriteAsync();
9236        }
9237        long callingId = Binder.clearCallingIdentity();
9238        try {
9239            synchronized (mInstallLock) {
9240                return performDexOptInternalWithDependenciesLI(p, options);
9241            }
9242        } finally {
9243            Binder.restoreCallingIdentity(callingId);
9244        }
9245    }
9246
9247    public ArraySet<String> getOptimizablePackages() {
9248        ArraySet<String> pkgs = new ArraySet<String>();
9249        synchronized (mPackages) {
9250            for (PackageParser.Package p : mPackages.values()) {
9251                if (PackageDexOptimizer.canOptimizePackage(p)) {
9252                    pkgs.add(p.packageName);
9253                }
9254            }
9255        }
9256        return pkgs;
9257    }
9258
9259    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9260            DexoptOptions options) {
9261        // Select the dex optimizer based on the force parameter.
9262        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9263        //       allocate an object here.
9264        PackageDexOptimizer pdo = options.isForce()
9265                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9266                : mPackageDexOptimizer;
9267
9268        // Dexopt all dependencies first. Note: we ignore the return value and march on
9269        // on errors.
9270        // Note that we are going to call performDexOpt on those libraries as many times as
9271        // they are referenced in packages. When we do a batch of performDexOpt (for example
9272        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9273        // and the first package that uses the library will dexopt it. The
9274        // others will see that the compiled code for the library is up to date.
9275        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9276        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9277        if (!deps.isEmpty()) {
9278            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9279                    options.getCompilationReason(), options.getCompilerFilter(),
9280                    options.getSplitName(),
9281                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9282            for (PackageParser.Package depPackage : deps) {
9283                // TODO: Analyze and investigate if we (should) profile libraries.
9284                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9285                        getOrCreateCompilerPackageStats(depPackage),
9286                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9287            }
9288        }
9289        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9290                getOrCreateCompilerPackageStats(p),
9291                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9292    }
9293
9294    /**
9295     * Reconcile the information we have about the secondary dex files belonging to
9296     * {@code packagName} and the actual dex files. For all dex files that were
9297     * deleted, update the internal records and delete the generated oat files.
9298     */
9299    @Override
9300    public void reconcileSecondaryDexFiles(String packageName) {
9301        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9302            return;
9303        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9304            return;
9305        }
9306        mDexManager.reconcileSecondaryDexFiles(packageName);
9307    }
9308
9309    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9310    // a reference there.
9311    /*package*/ DexManager getDexManager() {
9312        return mDexManager;
9313    }
9314
9315    /**
9316     * Execute the background dexopt job immediately.
9317     */
9318    @Override
9319    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9320        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9321            return false;
9322        }
9323        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9324    }
9325
9326    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9327        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9328                || p.usesStaticLibraries != null) {
9329            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9330            Set<String> collectedNames = new HashSet<>();
9331            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9332
9333            retValue.remove(p);
9334
9335            return retValue;
9336        } else {
9337            return Collections.emptyList();
9338        }
9339    }
9340
9341    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9342            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9343        if (!collectedNames.contains(p.packageName)) {
9344            collectedNames.add(p.packageName);
9345            collected.add(p);
9346
9347            if (p.usesLibraries != null) {
9348                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9349                        null, collected, collectedNames);
9350            }
9351            if (p.usesOptionalLibraries != null) {
9352                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9353                        null, collected, collectedNames);
9354            }
9355            if (p.usesStaticLibraries != null) {
9356                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9357                        p.usesStaticLibrariesVersions, collected, collectedNames);
9358            }
9359        }
9360    }
9361
9362    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9363            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9364        final int libNameCount = libs.size();
9365        for (int i = 0; i < libNameCount; i++) {
9366            String libName = libs.get(i);
9367            long version = (versions != null && versions.length == libNameCount)
9368                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9369            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9370            if (libPkg != null) {
9371                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9372            }
9373        }
9374    }
9375
9376    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9377        synchronized (mPackages) {
9378            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9379            if (libEntry != null) {
9380                return mPackages.get(libEntry.apk);
9381            }
9382            return null;
9383        }
9384    }
9385
9386    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9387        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9388        if (versionedLib == null) {
9389            return null;
9390        }
9391        return versionedLib.get(version);
9392    }
9393
9394    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9395        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9396                pkg.staticSharedLibName);
9397        if (versionedLib == null) {
9398            return null;
9399        }
9400        long previousLibVersion = -1;
9401        final int versionCount = versionedLib.size();
9402        for (int i = 0; i < versionCount; i++) {
9403            final long libVersion = versionedLib.keyAt(i);
9404            if (libVersion < pkg.staticSharedLibVersion) {
9405                previousLibVersion = Math.max(previousLibVersion, libVersion);
9406            }
9407        }
9408        if (previousLibVersion >= 0) {
9409            return versionedLib.get(previousLibVersion);
9410        }
9411        return null;
9412    }
9413
9414    public void shutdown() {
9415        mPackageUsage.writeNow(mPackages);
9416        mCompilerStats.writeNow();
9417        mDexManager.writePackageDexUsageNow();
9418    }
9419
9420    @Override
9421    public void dumpProfiles(String packageName) {
9422        PackageParser.Package pkg;
9423        synchronized (mPackages) {
9424            pkg = mPackages.get(packageName);
9425            if (pkg == null) {
9426                throw new IllegalArgumentException("Unknown package: " + packageName);
9427            }
9428        }
9429        /* Only the shell, root, or the app user should be able to dump profiles. */
9430        int callingUid = Binder.getCallingUid();
9431        if (callingUid != Process.SHELL_UID &&
9432            callingUid != Process.ROOT_UID &&
9433            callingUid != pkg.applicationInfo.uid) {
9434            throw new SecurityException("dumpProfiles");
9435        }
9436
9437        synchronized (mInstallLock) {
9438            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9439            mArtManagerService.dumpProfiles(pkg);
9440            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9441        }
9442    }
9443
9444    @Override
9445    public void forceDexOpt(String packageName) {
9446        enforceSystemOrRoot("forceDexOpt");
9447
9448        PackageParser.Package pkg;
9449        synchronized (mPackages) {
9450            pkg = mPackages.get(packageName);
9451            if (pkg == null) {
9452                throw new IllegalArgumentException("Unknown package: " + packageName);
9453            }
9454        }
9455
9456        synchronized (mInstallLock) {
9457            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9458
9459            // Whoever is calling forceDexOpt wants a compiled package.
9460            // Don't use profiles since that may cause compilation to be skipped.
9461            final int res = performDexOptInternalWithDependenciesLI(
9462                    pkg,
9463                    new DexoptOptions(packageName,
9464                            getDefaultCompilerFilter(),
9465                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9466
9467            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9468            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9469                throw new IllegalStateException("Failed to dexopt: " + res);
9470            }
9471        }
9472    }
9473
9474    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9475        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9476            Slog.w(TAG, "Unable to update from " + oldPkg.name
9477                    + " to " + newPkg.packageName
9478                    + ": old package not in system partition");
9479            return false;
9480        } else if (mPackages.get(oldPkg.name) != null) {
9481            Slog.w(TAG, "Unable to update from " + oldPkg.name
9482                    + " to " + newPkg.packageName
9483                    + ": old package still exists");
9484            return false;
9485        }
9486        return true;
9487    }
9488
9489    void removeCodePathLI(File codePath) {
9490        if (codePath.isDirectory()) {
9491            try {
9492                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9493            } catch (InstallerException e) {
9494                Slog.w(TAG, "Failed to remove code path", e);
9495            }
9496        } else {
9497            codePath.delete();
9498        }
9499    }
9500
9501    private int[] resolveUserIds(int userId) {
9502        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9503    }
9504
9505    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9506        if (pkg == null) {
9507            Slog.wtf(TAG, "Package was null!", new Throwable());
9508            return;
9509        }
9510        clearAppDataLeafLIF(pkg, userId, flags);
9511        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9512        for (int i = 0; i < childCount; i++) {
9513            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9514        }
9515
9516        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9517    }
9518
9519    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9520        final PackageSetting ps;
9521        synchronized (mPackages) {
9522            ps = mSettings.mPackages.get(pkg.packageName);
9523        }
9524        for (int realUserId : resolveUserIds(userId)) {
9525            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9526            try {
9527                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9528                        ceDataInode);
9529            } catch (InstallerException e) {
9530                Slog.w(TAG, String.valueOf(e));
9531            }
9532        }
9533    }
9534
9535    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9536        if (pkg == null) {
9537            Slog.wtf(TAG, "Package was null!", new Throwable());
9538            return;
9539        }
9540        destroyAppDataLeafLIF(pkg, userId, flags);
9541        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9542        for (int i = 0; i < childCount; i++) {
9543            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9544        }
9545    }
9546
9547    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9548        final PackageSetting ps;
9549        synchronized (mPackages) {
9550            ps = mSettings.mPackages.get(pkg.packageName);
9551        }
9552        for (int realUserId : resolveUserIds(userId)) {
9553            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9554            try {
9555                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9556                        ceDataInode);
9557            } catch (InstallerException e) {
9558                Slog.w(TAG, String.valueOf(e));
9559            }
9560            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9561        }
9562    }
9563
9564    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9565        if (pkg == null) {
9566            Slog.wtf(TAG, "Package was null!", new Throwable());
9567            return;
9568        }
9569        destroyAppProfilesLeafLIF(pkg);
9570        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9571        for (int i = 0; i < childCount; i++) {
9572            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9573        }
9574    }
9575
9576    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9577        try {
9578            mInstaller.destroyAppProfiles(pkg.packageName);
9579        } catch (InstallerException e) {
9580            Slog.w(TAG, String.valueOf(e));
9581        }
9582    }
9583
9584    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9585        if (pkg == null) {
9586            Slog.wtf(TAG, "Package was null!", new Throwable());
9587            return;
9588        }
9589        mArtManagerService.clearAppProfiles(pkg);
9590        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9591        for (int i = 0; i < childCount; i++) {
9592            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9593        }
9594    }
9595
9596    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9597            long lastUpdateTime) {
9598        // Set parent install/update time
9599        PackageSetting ps = (PackageSetting) pkg.mExtras;
9600        if (ps != null) {
9601            ps.firstInstallTime = firstInstallTime;
9602            ps.lastUpdateTime = lastUpdateTime;
9603        }
9604        // Set children install/update time
9605        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9606        for (int i = 0; i < childCount; i++) {
9607            PackageParser.Package childPkg = pkg.childPackages.get(i);
9608            ps = (PackageSetting) childPkg.mExtras;
9609            if (ps != null) {
9610                ps.firstInstallTime = firstInstallTime;
9611                ps.lastUpdateTime = lastUpdateTime;
9612            }
9613        }
9614    }
9615
9616    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9617            SharedLibraryEntry file,
9618            PackageParser.Package changingLib) {
9619        if (file.path != null) {
9620            usesLibraryFiles.add(file.path);
9621            return;
9622        }
9623        PackageParser.Package p = mPackages.get(file.apk);
9624        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9625            // If we are doing this while in the middle of updating a library apk,
9626            // then we need to make sure to use that new apk for determining the
9627            // dependencies here.  (We haven't yet finished committing the new apk
9628            // to the package manager state.)
9629            if (p == null || p.packageName.equals(changingLib.packageName)) {
9630                p = changingLib;
9631            }
9632        }
9633        if (p != null) {
9634            usesLibraryFiles.addAll(p.getAllCodePaths());
9635            if (p.usesLibraryFiles != null) {
9636                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9637            }
9638        }
9639    }
9640
9641    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9642            PackageParser.Package changingLib) throws PackageManagerException {
9643        if (pkg == null) {
9644            return;
9645        }
9646        // The collection used here must maintain the order of addition (so
9647        // that libraries are searched in the correct order) and must have no
9648        // duplicates.
9649        Set<String> usesLibraryFiles = null;
9650        if (pkg.usesLibraries != null) {
9651            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9652                    null, null, pkg.packageName, changingLib, true,
9653                    pkg.applicationInfo.targetSdkVersion, null);
9654        }
9655        if (pkg.usesStaticLibraries != null) {
9656            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9657                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9658                    pkg.packageName, changingLib, true,
9659                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9660        }
9661        if (pkg.usesOptionalLibraries != null) {
9662            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9663                    null, null, pkg.packageName, changingLib, false,
9664                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9665        }
9666        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9667            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9668        } else {
9669            pkg.usesLibraryFiles = null;
9670        }
9671    }
9672
9673    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9674            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9675            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9676            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9677            throws PackageManagerException {
9678        final int libCount = requestedLibraries.size();
9679        for (int i = 0; i < libCount; i++) {
9680            final String libName = requestedLibraries.get(i);
9681            final long libVersion = requiredVersions != null ? requiredVersions[i]
9682                    : SharedLibraryInfo.VERSION_UNDEFINED;
9683            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9684            if (libEntry == null) {
9685                if (required) {
9686                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9687                            "Package " + packageName + " requires unavailable shared library "
9688                                    + libName + "; failing!");
9689                } else if (DEBUG_SHARED_LIBRARIES) {
9690                    Slog.i(TAG, "Package " + packageName
9691                            + " desires unavailable shared library "
9692                            + libName + "; ignoring!");
9693                }
9694            } else {
9695                if (requiredVersions != null && requiredCertDigests != null) {
9696                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9697                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9698                            "Package " + packageName + " requires unavailable static shared"
9699                                    + " library " + libName + " version "
9700                                    + libEntry.info.getLongVersion() + "; failing!");
9701                    }
9702
9703                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9704                    if (libPkg == null) {
9705                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9706                                "Package " + packageName + " requires unavailable static shared"
9707                                        + " library; failing!");
9708                    }
9709
9710                    final String[] expectedCertDigests = requiredCertDigests[i];
9711
9712
9713                    if (expectedCertDigests.length > 1) {
9714
9715                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9716                        final String[] libCertDigests = (targetSdk >= Build.VERSION_CODES.O_MR1)
9717                                ? PackageUtils.computeSignaturesSha256Digests(
9718                                libPkg.mSigningDetails.signatures)
9719                                : PackageUtils.computeSignaturesSha256Digests(
9720                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9721
9722                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9723                        // target O we don't parse the "additional-certificate" tags similarly
9724                        // how we only consider all certs only for apps targeting O (see above).
9725                        // Therefore, the size check is safe to make.
9726                        if (expectedCertDigests.length != libCertDigests.length) {
9727                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9728                                    "Package " + packageName + " requires differently signed" +
9729                                            " static shared library; failing!");
9730                        }
9731
9732                        // Use a predictable order as signature order may vary
9733                        Arrays.sort(libCertDigests);
9734                        Arrays.sort(expectedCertDigests);
9735
9736                        final int certCount = libCertDigests.length;
9737                        for (int j = 0; j < certCount; j++) {
9738                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9739                                throw new PackageManagerException(
9740                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9741                                        "Package " + packageName + " requires differently signed" +
9742                                                " static shared library; failing!");
9743                            }
9744                        }
9745                    } else {
9746
9747                        // lib signing cert could have rotated beyond the one expected, check to see
9748                        // if the new one has been blessed by the old
9749                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9750                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9751                            throw new PackageManagerException(
9752                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9753                                    "Package " + packageName + " requires differently signed" +
9754                                            " static shared library; failing!");
9755                        }
9756                    }
9757                }
9758
9759                if (outUsedLibraries == null) {
9760                    // Use LinkedHashSet to preserve the order of files added to
9761                    // usesLibraryFiles while eliminating duplicates.
9762                    outUsedLibraries = new LinkedHashSet<>();
9763                }
9764                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9765            }
9766        }
9767        return outUsedLibraries;
9768    }
9769
9770    private static boolean hasString(List<String> list, List<String> which) {
9771        if (list == null) {
9772            return false;
9773        }
9774        for (int i=list.size()-1; i>=0; i--) {
9775            for (int j=which.size()-1; j>=0; j--) {
9776                if (which.get(j).equals(list.get(i))) {
9777                    return true;
9778                }
9779            }
9780        }
9781        return false;
9782    }
9783
9784    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9785            PackageParser.Package changingPkg) {
9786        ArrayList<PackageParser.Package> res = null;
9787        for (PackageParser.Package pkg : mPackages.values()) {
9788            if (changingPkg != null
9789                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9790                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9791                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9792                            changingPkg.staticSharedLibName)) {
9793                return null;
9794            }
9795            if (res == null) {
9796                res = new ArrayList<>();
9797            }
9798            res.add(pkg);
9799            try {
9800                updateSharedLibrariesLPr(pkg, changingPkg);
9801            } catch (PackageManagerException e) {
9802                // If a system app update or an app and a required lib missing we
9803                // delete the package and for updated system apps keep the data as
9804                // it is better for the user to reinstall than to be in an limbo
9805                // state. Also libs disappearing under an app should never happen
9806                // - just in case.
9807                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9808                    final int flags = pkg.isUpdatedSystemApp()
9809                            ? PackageManager.DELETE_KEEP_DATA : 0;
9810                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9811                            flags , null, true, null);
9812                }
9813                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9814            }
9815        }
9816        return res;
9817    }
9818
9819    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9820            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9821            @Nullable UserHandle user) throws PackageManagerException {
9822        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9823        // If the package has children and this is the first dive in the function
9824        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9825        // whether all packages (parent and children) would be successfully scanned
9826        // before the actual scan since scanning mutates internal state and we want
9827        // to atomically install the package and its children.
9828        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9829            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9830                scanFlags |= SCAN_CHECK_ONLY;
9831            }
9832        } else {
9833            scanFlags &= ~SCAN_CHECK_ONLY;
9834        }
9835
9836        final PackageParser.Package scannedPkg;
9837        try {
9838            // Scan the parent
9839            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9840            // Scan the children
9841            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9842            for (int i = 0; i < childCount; i++) {
9843                PackageParser.Package childPkg = pkg.childPackages.get(i);
9844                scanPackageNewLI(childPkg, parseFlags,
9845                        scanFlags, currentTime, user);
9846            }
9847        } finally {
9848            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9849        }
9850
9851        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9852            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9853        }
9854
9855        return scannedPkg;
9856    }
9857
9858    /** The result of a package scan. */
9859    private static class ScanResult {
9860        /** Whether or not the package scan was successful */
9861        public final boolean success;
9862        /**
9863         * The final package settings. This may be the same object passed in
9864         * the {@link ScanRequest}, but, with modified values.
9865         */
9866        @Nullable public final PackageSetting pkgSetting;
9867        /** ABI code paths that have changed in the package scan */
9868        @Nullable public final List<String> changedAbiCodePath;
9869        public ScanResult(
9870                boolean success,
9871                @Nullable PackageSetting pkgSetting,
9872                @Nullable List<String> changedAbiCodePath) {
9873            this.success = success;
9874            this.pkgSetting = pkgSetting;
9875            this.changedAbiCodePath = changedAbiCodePath;
9876        }
9877    }
9878
9879    /** A package to be scanned */
9880    private static class ScanRequest {
9881        /** The parsed package */
9882        @NonNull public final PackageParser.Package pkg;
9883        /** The package this package replaces */
9884        @Nullable public final PackageParser.Package oldPkg;
9885        /** Shared user settings, if the package has a shared user */
9886        @Nullable public final SharedUserSetting sharedUserSetting;
9887        /**
9888         * Package settings of the currently installed version.
9889         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9890         * during scan.
9891         */
9892        @Nullable public final PackageSetting pkgSetting;
9893        /** A copy of the settings for the currently installed version */
9894        @Nullable public final PackageSetting oldPkgSetting;
9895        /** Package settings for the disabled version on the /system partition */
9896        @Nullable public final PackageSetting disabledPkgSetting;
9897        /** Package settings for the installed version under its original package name */
9898        @Nullable public final PackageSetting originalPkgSetting;
9899        /** The real package name of a renamed application */
9900        @Nullable public final String realPkgName;
9901        public final @ParseFlags int parseFlags;
9902        public final @ScanFlags int scanFlags;
9903        /** The user for which the package is being scanned */
9904        @Nullable public final UserHandle user;
9905        /** Whether or not the platform package is being scanned */
9906        public final boolean isPlatformPackage;
9907        public ScanRequest(
9908                @NonNull PackageParser.Package pkg,
9909                @Nullable SharedUserSetting sharedUserSetting,
9910                @Nullable PackageParser.Package oldPkg,
9911                @Nullable PackageSetting pkgSetting,
9912                @Nullable PackageSetting disabledPkgSetting,
9913                @Nullable PackageSetting originalPkgSetting,
9914                @Nullable String realPkgName,
9915                @ParseFlags int parseFlags,
9916                @ScanFlags int scanFlags,
9917                boolean isPlatformPackage,
9918                @Nullable UserHandle user) {
9919            this.pkg = pkg;
9920            this.oldPkg = oldPkg;
9921            this.pkgSetting = pkgSetting;
9922            this.sharedUserSetting = sharedUserSetting;
9923            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9924            this.disabledPkgSetting = disabledPkgSetting;
9925            this.originalPkgSetting = originalPkgSetting;
9926            this.realPkgName = realPkgName;
9927            this.parseFlags = parseFlags;
9928            this.scanFlags = scanFlags;
9929            this.isPlatformPackage = isPlatformPackage;
9930            this.user = user;
9931        }
9932    }
9933
9934    /**
9935     * Returns the actual scan flags depending upon the state of the other settings.
9936     * <p>Updated system applications will not have the following flags set
9937     * by default and need to be adjusted after the fact:
9938     * <ul>
9939     * <li>{@link #SCAN_AS_SYSTEM}</li>
9940     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9941     * <li>{@link #SCAN_AS_OEM}</li>
9942     * <li>{@link #SCAN_AS_VENDOR}</li>
9943     * <li>{@link #SCAN_AS_PRODUCT}</li>
9944     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9945     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9946     * </ul>
9947     */
9948    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9949            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9950            PackageParser.Package pkg) {
9951        if (disabledPkgSetting != null) {
9952            // updated system application, must at least have SCAN_AS_SYSTEM
9953            scanFlags |= SCAN_AS_SYSTEM;
9954            if ((disabledPkgSetting.pkgPrivateFlags
9955                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9956                scanFlags |= SCAN_AS_PRIVILEGED;
9957            }
9958            if ((disabledPkgSetting.pkgPrivateFlags
9959                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9960                scanFlags |= SCAN_AS_OEM;
9961            }
9962            if ((disabledPkgSetting.pkgPrivateFlags
9963                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9964                scanFlags |= SCAN_AS_VENDOR;
9965            }
9966            if ((disabledPkgSetting.pkgPrivateFlags
9967                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9968                scanFlags |= SCAN_AS_PRODUCT;
9969            }
9970        }
9971        if (pkgSetting != null) {
9972            final int userId = ((user == null) ? 0 : user.getIdentifier());
9973            if (pkgSetting.getInstantApp(userId)) {
9974                scanFlags |= SCAN_AS_INSTANT_APP;
9975            }
9976            if (pkgSetting.getVirtulalPreload(userId)) {
9977                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9978            }
9979        }
9980
9981        // Scan as privileged apps that share a user with a priv-app.
9982        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9983                && (pkg.mSharedUserId != null)) {
9984            SharedUserSetting sharedUserSetting = null;
9985            try {
9986                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9987            } catch (PackageManagerException ignore) {}
9988            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9989                // Exempt SharedUsers signed with the platform key.
9990                // TODO(b/72378145) Fix this exemption. Force signature apps
9991                // to whitelist their privileged permissions just like other
9992                // priv-apps.
9993                synchronized (mPackages) {
9994                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9995                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
9996                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
9997                        scanFlags |= SCAN_AS_PRIVILEGED;
9998                    }
9999                }
10000            }
10001        }
10002
10003        return scanFlags;
10004    }
10005
10006    // TODO: scanPackageNewLI() and scanPackageOnly() should be merged. But, first, commiting
10007    // the results / removing app data needs to be moved up a level to the callers of this
10008    // method. Also, we need to solve the problem of potentially creating a new shared user
10009    // setting. That can probably be done later and patch things up after the fact.
10010    @GuardedBy("mInstallLock")
10011    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
10012            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
10013            @Nullable UserHandle user) throws PackageManagerException {
10014
10015        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10016        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
10017        if (realPkgName != null) {
10018            ensurePackageRenamed(pkg, renamedPkgName);
10019        }
10020        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
10021        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10022        final PackageSetting disabledPkgSetting =
10023                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10024
10025        if (mTransferedPackages.contains(pkg.packageName)) {
10026            Slog.w(TAG, "Package " + pkg.packageName
10027                    + " was transferred to another, but its .apk remains");
10028        }
10029
10030        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
10031        synchronized (mPackages) {
10032            applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage);
10033            assertPackageIsValid(pkg, parseFlags, scanFlags);
10034
10035            SharedUserSetting sharedUserSetting = null;
10036            if (pkg.mSharedUserId != null) {
10037                // SIDE EFFECTS; may potentially allocate a new shared user
10038                sharedUserSetting = mSettings.getSharedUserLPw(
10039                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10040                if (DEBUG_PACKAGE_SCANNING) {
10041                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10042                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
10043                                + " (uid=" + sharedUserSetting.userId + "):"
10044                                + " packages=" + sharedUserSetting.packages);
10045                }
10046            }
10047
10048            boolean scanSucceeded = false;
10049            try {
10050                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
10051                        pkgSetting == null ? null : pkgSetting.pkg, pkgSetting, disabledPkgSetting,
10052                        originalPkgSetting, realPkgName, parseFlags, scanFlags,
10053                        (pkg == mPlatformPackage), user);
10054                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
10055                if (result.success) {
10056                    commitScanResultsLocked(request, result);
10057                }
10058                scanSucceeded = true;
10059            } finally {
10060                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10061                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
10062                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10063                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10064                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10065                  }
10066            }
10067        }
10068        return pkg;
10069    }
10070
10071    /**
10072     * Commits the package scan and modifies system state.
10073     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
10074     * of committing the package, leaving the system in an inconsistent state.
10075     * This needs to be fixed so, once we get to this point, no errors are
10076     * possible and the system is not left in an inconsistent state.
10077     */
10078    @GuardedBy("mPackages")
10079    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
10080            throws PackageManagerException {
10081        final PackageParser.Package pkg = request.pkg;
10082        final PackageParser.Package oldPkg = request.oldPkg;
10083        final @ParseFlags int parseFlags = request.parseFlags;
10084        final @ScanFlags int scanFlags = request.scanFlags;
10085        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10086        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10087        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10088        final UserHandle user = request.user;
10089        final String realPkgName = request.realPkgName;
10090        final PackageSetting pkgSetting = result.pkgSetting;
10091        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10092        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10093
10094        if (newPkgSettingCreated) {
10095            if (originalPkgSetting != null) {
10096                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10097            }
10098            // THROWS: when we can't allocate a user id. add call to check if there's
10099            // enough space to ensure we won't throw; otherwise, don't modify state
10100            mSettings.addUserToSettingLPw(pkgSetting);
10101
10102            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10103                mTransferedPackages.add(originalPkgSetting.name);
10104            }
10105        }
10106        // TODO(toddke): Consider a method specifically for modifying the Package object
10107        // post scan; or, moving this stuff out of the Package object since it has nothing
10108        // to do with the package on disk.
10109        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10110        // for creating the application ID. If we did this earlier, we would be saving the
10111        // correct ID.
10112        pkg.applicationInfo.uid = pkgSetting.appId;
10113
10114        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10115
10116        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10117            mTransferedPackages.add(pkg.packageName);
10118        }
10119
10120        // THROWS: when requested libraries that can't be found. it only changes
10121        // the state of the passed in pkg object, so, move to the top of the method
10122        // and allow it to abort
10123        if ((scanFlags & SCAN_BOOTING) == 0
10124                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10125            // Check all shared libraries and map to their actual file path.
10126            // We only do this here for apps not on a system dir, because those
10127            // are the only ones that can fail an install due to this.  We
10128            // will take care of the system apps by updating all of their
10129            // library paths after the scan is done. Also during the initial
10130            // scan don't update any libs as we do this wholesale after all
10131            // apps are scanned to avoid dependency based scanning.
10132            updateSharedLibrariesLPr(pkg, null);
10133        }
10134
10135        // All versions of a static shared library are referenced with the same
10136        // package name. Internally, we use a synthetic package name to allow
10137        // multiple versions of the same shared library to be installed. So,
10138        // we need to generate the synthetic package name of the latest shared
10139        // library in order to compare signatures.
10140        PackageSetting signatureCheckPs = pkgSetting;
10141        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10142            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10143            if (libraryEntry != null) {
10144                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10145            }
10146        }
10147
10148        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10149        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10150            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10151                // We just determined the app is signed correctly, so bring
10152                // over the latest parsed certs.
10153                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10154            } else {
10155                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10156                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10157                            "Package " + pkg.packageName + " upgrade keys do not match the "
10158                                    + "previously installed version");
10159                } else {
10160                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10161                    String msg = "System package " + pkg.packageName
10162                            + " signature changed; retaining data.";
10163                    reportSettingsProblem(Log.WARN, msg);
10164                }
10165            }
10166        } else {
10167            try {
10168                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10169                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10170                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10171                        pkg.mSigningDetails, compareCompat, compareRecover);
10172                // The new KeySets will be re-added later in the scanning process.
10173                if (compatMatch) {
10174                    synchronized (mPackages) {
10175                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10176                    }
10177                }
10178                // We just determined the app is signed correctly, so bring
10179                // over the latest parsed certs.
10180                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10181
10182
10183                // if this is is a sharedUser, check to see if the new package is signed by a newer
10184                // signing certificate than the existing one, and if so, copy over the new details
10185                if (signatureCheckPs.sharedUser != null
10186                        && pkg.mSigningDetails.hasAncestor(
10187                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10188                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10189                }
10190            } catch (PackageManagerException e) {
10191                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10192                    throw e;
10193                }
10194                // The signature has changed, but this package is in the system
10195                // image...  let's recover!
10196                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10197                // If the system app is part of a shared user we allow that shared user to change
10198                // signatures as well in part as part of an OTA.
10199                if (signatureCheckPs.sharedUser != null) {
10200                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10201                }
10202                // File a report about this.
10203                String msg = "System package " + pkg.packageName
10204                        + " signature changed; retaining data.";
10205                reportSettingsProblem(Log.WARN, msg);
10206            } catch (IllegalArgumentException e) {
10207
10208                // should never happen: certs matched when checking, but not when comparing
10209                // old to new for sharedUser
10210                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10211                        "Signing certificates comparison made on incomparable signing details"
10212                        + " but somehow passed verifySignatures!");
10213            }
10214        }
10215
10216        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10217            // This package wants to adopt ownership of permissions from
10218            // another package.
10219            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10220                final String origName = pkg.mAdoptPermissions.get(i);
10221                final PackageSetting orig = mSettings.getPackageLPr(origName);
10222                if (orig != null) {
10223                    if (verifyPackageUpdateLPr(orig, pkg)) {
10224                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10225                                + pkg.packageName);
10226                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10227                    }
10228                }
10229            }
10230        }
10231
10232        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10233            for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
10234                final String codePathString = changedAbiCodePath.get(i);
10235                try {
10236                    mInstaller.rmdex(codePathString,
10237                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10238                } catch (InstallerException ignored) {
10239                }
10240            }
10241        }
10242
10243        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10244            if (oldPkgSetting != null) {
10245                synchronized (mPackages) {
10246                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10247                }
10248            }
10249        } else {
10250            final int userId = user == null ? 0 : user.getIdentifier();
10251            // Modify state for the given package setting
10252            commitPackageSettings(pkg, oldPkg, pkgSetting, user, scanFlags,
10253                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10254            if (pkgSetting.getInstantApp(userId)) {
10255                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10256            }
10257        }
10258    }
10259
10260    /**
10261     * Returns the "real" name of the package.
10262     * <p>This may differ from the package's actual name if the application has already
10263     * been installed under one of this package's original names.
10264     */
10265    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10266            @Nullable String renamedPkgName) {
10267        if (isPackageRenamed(pkg, renamedPkgName)) {
10268            return pkg.mRealPackage;
10269        }
10270        return null;
10271    }
10272
10273    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10274    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10275            @Nullable String renamedPkgName) {
10276        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10277    }
10278
10279    /**
10280     * Returns the original package setting.
10281     * <p>A package can migrate its name during an update. In this scenario, a package
10282     * designates a set of names that it considers as one of its original names.
10283     * <p>An original package must be signed identically and it must have the same
10284     * shared user [if any].
10285     */
10286    @GuardedBy("mPackages")
10287    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10288            @Nullable String renamedPkgName) {
10289        if (!isPackageRenamed(pkg, renamedPkgName)) {
10290            return null;
10291        }
10292        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10293            final PackageSetting originalPs =
10294                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10295            if (originalPs != null) {
10296                // the package is already installed under its original name...
10297                // but, should we use it?
10298                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10299                    // the new package is incompatible with the original
10300                    continue;
10301                } else if (originalPs.sharedUser != null) {
10302                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10303                        // the shared user id is incompatible with the original
10304                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10305                                + " to " + pkg.packageName + ": old uid "
10306                                + originalPs.sharedUser.name
10307                                + " differs from " + pkg.mSharedUserId);
10308                        continue;
10309                    }
10310                    // TODO: Add case when shared user id is added [b/28144775]
10311                } else {
10312                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10313                            + pkg.packageName + " to old name " + originalPs.name);
10314                }
10315                return originalPs;
10316            }
10317        }
10318        return null;
10319    }
10320
10321    /**
10322     * Renames the package if it was installed under a different name.
10323     * <p>When we've already installed the package under an original name, update
10324     * the new package so we can continue to have the old name.
10325     */
10326    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10327            @NonNull String renamedPackageName) {
10328        if (pkg.mOriginalPackages == null
10329                || !pkg.mOriginalPackages.contains(renamedPackageName)
10330                || pkg.packageName.equals(renamedPackageName)) {
10331            return;
10332        }
10333        pkg.setPackageName(renamedPackageName);
10334    }
10335
10336    /**
10337     * Just scans the package without any side effects.
10338     * <p>Not entirely true at the moment. There is still one side effect -- this
10339     * method potentially modifies a live {@link PackageSetting} object representing
10340     * the package being scanned. This will be resolved in the future.
10341     *
10342     * @param request Information about the package to be scanned
10343     * @param isUnderFactoryTest Whether or not the device is under factory test
10344     * @param currentTime The current time, in millis
10345     * @return The results of the scan
10346     */
10347    @GuardedBy("mInstallLock")
10348    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10349            boolean isUnderFactoryTest, long currentTime)
10350                    throws PackageManagerException {
10351        final PackageParser.Package pkg = request.pkg;
10352        PackageSetting pkgSetting = request.pkgSetting;
10353        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10354        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10355        final @ParseFlags int parseFlags = request.parseFlags;
10356        final @ScanFlags int scanFlags = request.scanFlags;
10357        final String realPkgName = request.realPkgName;
10358        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10359        final UserHandle user = request.user;
10360        final boolean isPlatformPackage = request.isPlatformPackage;
10361
10362        List<String> changedAbiCodePath = null;
10363
10364        if (DEBUG_PACKAGE_SCANNING) {
10365            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10366                Log.d(TAG, "Scanning package " + pkg.packageName);
10367        }
10368
10369        if (Build.IS_DEBUGGABLE &&
10370                pkg.isPrivileged() &&
10371                SystemProperties.getBoolean(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, false)) {
10372            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10373        }
10374
10375        // Initialize package source and resource directories
10376        final File scanFile = new File(pkg.codePath);
10377        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10378        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10379
10380        // We keep references to the derived CPU Abis from settings in oder to reuse
10381        // them in the case where we're not upgrading or booting for the first time.
10382        String primaryCpuAbiFromSettings = null;
10383        String secondaryCpuAbiFromSettings = null;
10384        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10385
10386        if (!needToDeriveAbi) {
10387            if (pkgSetting != null) {
10388                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10389                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10390            } else {
10391                // Re-scanning a system package after uninstalling updates; need to derive ABI
10392                needToDeriveAbi = true;
10393            }
10394        }
10395
10396        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10397            PackageManagerService.reportSettingsProblem(Log.WARN,
10398                    "Package " + pkg.packageName + " shared user changed from "
10399                            + (pkgSetting.sharedUser != null
10400                            ? pkgSetting.sharedUser.name : "<nothing>")
10401                            + " to "
10402                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10403                            + "; replacing with new");
10404            pkgSetting = null;
10405        }
10406
10407        String[] usesStaticLibraries = null;
10408        if (pkg.usesStaticLibraries != null) {
10409            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10410            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10411        }
10412        final boolean createNewPackage = (pkgSetting == null);
10413        if (createNewPackage) {
10414            final String parentPackageName = (pkg.parentPackage != null)
10415                    ? pkg.parentPackage.packageName : null;
10416            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10417            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10418            // REMOVE SharedUserSetting from method; update in a separate call
10419            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10420                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10421                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10422                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10423                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10424                    user, true /*allowInstall*/, instantApp, virtualPreload,
10425                    parentPackageName, pkg.getChildPackageNames(),
10426                    UserManagerService.getInstance(), usesStaticLibraries,
10427                    pkg.usesStaticLibrariesVersions);
10428        } else {
10429            // REMOVE SharedUserSetting from method; update in a separate call.
10430            //
10431            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10432            // secondaryCpuAbi are not known at this point so we always update them
10433            // to null here, only to reset them at a later point.
10434            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10435                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10436                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10437                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10438                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10439                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10440        }
10441        if (createNewPackage && originalPkgSetting != null) {
10442            // This is the initial transition from the original package, so,
10443            // fix up the new package's name now. We must do this after looking
10444            // up the package under its new name, so getPackageLP takes care of
10445            // fiddling things correctly.
10446            pkg.setPackageName(originalPkgSetting.name);
10447
10448            // File a report about this.
10449            String msg = "New package " + pkgSetting.realName
10450                    + " renamed to replace old package " + pkgSetting.name;
10451            reportSettingsProblem(Log.WARN, msg);
10452        }
10453
10454        final int userId = (user == null ? UserHandle.USER_SYSTEM : user.getIdentifier());
10455        // for existing packages, change the install state; but, only if it's explicitly specified
10456        if (!createNewPackage) {
10457            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10458            final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
10459            setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
10460        }
10461
10462        if (disabledPkgSetting != null) {
10463            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10464        }
10465
10466        // Apps which share a sharedUserId must be placed in the same selinux domain. If this
10467        // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its
10468        // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be
10469        // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the
10470        // least restrictive selinux domain.
10471        // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion
10472        // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This
10473        // ensures that all packages continue to run in the same selinux domain.
10474        final int targetSdkVersion =
10475            ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ?
10476            sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion;
10477        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10478        // They currently can be if the sharedUser apps are signed with the platform key.
10479        final boolean isPrivileged = (sharedUserSetting != null) ?
10480            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10481
10482        pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged,
10483                pkg.applicationInfo.targetSandboxVersion, targetSdkVersion);
10484        pkg.applicationInfo.seInfoUser = SELinuxUtil.assignSeinfoUser(pkgSetting.readUserState(
10485                userId == UserHandle.USER_ALL ? UserHandle.USER_SYSTEM : userId));
10486
10487        pkg.mExtras = pkgSetting;
10488        pkg.applicationInfo.processName = fixProcessName(
10489                pkg.applicationInfo.packageName,
10490                pkg.applicationInfo.processName);
10491
10492        if (!isPlatformPackage) {
10493            // Get all of our default paths setup
10494            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10495        }
10496
10497        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10498
10499        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10500            if (needToDeriveAbi) {
10501                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10502                final boolean extractNativeLibs = !pkg.isLibrary();
10503                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10504                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10505
10506                // Some system apps still use directory structure for native libraries
10507                // in which case we might end up not detecting abi solely based on apk
10508                // structure. Try to detect abi based on directory structure.
10509                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10510                        pkg.applicationInfo.primaryCpuAbi == null) {
10511                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10512                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10513                }
10514            } else {
10515                // This is not a first boot or an upgrade, don't bother deriving the
10516                // ABI during the scan. Instead, trust the value that was stored in the
10517                // package setting.
10518                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10519                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10520
10521                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10522
10523                if (DEBUG_ABI_SELECTION) {
10524                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10525                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10526                            pkg.applicationInfo.secondaryCpuAbi);
10527                }
10528            }
10529        } else {
10530            if ((scanFlags & SCAN_MOVE) != 0) {
10531                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10532                // but we already have this packages package info in the PackageSetting. We just
10533                // use that and derive the native library path based on the new codepath.
10534                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10535                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10536            }
10537
10538            // Set native library paths again. For moves, the path will be updated based on the
10539            // ABIs we've determined above. For non-moves, the path will be updated based on the
10540            // ABIs we determined during compilation, but the path will depend on the final
10541            // package path (after the rename away from the stage path).
10542            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10543        }
10544
10545        // This is a special case for the "system" package, where the ABI is
10546        // dictated by the zygote configuration (and init.rc). We should keep track
10547        // of this ABI so that we can deal with "normal" applications that run under
10548        // the same UID correctly.
10549        if (isPlatformPackage) {
10550            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10551                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10552        }
10553
10554        // If there's a mismatch between the abi-override in the package setting
10555        // and the abiOverride specified for the install. Warn about this because we
10556        // would've already compiled the app without taking the package setting into
10557        // account.
10558        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10559            if (cpuAbiOverride == null && pkg.packageName != null) {
10560                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10561                        " for package " + pkg.packageName);
10562            }
10563        }
10564
10565        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10566        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10567        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10568
10569        // Copy the derived override back to the parsed package, so that we can
10570        // update the package settings accordingly.
10571        pkg.cpuAbiOverride = cpuAbiOverride;
10572
10573        if (DEBUG_ABI_SELECTION) {
10574            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10575                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10576                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10577        }
10578
10579        // Push the derived path down into PackageSettings so we know what to
10580        // clean up at uninstall time.
10581        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10582
10583        if (DEBUG_ABI_SELECTION) {
10584            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10585                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10586                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10587        }
10588
10589        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10590            // We don't do this here during boot because we can do it all
10591            // at once after scanning all existing packages.
10592            //
10593            // We also do this *before* we perform dexopt on this package, so that
10594            // we can avoid redundant dexopts, and also to make sure we've got the
10595            // code and package path correct.
10596            changedAbiCodePath =
10597                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10598        }
10599
10600        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10601                android.Manifest.permission.FACTORY_TEST)) {
10602            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10603        }
10604
10605        if (isSystemApp(pkg)) {
10606            pkgSetting.isOrphaned = true;
10607        }
10608
10609        // Take care of first install / last update times.
10610        final long scanFileTime = getLastModifiedTime(pkg);
10611        if (currentTime != 0) {
10612            if (pkgSetting.firstInstallTime == 0) {
10613                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10614            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10615                pkgSetting.lastUpdateTime = currentTime;
10616            }
10617        } else if (pkgSetting.firstInstallTime == 0) {
10618            // We need *something*.  Take time time stamp of the file.
10619            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10620        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10621            if (scanFileTime != pkgSetting.timeStamp) {
10622                // A package on the system image has changed; consider this
10623                // to be an update.
10624                pkgSetting.lastUpdateTime = scanFileTime;
10625            }
10626        }
10627        pkgSetting.setTimeStamp(scanFileTime);
10628
10629        pkgSetting.pkg = pkg;
10630        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10631        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10632            pkgSetting.versionCode = pkg.getLongVersionCode();
10633        }
10634        // Update volume if needed
10635        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10636        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10637            Slog.i(PackageManagerService.TAG,
10638                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10639                    + " package " + pkg.packageName
10640                    + " volume from " + pkgSetting.volumeUuid
10641                    + " to " + volumeUuid);
10642            pkgSetting.volumeUuid = volumeUuid;
10643        }
10644
10645        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10646    }
10647
10648    /**
10649     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10650     */
10651    private static boolean apkHasCode(String fileName) {
10652        StrictJarFile jarFile = null;
10653        try {
10654            jarFile = new StrictJarFile(fileName,
10655                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10656            return jarFile.findEntry("classes.dex") != null;
10657        } catch (IOException ignore) {
10658        } finally {
10659            try {
10660                if (jarFile != null) {
10661                    jarFile.close();
10662                }
10663            } catch (IOException ignore) {}
10664        }
10665        return false;
10666    }
10667
10668    /**
10669     * Enforces code policy for the package. This ensures that if an APK has
10670     * declared hasCode="true" in its manifest that the APK actually contains
10671     * code.
10672     *
10673     * @throws PackageManagerException If bytecode could not be found when it should exist
10674     */
10675    private static void assertCodePolicy(PackageParser.Package pkg)
10676            throws PackageManagerException {
10677        final boolean shouldHaveCode =
10678                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10679        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10680            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10681                    "Package " + pkg.baseCodePath + " code is missing");
10682        }
10683
10684        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10685            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10686                final boolean splitShouldHaveCode =
10687                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10688                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10689                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10690                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10691                }
10692            }
10693        }
10694    }
10695
10696    /**
10697     * Applies policy to the parsed package based upon the given policy flags.
10698     * Ensures the package is in a good state.
10699     * <p>
10700     * Implementation detail: This method must NOT have any side effect. It would
10701     * ideally be static, but, it requires locks to read system state.
10702     */
10703    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10704            final @ScanFlags int scanFlags, PackageParser.Package platformPkg) {
10705        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10706            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10707            if (pkg.applicationInfo.isDirectBootAware()) {
10708                // we're direct boot aware; set for all components
10709                for (PackageParser.Service s : pkg.services) {
10710                    s.info.encryptionAware = s.info.directBootAware = true;
10711                }
10712                for (PackageParser.Provider p : pkg.providers) {
10713                    p.info.encryptionAware = p.info.directBootAware = true;
10714                }
10715                for (PackageParser.Activity a : pkg.activities) {
10716                    a.info.encryptionAware = a.info.directBootAware = true;
10717                }
10718                for (PackageParser.Activity r : pkg.receivers) {
10719                    r.info.encryptionAware = r.info.directBootAware = true;
10720                }
10721            }
10722            if (compressedFileExists(pkg.codePath)) {
10723                pkg.isStub = true;
10724            }
10725        } else {
10726            // non system apps can't be flagged as core
10727            pkg.coreApp = false;
10728            // clear flags not applicable to regular apps
10729            pkg.applicationInfo.flags &=
10730                    ~ApplicationInfo.FLAG_PERSISTENT;
10731            pkg.applicationInfo.privateFlags &=
10732                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10733            pkg.applicationInfo.privateFlags &=
10734                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10735            // cap permission priorities
10736            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10737                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10738                    pkg.permissionGroups.get(i).info.priority = 0;
10739                }
10740            }
10741        }
10742        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10743            // clear protected broadcasts
10744            pkg.protectedBroadcasts = null;
10745            // ignore export request for single user receivers
10746            if (pkg.receivers != null) {
10747                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10748                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10749                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10750                        receiver.info.exported = false;
10751                    }
10752                }
10753            }
10754            // ignore export request for single user services
10755            if (pkg.services != null) {
10756                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10757                    final PackageParser.Service service = pkg.services.get(i);
10758                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10759                        service.info.exported = false;
10760                    }
10761                }
10762            }
10763            // ignore export request for single user providers
10764            if (pkg.providers != null) {
10765                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10766                    final PackageParser.Provider provider = pkg.providers.get(i);
10767                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10768                        provider.info.exported = false;
10769                    }
10770                }
10771            }
10772        }
10773
10774        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10775            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10776        }
10777
10778        if ((scanFlags & SCAN_AS_OEM) != 0) {
10779            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10780        }
10781
10782        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10783            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10784        }
10785
10786        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10787            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10788        }
10789
10790        // Check if the package is signed with the same key as the platform package.
10791        if (PLATFORM_PACKAGE_NAME.equals(pkg.packageName) ||
10792                (platformPkg != null && compareSignatures(
10793                        platformPkg.mSigningDetails.signatures,
10794                        pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH)) {
10795            pkg.applicationInfo.privateFlags |=
10796                ApplicationInfo.PRIVATE_FLAG_SIGNED_WITH_PLATFORM_KEY;
10797        }
10798
10799        if (!isSystemApp(pkg)) {
10800            // Only system apps can use these features.
10801            pkg.mOriginalPackages = null;
10802            pkg.mRealPackage = null;
10803            pkg.mAdoptPermissions = null;
10804        }
10805    }
10806
10807    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10808            throws PackageManagerException {
10809        if (object == null) {
10810            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10811        }
10812        return object;
10813    }
10814
10815    /**
10816     * Asserts the parsed package is valid according to the given policy. If the
10817     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10818     * <p>
10819     * Implementation detail: This method must NOT have any side effects. It would
10820     * ideally be static, but, it requires locks to read system state.
10821     *
10822     * @throws PackageManagerException If the package fails any of the validation checks
10823     */
10824    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10825            final @ScanFlags int scanFlags)
10826                    throws PackageManagerException {
10827        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10828            assertCodePolicy(pkg);
10829        }
10830
10831        if (pkg.applicationInfo.getCodePath() == null ||
10832                pkg.applicationInfo.getResourcePath() == null) {
10833            // Bail out. The resource and code paths haven't been set.
10834            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10835                    "Code and resource paths haven't been set correctly");
10836        }
10837
10838        // Make sure we're not adding any bogus keyset info
10839        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10840        ksms.assertScannedPackageValid(pkg);
10841
10842        synchronized (mPackages) {
10843            // The special "android" package can only be defined once
10844            if (pkg.packageName.equals("android")) {
10845                if (mAndroidApplication != null) {
10846                    Slog.w(TAG, "*************************************************");
10847                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10848                    Slog.w(TAG, " codePath=" + pkg.codePath);
10849                    Slog.w(TAG, "*************************************************");
10850                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10851                            "Core android package being redefined.  Skipping.");
10852                }
10853            }
10854
10855            // A package name must be unique; don't allow duplicates
10856            if (mPackages.containsKey(pkg.packageName)) {
10857                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10858                        "Application package " + pkg.packageName
10859                        + " already installed.  Skipping duplicate.");
10860            }
10861
10862            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10863                // Static libs have a synthetic package name containing the version
10864                // but we still want the base name to be unique.
10865                if (mPackages.containsKey(pkg.manifestPackageName)) {
10866                    throw new PackageManagerException(
10867                            "Duplicate static shared lib provider package");
10868                }
10869
10870                // Static shared libraries should have at least O target SDK
10871                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10872                    throw new PackageManagerException(
10873                            "Packages declaring static-shared libs must target O SDK or higher");
10874                }
10875
10876                // Package declaring static a shared lib cannot be instant apps
10877                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10878                    throw new PackageManagerException(
10879                            "Packages declaring static-shared libs cannot be instant apps");
10880                }
10881
10882                // Package declaring static a shared lib cannot be renamed since the package
10883                // name is synthetic and apps can't code around package manager internals.
10884                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10885                    throw new PackageManagerException(
10886                            "Packages declaring static-shared libs cannot be renamed");
10887                }
10888
10889                // Package declaring static a shared lib cannot declare child packages
10890                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10891                    throw new PackageManagerException(
10892                            "Packages declaring static-shared libs cannot have child packages");
10893                }
10894
10895                // Package declaring static a shared lib cannot declare dynamic libs
10896                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10897                    throw new PackageManagerException(
10898                            "Packages declaring static-shared libs cannot declare dynamic libs");
10899                }
10900
10901                // Package declaring static a shared lib cannot declare shared users
10902                if (pkg.mSharedUserId != null) {
10903                    throw new PackageManagerException(
10904                            "Packages declaring static-shared libs cannot declare shared users");
10905                }
10906
10907                // Static shared libs cannot declare activities
10908                if (!pkg.activities.isEmpty()) {
10909                    throw new PackageManagerException(
10910                            "Static shared libs cannot declare activities");
10911                }
10912
10913                // Static shared libs cannot declare services
10914                if (!pkg.services.isEmpty()) {
10915                    throw new PackageManagerException(
10916                            "Static shared libs cannot declare services");
10917                }
10918
10919                // Static shared libs cannot declare providers
10920                if (!pkg.providers.isEmpty()) {
10921                    throw new PackageManagerException(
10922                            "Static shared libs cannot declare content providers");
10923                }
10924
10925                // Static shared libs cannot declare receivers
10926                if (!pkg.receivers.isEmpty()) {
10927                    throw new PackageManagerException(
10928                            "Static shared libs cannot declare broadcast receivers");
10929                }
10930
10931                // Static shared libs cannot declare permission groups
10932                if (!pkg.permissionGroups.isEmpty()) {
10933                    throw new PackageManagerException(
10934                            "Static shared libs cannot declare permission groups");
10935                }
10936
10937                // Static shared libs cannot declare permissions
10938                if (!pkg.permissions.isEmpty()) {
10939                    throw new PackageManagerException(
10940                            "Static shared libs cannot declare permissions");
10941                }
10942
10943                // Static shared libs cannot declare protected broadcasts
10944                if (pkg.protectedBroadcasts != null) {
10945                    throw new PackageManagerException(
10946                            "Static shared libs cannot declare protected broadcasts");
10947                }
10948
10949                // Static shared libs cannot be overlay targets
10950                if (pkg.mOverlayTarget != null) {
10951                    throw new PackageManagerException(
10952                            "Static shared libs cannot be overlay targets");
10953                }
10954
10955                // The version codes must be ordered as lib versions
10956                long minVersionCode = Long.MIN_VALUE;
10957                long maxVersionCode = Long.MAX_VALUE;
10958
10959                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10960                        pkg.staticSharedLibName);
10961                if (versionedLib != null) {
10962                    final int versionCount = versionedLib.size();
10963                    for (int i = 0; i < versionCount; i++) {
10964                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10965                        final long libVersionCode = libInfo.getDeclaringPackage()
10966                                .getLongVersionCode();
10967                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10968                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10969                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10970                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10971                        } else {
10972                            minVersionCode = maxVersionCode = libVersionCode;
10973                            break;
10974                        }
10975                    }
10976                }
10977                if (pkg.getLongVersionCode() < minVersionCode
10978                        || pkg.getLongVersionCode() > maxVersionCode) {
10979                    throw new PackageManagerException("Static shared"
10980                            + " lib version codes must be ordered as lib versions");
10981                }
10982            }
10983
10984            // Only privileged apps and updated privileged apps can add child packages.
10985            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10986                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10987                    throw new PackageManagerException("Only privileged apps can add child "
10988                            + "packages. Ignoring package " + pkg.packageName);
10989                }
10990                final int childCount = pkg.childPackages.size();
10991                for (int i = 0; i < childCount; i++) {
10992                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10993                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10994                            childPkg.packageName)) {
10995                        throw new PackageManagerException("Can't override child of "
10996                                + "another disabled app. Ignoring package " + pkg.packageName);
10997                    }
10998                }
10999            }
11000
11001            // If we're only installing presumed-existing packages, require that the
11002            // scanned APK is both already known and at the path previously established
11003            // for it.  Previously unknown packages we pick up normally, but if we have an
11004            // a priori expectation about this package's install presence, enforce it.
11005            // With a singular exception for new system packages. When an OTA contains
11006            // a new system package, we allow the codepath to change from a system location
11007            // to the user-installed location. If we don't allow this change, any newer,
11008            // user-installed version of the application will be ignored.
11009            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11010                if (mExpectingBetter.containsKey(pkg.packageName)) {
11011                    logCriticalInfo(Log.WARN,
11012                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11013                } else {
11014                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11015                    if (known != null) {
11016                        if (DEBUG_PACKAGE_SCANNING) {
11017                            Log.d(TAG, "Examining " + pkg.codePath
11018                                    + " and requiring known paths " + known.codePathString
11019                                    + " & " + known.resourcePathString);
11020                        }
11021                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11022                                || !pkg.applicationInfo.getResourcePath().equals(
11023                                        known.resourcePathString)) {
11024                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11025                                    "Application package " + pkg.packageName
11026                                    + " found at " + pkg.applicationInfo.getCodePath()
11027                                    + " but expected at " + known.codePathString
11028                                    + "; ignoring.");
11029                        }
11030                    } else {
11031                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11032                                "Application package " + pkg.packageName
11033                                + " not found; ignoring.");
11034                    }
11035                }
11036            }
11037
11038            // Verify that this new package doesn't have any content providers
11039            // that conflict with existing packages.  Only do this if the
11040            // package isn't already installed, since we don't want to break
11041            // things that are installed.
11042            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11043                final int N = pkg.providers.size();
11044                int i;
11045                for (i=0; i<N; i++) {
11046                    PackageParser.Provider p = pkg.providers.get(i);
11047                    if (p.info.authority != null) {
11048                        String names[] = p.info.authority.split(";");
11049                        for (int j = 0; j < names.length; j++) {
11050                            if (mProvidersByAuthority.containsKey(names[j])) {
11051                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11052                                final String otherPackageName =
11053                                        ((other != null && other.getComponentName() != null) ?
11054                                                other.getComponentName().getPackageName() : "?");
11055                                throw new PackageManagerException(
11056                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11057                                        "Can't install because provider name " + names[j]
11058                                                + " (in package " + pkg.applicationInfo.packageName
11059                                                + ") is already used by " + otherPackageName);
11060                            }
11061                        }
11062                    }
11063                }
11064            }
11065
11066            // Verify that packages sharing a user with a privileged app are marked as privileged.
11067            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
11068                SharedUserSetting sharedUserSetting = null;
11069                try {
11070                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
11071                } catch (PackageManagerException ignore) {}
11072                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
11073                    // Exempt SharedUsers signed with the platform key.
11074                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
11075                    if ((platformPkgSetting.signatures.mSigningDetails
11076                            != PackageParser.SigningDetails.UNKNOWN)
11077                            && (compareSignatures(
11078                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11079                                    pkg.mSigningDetails.signatures)
11080                                            != PackageManager.SIGNATURE_MATCH)) {
11081                        throw new PackageManagerException("Apps that share a user with a " +
11082                                "privileged app must themselves be marked as privileged. " +
11083                                pkg.packageName + " shares privileged user " +
11084                                pkg.mSharedUserId + ".");
11085                    }
11086                }
11087            }
11088
11089            // Apply policies specific for runtime resource overlays (RROs).
11090            if (pkg.mOverlayTarget != null) {
11091                // System overlays have some restrictions on their use of the 'static' state.
11092                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11093                    // We are scanning a system overlay. This can be the first scan of the
11094                    // system/vendor/oem partition, or an update to the system overlay.
11095                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11096                        // This must be an update to a system overlay.
11097                        final PackageSetting previousPkg = assertNotNull(
11098                                mSettings.getPackageLPr(pkg.packageName),
11099                                "previous package state not present");
11100
11101                        // Static overlays cannot be updated.
11102                        if (previousPkg.pkg.mOverlayIsStatic) {
11103                            throw new PackageManagerException("Overlay " + pkg.packageName +
11104                                    " is static and cannot be upgraded.");
11105                        // Non-static overlays cannot be converted to static overlays.
11106                        } else if (pkg.mOverlayIsStatic) {
11107                            throw new PackageManagerException("Overlay " + pkg.packageName +
11108                                    " cannot be upgraded into a static overlay.");
11109                        }
11110                    }
11111                } else {
11112                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11113                    if (pkg.mOverlayIsStatic) {
11114                        throw new PackageManagerException("Overlay " + pkg.packageName +
11115                                " is static but not pre-installed.");
11116                    }
11117
11118                    // The only case where we allow installation of a non-system overlay is when
11119                    // its signature is signed with the platform certificate.
11120                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11121                    if ((platformPkgSetting.signatures.mSigningDetails
11122                            != PackageParser.SigningDetails.UNKNOWN)
11123                            && (compareSignatures(
11124                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11125                                    pkg.mSigningDetails.signatures)
11126                                            != PackageManager.SIGNATURE_MATCH)) {
11127                        throw new PackageManagerException("Overlay " + pkg.packageName +
11128                                " must be signed with the platform certificate.");
11129                    }
11130                }
11131            }
11132        }
11133    }
11134
11135    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11136            int type, String declaringPackageName, long declaringVersionCode) {
11137        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11138        if (versionedLib == null) {
11139            versionedLib = new LongSparseArray<>();
11140            mSharedLibraries.put(name, versionedLib);
11141            if (type == SharedLibraryInfo.TYPE_STATIC) {
11142                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11143            }
11144        } else if (versionedLib.indexOfKey(version) >= 0) {
11145            return false;
11146        }
11147        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11148                version, type, declaringPackageName, declaringVersionCode);
11149        versionedLib.put(version, libEntry);
11150        return true;
11151    }
11152
11153    private boolean removeSharedLibraryLPw(String name, long version) {
11154        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11155        if (versionedLib == null) {
11156            return false;
11157        }
11158        final int libIdx = versionedLib.indexOfKey(version);
11159        if (libIdx < 0) {
11160            return false;
11161        }
11162        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11163        versionedLib.remove(version);
11164        if (versionedLib.size() <= 0) {
11165            mSharedLibraries.remove(name);
11166            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11167                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11168                        .getPackageName());
11169            }
11170        }
11171        return true;
11172    }
11173
11174    /**
11175     * Adds a scanned package to the system. When this method is finished, the package will
11176     * be available for query, resolution, etc...
11177     */
11178    private void commitPackageSettings(PackageParser.Package pkg,
11179            @Nullable PackageParser.Package oldPkg, PackageSetting pkgSetting, UserHandle user,
11180            final @ScanFlags int scanFlags, boolean chatty) {
11181        final String pkgName = pkg.packageName;
11182        if (mCustomResolverComponentName != null &&
11183                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11184            setUpCustomResolverActivity(pkg);
11185        }
11186
11187        if (pkg.packageName.equals("android")) {
11188            synchronized (mPackages) {
11189                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11190                    // Set up information for our fall-back user intent resolution activity.
11191                    mPlatformPackage = pkg;
11192                    pkg.mVersionCode = mSdkVersion;
11193                    pkg.mVersionCodeMajor = 0;
11194                    mAndroidApplication = pkg.applicationInfo;
11195                    if (!mResolverReplaced) {
11196                        mResolveActivity.applicationInfo = mAndroidApplication;
11197                        mResolveActivity.name = ResolverActivity.class.getName();
11198                        mResolveActivity.packageName = mAndroidApplication.packageName;
11199                        mResolveActivity.processName = "system:ui";
11200                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11201                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11202                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11203                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11204                        mResolveActivity.exported = true;
11205                        mResolveActivity.enabled = true;
11206                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11207                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11208                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11209                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11210                                | ActivityInfo.CONFIG_ORIENTATION
11211                                | ActivityInfo.CONFIG_KEYBOARD
11212                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11213                        mResolveInfo.activityInfo = mResolveActivity;
11214                        mResolveInfo.priority = 0;
11215                        mResolveInfo.preferredOrder = 0;
11216                        mResolveInfo.match = 0;
11217                        mResolveComponentName = new ComponentName(
11218                                mAndroidApplication.packageName, mResolveActivity.name);
11219                    }
11220                }
11221            }
11222        }
11223
11224        ArrayList<PackageParser.Package> clientLibPkgs = null;
11225        // writer
11226        synchronized (mPackages) {
11227            boolean hasStaticSharedLibs = false;
11228
11229            // Any app can add new static shared libraries
11230            if (pkg.staticSharedLibName != null) {
11231                // Static shared libs don't allow renaming as they have synthetic package
11232                // names to allow install of multiple versions, so use name from manifest.
11233                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11234                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11235                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11236                    hasStaticSharedLibs = true;
11237                } else {
11238                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11239                                + pkg.staticSharedLibName + " already exists; skipping");
11240                }
11241                // Static shared libs cannot be updated once installed since they
11242                // use synthetic package name which includes the version code, so
11243                // not need to update other packages's shared lib dependencies.
11244            }
11245
11246            if (!hasStaticSharedLibs
11247                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11248                // Only system apps can add new dynamic shared libraries.
11249                if (pkg.libraryNames != null) {
11250                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11251                        String name = pkg.libraryNames.get(i);
11252                        boolean allowed = false;
11253                        if (pkg.isUpdatedSystemApp()) {
11254                            // New library entries can only be added through the
11255                            // system image.  This is important to get rid of a lot
11256                            // of nasty edge cases: for example if we allowed a non-
11257                            // system update of the app to add a library, then uninstalling
11258                            // the update would make the library go away, and assumptions
11259                            // we made such as through app install filtering would now
11260                            // have allowed apps on the device which aren't compatible
11261                            // with it.  Better to just have the restriction here, be
11262                            // conservative, and create many fewer cases that can negatively
11263                            // impact the user experience.
11264                            final PackageSetting sysPs = mSettings
11265                                    .getDisabledSystemPkgLPr(pkg.packageName);
11266                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11267                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11268                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11269                                        allowed = true;
11270                                        break;
11271                                    }
11272                                }
11273                            }
11274                        } else {
11275                            allowed = true;
11276                        }
11277                        if (allowed) {
11278                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11279                                    SharedLibraryInfo.VERSION_UNDEFINED,
11280                                    SharedLibraryInfo.TYPE_DYNAMIC,
11281                                    pkg.packageName, pkg.getLongVersionCode())) {
11282                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11283                                        + name + " already exists; skipping");
11284                            }
11285                        } else {
11286                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11287                                    + name + " that is not declared on system image; skipping");
11288                        }
11289                    }
11290
11291                    if ((scanFlags & SCAN_BOOTING) == 0) {
11292                        // If we are not booting, we need to update any applications
11293                        // that are clients of our shared library.  If we are booting,
11294                        // this will all be done once the scan is complete.
11295                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11296                    }
11297                }
11298            }
11299        }
11300
11301        if ((scanFlags & SCAN_BOOTING) != 0) {
11302            // No apps can run during boot scan, so they don't need to be frozen
11303        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11304            // Caller asked to not kill app, so it's probably not frozen
11305        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11306            // Caller asked us to ignore frozen check for some reason; they
11307            // probably didn't know the package name
11308        } else {
11309            // We're doing major surgery on this package, so it better be frozen
11310            // right now to keep it from launching
11311            checkPackageFrozen(pkgName);
11312        }
11313
11314        // Also need to kill any apps that are dependent on the library.
11315        if (clientLibPkgs != null) {
11316            for (int i=0; i<clientLibPkgs.size(); i++) {
11317                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11318                killApplication(clientPkg.applicationInfo.packageName,
11319                        clientPkg.applicationInfo.uid, "update lib");
11320            }
11321        }
11322
11323        // writer
11324        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11325
11326        synchronized (mPackages) {
11327            // We don't expect installation to fail beyond this point
11328
11329            // Add the new setting to mSettings
11330            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11331            // Add the new setting to mPackages
11332            mPackages.put(pkg.applicationInfo.packageName, pkg);
11333            // Make sure we don't accidentally delete its data.
11334            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11335            while (iter.hasNext()) {
11336                PackageCleanItem item = iter.next();
11337                if (pkgName.equals(item.packageName)) {
11338                    iter.remove();
11339                }
11340            }
11341
11342            // Add the package's KeySets to the global KeySetManagerService
11343            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11344            ksms.addScannedPackageLPw(pkg);
11345
11346            int N = pkg.providers.size();
11347            StringBuilder r = null;
11348            int i;
11349            for (i=0; i<N; i++) {
11350                PackageParser.Provider p = pkg.providers.get(i);
11351                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11352                        p.info.processName);
11353                mProviders.addProvider(p);
11354                p.syncable = p.info.isSyncable;
11355                if (p.info.authority != null) {
11356                    String names[] = p.info.authority.split(";");
11357                    p.info.authority = null;
11358                    for (int j = 0; j < names.length; j++) {
11359                        if (j == 1 && p.syncable) {
11360                            // We only want the first authority for a provider to possibly be
11361                            // syncable, so if we already added this provider using a different
11362                            // authority clear the syncable flag. We copy the provider before
11363                            // changing it because the mProviders object contains a reference
11364                            // to a provider that we don't want to change.
11365                            // Only do this for the second authority since the resulting provider
11366                            // object can be the same for all future authorities for this provider.
11367                            p = new PackageParser.Provider(p);
11368                            p.syncable = false;
11369                        }
11370                        if (!mProvidersByAuthority.containsKey(names[j])) {
11371                            mProvidersByAuthority.put(names[j], p);
11372                            if (p.info.authority == null) {
11373                                p.info.authority = names[j];
11374                            } else {
11375                                p.info.authority = p.info.authority + ";" + names[j];
11376                            }
11377                            if (DEBUG_PACKAGE_SCANNING) {
11378                                if (chatty)
11379                                    Log.d(TAG, "Registered content provider: " + names[j]
11380                                            + ", className = " + p.info.name + ", isSyncable = "
11381                                            + p.info.isSyncable);
11382                            }
11383                        } else {
11384                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11385                            Slog.w(TAG, "Skipping provider name " + names[j] +
11386                                    " (in package " + pkg.applicationInfo.packageName +
11387                                    "): name already used by "
11388                                    + ((other != null && other.getComponentName() != null)
11389                                            ? other.getComponentName().getPackageName() : "?"));
11390                        }
11391                    }
11392                }
11393                if (chatty) {
11394                    if (r == null) {
11395                        r = new StringBuilder(256);
11396                    } else {
11397                        r.append(' ');
11398                    }
11399                    r.append(p.info.name);
11400                }
11401            }
11402            if (r != null) {
11403                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11404            }
11405
11406            N = pkg.services.size();
11407            r = null;
11408            for (i=0; i<N; i++) {
11409                PackageParser.Service s = pkg.services.get(i);
11410                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11411                        s.info.processName);
11412                mServices.addService(s);
11413                if (chatty) {
11414                    if (r == null) {
11415                        r = new StringBuilder(256);
11416                    } else {
11417                        r.append(' ');
11418                    }
11419                    r.append(s.info.name);
11420                }
11421            }
11422            if (r != null) {
11423                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11424            }
11425
11426            N = pkg.receivers.size();
11427            r = null;
11428            for (i=0; i<N; i++) {
11429                PackageParser.Activity a = pkg.receivers.get(i);
11430                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11431                        a.info.processName);
11432                mReceivers.addActivity(a, "receiver");
11433                if (chatty) {
11434                    if (r == null) {
11435                        r = new StringBuilder(256);
11436                    } else {
11437                        r.append(' ');
11438                    }
11439                    r.append(a.info.name);
11440                }
11441            }
11442            if (r != null) {
11443                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11444            }
11445
11446            N = pkg.activities.size();
11447            r = null;
11448            for (i=0; i<N; i++) {
11449                PackageParser.Activity a = pkg.activities.get(i);
11450                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11451                        a.info.processName);
11452                mActivities.addActivity(a, "activity");
11453                if (chatty) {
11454                    if (r == null) {
11455                        r = new StringBuilder(256);
11456                    } else {
11457                        r.append(' ');
11458                    }
11459                    r.append(a.info.name);
11460                }
11461            }
11462            if (r != null) {
11463                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11464            }
11465
11466            // Don't allow ephemeral applications to define new permissions groups.
11467            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11468                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11469                        + " ignored: instant apps cannot define new permission groups.");
11470            } else {
11471                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11472            }
11473
11474            // Don't allow ephemeral applications to define new permissions.
11475            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11476                Slog.w(TAG, "Permissions from package " + pkg.packageName
11477                        + " ignored: instant apps cannot define new permissions.");
11478            } else {
11479                mPermissionManager.addAllPermissions(pkg, chatty);
11480            }
11481
11482            N = pkg.instrumentation.size();
11483            r = null;
11484            for (i=0; i<N; i++) {
11485                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11486                a.info.packageName = pkg.applicationInfo.packageName;
11487                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11488                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11489                a.info.splitNames = pkg.splitNames;
11490                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11491                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11492                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11493                a.info.dataDir = pkg.applicationInfo.dataDir;
11494                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11495                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11496                a.info.primaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11497                a.info.secondaryCpuAbi = pkg.applicationInfo.secondaryCpuAbi;
11498                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11499                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11500                mInstrumentation.put(a.getComponentName(), a);
11501                if (chatty) {
11502                    if (r == null) {
11503                        r = new StringBuilder(256);
11504                    } else {
11505                        r.append(' ');
11506                    }
11507                    r.append(a.info.name);
11508                }
11509            }
11510            if (r != null) {
11511                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11512            }
11513
11514            if (pkg.protectedBroadcasts != null) {
11515                N = pkg.protectedBroadcasts.size();
11516                synchronized (mProtectedBroadcasts) {
11517                    for (i = 0; i < N; i++) {
11518                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11519                    }
11520                }
11521            }
11522
11523            if (oldPkg != null) {
11524                // We need to call revokeRuntimePermissionsIfGroupChanged async as permission
11525                // revoke callbacks from this method might need to kill apps which need the
11526                // mPackages lock on a different thread. This would dead lock.
11527                //
11528                // Hence create a copy of all package names and pass it into
11529                // revokeRuntimePermissionsIfGroupChanged. Only for those permissions might get
11530                // revoked. If a new package is added before the async code runs the permission
11531                // won't be granted yet, hence new packages are no problem.
11532                final ArrayList<String> allPackageNames = new ArrayList<>(mPackages.keySet());
11533
11534                AsyncTask.execute(() ->
11535                        mPermissionManager.revokeRuntimePermissionsIfGroupChanged(pkg, oldPkg,
11536                                allPackageNames, mPermissionCallback));
11537            }
11538        }
11539
11540        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11541    }
11542
11543    /**
11544     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11545     * is derived purely on the basis of the contents of {@code scanFile} and
11546     * {@code cpuAbiOverride}.
11547     *
11548     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11549     */
11550    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11551            boolean extractLibs)
11552                    throws PackageManagerException {
11553        // Give ourselves some initial paths; we'll come back for another
11554        // pass once we've determined ABI below.
11555        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11556
11557        // We would never need to extract libs for forward-locked and external packages,
11558        // since the container service will do it for us. We shouldn't attempt to
11559        // extract libs from system app when it was not updated.
11560        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11561                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11562            extractLibs = false;
11563        }
11564
11565        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11566        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11567
11568        NativeLibraryHelper.Handle handle = null;
11569        try {
11570            handle = NativeLibraryHelper.Handle.create(pkg);
11571            // TODO(multiArch): This can be null for apps that didn't go through the
11572            // usual installation process. We can calculate it again, like we
11573            // do during install time.
11574            //
11575            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11576            // unnecessary.
11577            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11578
11579            // Null out the abis so that they can be recalculated.
11580            pkg.applicationInfo.primaryCpuAbi = null;
11581            pkg.applicationInfo.secondaryCpuAbi = null;
11582            if (isMultiArch(pkg.applicationInfo)) {
11583                // Warn if we've set an abiOverride for multi-lib packages..
11584                // By definition, we need to copy both 32 and 64 bit libraries for
11585                // such packages.
11586                if (pkg.cpuAbiOverride != null
11587                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11588                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11589                }
11590
11591                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11592                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11593                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11594                    if (extractLibs) {
11595                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11596                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11597                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11598                                useIsaSpecificSubdirs);
11599                    } else {
11600                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11601                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11602                    }
11603                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11604                }
11605
11606                // Shared library native code should be in the APK zip aligned
11607                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11608                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11609                            "Shared library native lib extraction not supported");
11610                }
11611
11612                maybeThrowExceptionForMultiArchCopy(
11613                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11614
11615                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11616                    if (extractLibs) {
11617                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11618                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11619                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11620                                useIsaSpecificSubdirs);
11621                    } else {
11622                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11623                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11624                    }
11625                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11626                }
11627
11628                maybeThrowExceptionForMultiArchCopy(
11629                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11630
11631                if (abi64 >= 0) {
11632                    // Shared library native libs should be in the APK zip aligned
11633                    if (extractLibs && pkg.isLibrary()) {
11634                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11635                                "Shared library native lib extraction not supported");
11636                    }
11637                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11638                }
11639
11640                if (abi32 >= 0) {
11641                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11642                    if (abi64 >= 0) {
11643                        if (pkg.use32bitAbi) {
11644                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11645                            pkg.applicationInfo.primaryCpuAbi = abi;
11646                        } else {
11647                            pkg.applicationInfo.secondaryCpuAbi = abi;
11648                        }
11649                    } else {
11650                        pkg.applicationInfo.primaryCpuAbi = abi;
11651                    }
11652                }
11653            } else {
11654                String[] abiList = (cpuAbiOverride != null) ?
11655                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11656
11657                // Enable gross and lame hacks for apps that are built with old
11658                // SDK tools. We must scan their APKs for renderscript bitcode and
11659                // not launch them if it's present. Don't bother checking on devices
11660                // that don't have 64 bit support.
11661                boolean needsRenderScriptOverride = false;
11662                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11663                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11664                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11665                    needsRenderScriptOverride = true;
11666                }
11667
11668                final int copyRet;
11669                if (extractLibs) {
11670                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11671                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11672                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11673                } else {
11674                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11675                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11676                }
11677                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11678
11679                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11680                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11681                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11682                }
11683
11684                if (copyRet >= 0) {
11685                    // Shared libraries that have native libs must be multi-architecture
11686                    if (pkg.isLibrary()) {
11687                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11688                                "Shared library with native libs must be multiarch");
11689                    }
11690                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11691                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11692                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11693                } else if (needsRenderScriptOverride) {
11694                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11695                }
11696            }
11697        } catch (IOException ioe) {
11698            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11699        } finally {
11700            IoUtils.closeQuietly(handle);
11701        }
11702
11703        // Now that we've calculated the ABIs and determined if it's an internal app,
11704        // we will go ahead and populate the nativeLibraryPath.
11705        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11706    }
11707
11708    /**
11709     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11710     * i.e, so that all packages can be run inside a single process if required.
11711     *
11712     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11713     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11714     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11715     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11716     * updating a package that belongs to a shared user.
11717     *
11718     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11719     * adds unnecessary complexity.
11720     */
11721    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11722            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11723        List<String> changedAbiCodePath = null;
11724        String requiredInstructionSet = null;
11725        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11726            requiredInstructionSet = VMRuntime.getInstructionSet(
11727                     scannedPackage.applicationInfo.primaryCpuAbi);
11728        }
11729
11730        PackageSetting requirer = null;
11731        for (PackageSetting ps : packagesForUser) {
11732            // If packagesForUser contains scannedPackage, we skip it. This will happen
11733            // when scannedPackage is an update of an existing package. Without this check,
11734            // we will never be able to change the ABI of any package belonging to a shared
11735            // user, even if it's compatible with other packages.
11736            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11737                if (ps.primaryCpuAbiString == null) {
11738                    continue;
11739                }
11740
11741                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11742                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11743                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11744                    // this but there's not much we can do.
11745                    String errorMessage = "Instruction set mismatch, "
11746                            + ((requirer == null) ? "[caller]" : requirer)
11747                            + " requires " + requiredInstructionSet + " whereas " + ps
11748                            + " requires " + instructionSet;
11749                    Slog.w(TAG, errorMessage);
11750                }
11751
11752                if (requiredInstructionSet == null) {
11753                    requiredInstructionSet = instructionSet;
11754                    requirer = ps;
11755                }
11756            }
11757        }
11758
11759        if (requiredInstructionSet != null) {
11760            String adjustedAbi;
11761            if (requirer != null) {
11762                // requirer != null implies that either scannedPackage was null or that scannedPackage
11763                // did not require an ABI, in which case we have to adjust scannedPackage to match
11764                // the ABI of the set (which is the same as requirer's ABI)
11765                adjustedAbi = requirer.primaryCpuAbiString;
11766                if (scannedPackage != null) {
11767                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11768                }
11769            } else {
11770                // requirer == null implies that we're updating all ABIs in the set to
11771                // match scannedPackage.
11772                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11773            }
11774
11775            for (PackageSetting ps : packagesForUser) {
11776                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11777                    if (ps.primaryCpuAbiString != null) {
11778                        continue;
11779                    }
11780
11781                    ps.primaryCpuAbiString = adjustedAbi;
11782                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11783                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11784                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11785                        if (DEBUG_ABI_SELECTION) {
11786                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11787                                    + " (requirer="
11788                                    + (requirer != null ? requirer.pkg : "null")
11789                                    + ", scannedPackage="
11790                                    + (scannedPackage != null ? scannedPackage : "null")
11791                                    + ")");
11792                        }
11793                        if (changedAbiCodePath == null) {
11794                            changedAbiCodePath = new ArrayList<>();
11795                        }
11796                        changedAbiCodePath.add(ps.codePathString);
11797                    }
11798                }
11799            }
11800        }
11801        return changedAbiCodePath;
11802    }
11803
11804    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11805        synchronized (mPackages) {
11806            mResolverReplaced = true;
11807            // Set up information for custom user intent resolution activity.
11808            mResolveActivity.applicationInfo = pkg.applicationInfo;
11809            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11810            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11811            mResolveActivity.processName = pkg.applicationInfo.packageName;
11812            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11813            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11814                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11815            mResolveActivity.theme = 0;
11816            mResolveActivity.exported = true;
11817            mResolveActivity.enabled = true;
11818            mResolveInfo.activityInfo = mResolveActivity;
11819            mResolveInfo.priority = 0;
11820            mResolveInfo.preferredOrder = 0;
11821            mResolveInfo.match = 0;
11822            mResolveComponentName = mCustomResolverComponentName;
11823            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11824                    mResolveComponentName);
11825        }
11826    }
11827
11828    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11829        if (installerActivity == null) {
11830            if (DEBUG_INSTANT) {
11831                Slog.d(TAG, "Clear ephemeral installer activity");
11832            }
11833            mInstantAppInstallerActivity = null;
11834            return;
11835        }
11836
11837        if (DEBUG_INSTANT) {
11838            Slog.d(TAG, "Set ephemeral installer activity: "
11839                    + installerActivity.getComponentName());
11840        }
11841        // Set up information for ephemeral installer activity
11842        mInstantAppInstallerActivity = installerActivity;
11843        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11844                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11845        mInstantAppInstallerActivity.exported = true;
11846        mInstantAppInstallerActivity.enabled = true;
11847        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11848        mInstantAppInstallerInfo.priority = 1;
11849        mInstantAppInstallerInfo.preferredOrder = 1;
11850        mInstantAppInstallerInfo.isDefault = true;
11851        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11852                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11853    }
11854
11855    private static String calculateBundledApkRoot(final String codePathString) {
11856        final File codePath = new File(codePathString);
11857        final File codeRoot;
11858        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11859            codeRoot = Environment.getRootDirectory();
11860        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11861            codeRoot = Environment.getOemDirectory();
11862        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11863            codeRoot = Environment.getVendorDirectory();
11864        } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) {
11865            codeRoot = Environment.getOdmDirectory();
11866        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11867            codeRoot = Environment.getProductDirectory();
11868        } else {
11869            // Unrecognized code path; take its top real segment as the apk root:
11870            // e.g. /something/app/blah.apk => /something
11871            try {
11872                File f = codePath.getCanonicalFile();
11873                File parent = f.getParentFile();    // non-null because codePath is a file
11874                File tmp;
11875                while ((tmp = parent.getParentFile()) != null) {
11876                    f = parent;
11877                    parent = tmp;
11878                }
11879                codeRoot = f;
11880                Slog.w(TAG, "Unrecognized code path "
11881                        + codePath + " - using " + codeRoot);
11882            } catch (IOException e) {
11883                // Can't canonicalize the code path -- shenanigans?
11884                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11885                return Environment.getRootDirectory().getPath();
11886            }
11887        }
11888        return codeRoot.getPath();
11889    }
11890
11891    /**
11892     * Derive and set the location of native libraries for the given package,
11893     * which varies depending on where and how the package was installed.
11894     */
11895    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11896        final ApplicationInfo info = pkg.applicationInfo;
11897        final String codePath = pkg.codePath;
11898        final File codeFile = new File(codePath);
11899        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11900        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11901
11902        info.nativeLibraryRootDir = null;
11903        info.nativeLibraryRootRequiresIsa = false;
11904        info.nativeLibraryDir = null;
11905        info.secondaryNativeLibraryDir = null;
11906
11907        if (isApkFile(codeFile)) {
11908            // Monolithic install
11909            if (bundledApp) {
11910                // If "/system/lib64/apkname" exists, assume that is the per-package
11911                // native library directory to use; otherwise use "/system/lib/apkname".
11912                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11913                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11914                        getPrimaryInstructionSet(info));
11915
11916                // This is a bundled system app so choose the path based on the ABI.
11917                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11918                // is just the default path.
11919                final String apkName = deriveCodePathName(codePath);
11920                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11921                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11922                        apkName).getAbsolutePath();
11923
11924                if (info.secondaryCpuAbi != null) {
11925                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11926                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11927                            secondaryLibDir, apkName).getAbsolutePath();
11928                }
11929            } else if (asecApp) {
11930                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11931                        .getAbsolutePath();
11932            } else {
11933                final String apkName = deriveCodePathName(codePath);
11934                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11935                        .getAbsolutePath();
11936            }
11937
11938            info.nativeLibraryRootRequiresIsa = false;
11939            info.nativeLibraryDir = info.nativeLibraryRootDir;
11940        } else {
11941            // Cluster install
11942            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11943            info.nativeLibraryRootRequiresIsa = true;
11944
11945            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11946                    getPrimaryInstructionSet(info)).getAbsolutePath();
11947
11948            if (info.secondaryCpuAbi != null) {
11949                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11950                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11951            }
11952        }
11953    }
11954
11955    /**
11956     * Calculate the abis and roots for a bundled app. These can uniquely
11957     * be determined from the contents of the system partition, i.e whether
11958     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11959     * of this information, and instead assume that the system was built
11960     * sensibly.
11961     */
11962    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11963                                           PackageSetting pkgSetting) {
11964        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11965
11966        // If "/system/lib64/apkname" exists, assume that is the per-package
11967        // native library directory to use; otherwise use "/system/lib/apkname".
11968        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11969        setBundledAppAbi(pkg, apkRoot, apkName);
11970        // pkgSetting might be null during rescan following uninstall of updates
11971        // to a bundled app, so accommodate that possibility.  The settings in
11972        // that case will be established later from the parsed package.
11973        //
11974        // If the settings aren't null, sync them up with what we've just derived.
11975        // note that apkRoot isn't stored in the package settings.
11976        if (pkgSetting != null) {
11977            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11978            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11979        }
11980    }
11981
11982    /**
11983     * Deduces the ABI of a bundled app and sets the relevant fields on the
11984     * parsed pkg object.
11985     *
11986     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11987     *        under which system libraries are installed.
11988     * @param apkName the name of the installed package.
11989     */
11990    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11991        final File codeFile = new File(pkg.codePath);
11992
11993        final boolean has64BitLibs;
11994        final boolean has32BitLibs;
11995        if (isApkFile(codeFile)) {
11996            // Monolithic install
11997            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11998            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11999        } else {
12000            // Cluster install
12001            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12002            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12003                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12004                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12005                has64BitLibs = (new File(rootDir, isa)).exists();
12006            } else {
12007                has64BitLibs = false;
12008            }
12009            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12010                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12011                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12012                has32BitLibs = (new File(rootDir, isa)).exists();
12013            } else {
12014                has32BitLibs = false;
12015            }
12016        }
12017
12018        if (has64BitLibs && !has32BitLibs) {
12019            // The package has 64 bit libs, but not 32 bit libs. Its primary
12020            // ABI should be 64 bit. We can safely assume here that the bundled
12021            // native libraries correspond to the most preferred ABI in the list.
12022
12023            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12024            pkg.applicationInfo.secondaryCpuAbi = null;
12025        } else if (has32BitLibs && !has64BitLibs) {
12026            // The package has 32 bit libs but not 64 bit libs. Its primary
12027            // ABI should be 32 bit.
12028
12029            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12030            pkg.applicationInfo.secondaryCpuAbi = null;
12031        } else if (has32BitLibs && has64BitLibs) {
12032            // The application has both 64 and 32 bit bundled libraries. We check
12033            // here that the app declares multiArch support, and warn if it doesn't.
12034            //
12035            // We will be lenient here and record both ABIs. The primary will be the
12036            // ABI that's higher on the list, i.e, a device that's configured to prefer
12037            // 64 bit apps will see a 64 bit primary ABI,
12038
12039            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12040                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12041            }
12042
12043            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12044                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12045                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12046            } else {
12047                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12048                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12049            }
12050        } else {
12051            pkg.applicationInfo.primaryCpuAbi = null;
12052            pkg.applicationInfo.secondaryCpuAbi = null;
12053        }
12054    }
12055
12056    private void killApplication(String pkgName, int appId, String reason) {
12057        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12058    }
12059
12060    private void killApplication(String pkgName, int appId, int userId, String reason) {
12061        // Request the ActivityManager to kill the process(only for existing packages)
12062        // so that we do not end up in a confused state while the user is still using the older
12063        // version of the application while the new one gets installed.
12064        final long token = Binder.clearCallingIdentity();
12065        try {
12066            IActivityManager am = ActivityManager.getService();
12067            if (am != null) {
12068                try {
12069                    am.killApplication(pkgName, appId, userId, reason);
12070                } catch (RemoteException e) {
12071                }
12072            }
12073        } finally {
12074            Binder.restoreCallingIdentity(token);
12075        }
12076    }
12077
12078    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12079        // Remove the parent package setting
12080        PackageSetting ps = (PackageSetting) pkg.mExtras;
12081        if (ps != null) {
12082            removePackageLI(ps, chatty);
12083        }
12084        // Remove the child package setting
12085        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12086        for (int i = 0; i < childCount; i++) {
12087            PackageParser.Package childPkg = pkg.childPackages.get(i);
12088            ps = (PackageSetting) childPkg.mExtras;
12089            if (ps != null) {
12090                removePackageLI(ps, chatty);
12091            }
12092        }
12093    }
12094
12095    void removePackageLI(PackageSetting ps, boolean chatty) {
12096        if (DEBUG_INSTALL) {
12097            if (chatty)
12098                Log.d(TAG, "Removing package " + ps.name);
12099        }
12100
12101        // writer
12102        synchronized (mPackages) {
12103            mPackages.remove(ps.name);
12104            final PackageParser.Package pkg = ps.pkg;
12105            if (pkg != null) {
12106                cleanPackageDataStructuresLILPw(pkg, chatty);
12107            }
12108        }
12109    }
12110
12111    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12112        if (DEBUG_INSTALL) {
12113            if (chatty)
12114                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12115        }
12116
12117        // writer
12118        synchronized (mPackages) {
12119            // Remove the parent package
12120            mPackages.remove(pkg.applicationInfo.packageName);
12121            cleanPackageDataStructuresLILPw(pkg, chatty);
12122
12123            // Remove the child packages
12124            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12125            for (int i = 0; i < childCount; i++) {
12126                PackageParser.Package childPkg = pkg.childPackages.get(i);
12127                mPackages.remove(childPkg.applicationInfo.packageName);
12128                cleanPackageDataStructuresLILPw(childPkg, chatty);
12129            }
12130        }
12131    }
12132
12133    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12134        int N = pkg.providers.size();
12135        StringBuilder r = null;
12136        int i;
12137        for (i=0; i<N; i++) {
12138            PackageParser.Provider p = pkg.providers.get(i);
12139            mProviders.removeProvider(p);
12140            if (p.info.authority == null) {
12141
12142                /* There was another ContentProvider with this authority when
12143                 * this app was installed so this authority is null,
12144                 * Ignore it as we don't have to unregister the provider.
12145                 */
12146                continue;
12147            }
12148            String names[] = p.info.authority.split(";");
12149            for (int j = 0; j < names.length; j++) {
12150                if (mProvidersByAuthority.get(names[j]) == p) {
12151                    mProvidersByAuthority.remove(names[j]);
12152                    if (DEBUG_REMOVE) {
12153                        if (chatty)
12154                            Log.d(TAG, "Unregistered content provider: " + names[j]
12155                                    + ", className = " + p.info.name + ", isSyncable = "
12156                                    + p.info.isSyncable);
12157                    }
12158                }
12159            }
12160            if (DEBUG_REMOVE && chatty) {
12161                if (r == null) {
12162                    r = new StringBuilder(256);
12163                } else {
12164                    r.append(' ');
12165                }
12166                r.append(p.info.name);
12167            }
12168        }
12169        if (r != null) {
12170            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12171        }
12172
12173        N = pkg.services.size();
12174        r = null;
12175        for (i=0; i<N; i++) {
12176            PackageParser.Service s = pkg.services.get(i);
12177            mServices.removeService(s);
12178            if (chatty) {
12179                if (r == null) {
12180                    r = new StringBuilder(256);
12181                } else {
12182                    r.append(' ');
12183                }
12184                r.append(s.info.name);
12185            }
12186        }
12187        if (r != null) {
12188            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12189        }
12190
12191        N = pkg.receivers.size();
12192        r = null;
12193        for (i=0; i<N; i++) {
12194            PackageParser.Activity a = pkg.receivers.get(i);
12195            mReceivers.removeActivity(a, "receiver");
12196            if (DEBUG_REMOVE && chatty) {
12197                if (r == null) {
12198                    r = new StringBuilder(256);
12199                } else {
12200                    r.append(' ');
12201                }
12202                r.append(a.info.name);
12203            }
12204        }
12205        if (r != null) {
12206            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12207        }
12208
12209        N = pkg.activities.size();
12210        r = null;
12211        for (i=0; i<N; i++) {
12212            PackageParser.Activity a = pkg.activities.get(i);
12213            mActivities.removeActivity(a, "activity");
12214            if (DEBUG_REMOVE && chatty) {
12215                if (r == null) {
12216                    r = new StringBuilder(256);
12217                } else {
12218                    r.append(' ');
12219                }
12220                r.append(a.info.name);
12221            }
12222        }
12223        if (r != null) {
12224            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12225        }
12226
12227        mPermissionManager.removeAllPermissions(pkg, chatty);
12228
12229        N = pkg.instrumentation.size();
12230        r = null;
12231        for (i=0; i<N; i++) {
12232            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12233            mInstrumentation.remove(a.getComponentName());
12234            if (DEBUG_REMOVE && chatty) {
12235                if (r == null) {
12236                    r = new StringBuilder(256);
12237                } else {
12238                    r.append(' ');
12239                }
12240                r.append(a.info.name);
12241            }
12242        }
12243        if (r != null) {
12244            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12245        }
12246
12247        r = null;
12248        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12249            // Only system apps can hold shared libraries.
12250            if (pkg.libraryNames != null) {
12251                for (i = 0; i < pkg.libraryNames.size(); i++) {
12252                    String name = pkg.libraryNames.get(i);
12253                    if (removeSharedLibraryLPw(name, 0)) {
12254                        if (DEBUG_REMOVE && chatty) {
12255                            if (r == null) {
12256                                r = new StringBuilder(256);
12257                            } else {
12258                                r.append(' ');
12259                            }
12260                            r.append(name);
12261                        }
12262                    }
12263                }
12264            }
12265        }
12266
12267        r = null;
12268
12269        // Any package can hold static shared libraries.
12270        if (pkg.staticSharedLibName != null) {
12271            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12272                if (DEBUG_REMOVE && chatty) {
12273                    if (r == null) {
12274                        r = new StringBuilder(256);
12275                    } else {
12276                        r.append(' ');
12277                    }
12278                    r.append(pkg.staticSharedLibName);
12279                }
12280            }
12281        }
12282
12283        if (r != null) {
12284            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12285        }
12286    }
12287
12288
12289    final class ActivityIntentResolver
12290            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12291        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12292                boolean defaultOnly, int userId) {
12293            if (!sUserManager.exists(userId)) return null;
12294            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12295            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12296        }
12297
12298        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12299                int userId) {
12300            if (!sUserManager.exists(userId)) return null;
12301            mFlags = flags;
12302            return super.queryIntent(intent, resolvedType,
12303                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12304                    userId);
12305        }
12306
12307        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12308                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12309            if (!sUserManager.exists(userId)) return null;
12310            if (packageActivities == null) {
12311                return null;
12312            }
12313            mFlags = flags;
12314            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12315            final int N = packageActivities.size();
12316            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12317                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12318
12319            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12320            for (int i = 0; i < N; ++i) {
12321                intentFilters = packageActivities.get(i).intents;
12322                if (intentFilters != null && intentFilters.size() > 0) {
12323                    PackageParser.ActivityIntentInfo[] array =
12324                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12325                    intentFilters.toArray(array);
12326                    listCut.add(array);
12327                }
12328            }
12329            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12330        }
12331
12332        /**
12333         * Finds a privileged activity that matches the specified activity names.
12334         */
12335        private PackageParser.Activity findMatchingActivity(
12336                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12337            for (PackageParser.Activity sysActivity : activityList) {
12338                if (sysActivity.info.name.equals(activityInfo.name)) {
12339                    return sysActivity;
12340                }
12341                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12342                    return sysActivity;
12343                }
12344                if (sysActivity.info.targetActivity != null) {
12345                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12346                        return sysActivity;
12347                    }
12348                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12349                        return sysActivity;
12350                    }
12351                }
12352            }
12353            return null;
12354        }
12355
12356        public class IterGenerator<E> {
12357            public Iterator<E> generate(ActivityIntentInfo info) {
12358                return null;
12359            }
12360        }
12361
12362        public class ActionIterGenerator extends IterGenerator<String> {
12363            @Override
12364            public Iterator<String> generate(ActivityIntentInfo info) {
12365                return info.actionsIterator();
12366            }
12367        }
12368
12369        public class CategoriesIterGenerator extends IterGenerator<String> {
12370            @Override
12371            public Iterator<String> generate(ActivityIntentInfo info) {
12372                return info.categoriesIterator();
12373            }
12374        }
12375
12376        public class SchemesIterGenerator extends IterGenerator<String> {
12377            @Override
12378            public Iterator<String> generate(ActivityIntentInfo info) {
12379                return info.schemesIterator();
12380            }
12381        }
12382
12383        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12384            @Override
12385            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12386                return info.authoritiesIterator();
12387            }
12388        }
12389
12390        /**
12391         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12392         * MODIFIED. Do not pass in a list that should not be changed.
12393         */
12394        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12395                IterGenerator<T> generator, Iterator<T> searchIterator) {
12396            // loop through the set of actions; every one must be found in the intent filter
12397            while (searchIterator.hasNext()) {
12398                // we must have at least one filter in the list to consider a match
12399                if (intentList.size() == 0) {
12400                    break;
12401                }
12402
12403                final T searchAction = searchIterator.next();
12404
12405                // loop through the set of intent filters
12406                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12407                while (intentIter.hasNext()) {
12408                    final ActivityIntentInfo intentInfo = intentIter.next();
12409                    boolean selectionFound = false;
12410
12411                    // loop through the intent filter's selection criteria; at least one
12412                    // of them must match the searched criteria
12413                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12414                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12415                        final T intentSelection = intentSelectionIter.next();
12416                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12417                            selectionFound = true;
12418                            break;
12419                        }
12420                    }
12421
12422                    // the selection criteria wasn't found in this filter's set; this filter
12423                    // is not a potential match
12424                    if (!selectionFound) {
12425                        intentIter.remove();
12426                    }
12427                }
12428            }
12429        }
12430
12431        private boolean isProtectedAction(ActivityIntentInfo filter) {
12432            final Iterator<String> actionsIter = filter.actionsIterator();
12433            while (actionsIter != null && actionsIter.hasNext()) {
12434                final String filterAction = actionsIter.next();
12435                if (PROTECTED_ACTIONS.contains(filterAction)) {
12436                    return true;
12437                }
12438            }
12439            return false;
12440        }
12441
12442        /**
12443         * Adjusts the priority of the given intent filter according to policy.
12444         * <p>
12445         * <ul>
12446         * <li>The priority for non privileged applications is capped to '0'</li>
12447         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12448         * <li>The priority for unbundled updates to privileged applications is capped to the
12449         *      priority defined on the system partition</li>
12450         * </ul>
12451         * <p>
12452         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12453         * allowed to obtain any priority on any action.
12454         */
12455        private void adjustPriority(
12456                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12457            // nothing to do; priority is fine as-is
12458            if (intent.getPriority() <= 0) {
12459                return;
12460            }
12461
12462            final ActivityInfo activityInfo = intent.activity.info;
12463            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12464
12465            final boolean privilegedApp =
12466                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12467            if (!privilegedApp) {
12468                // non-privileged applications can never define a priority >0
12469                if (DEBUG_FILTERS) {
12470                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12471                            + " package: " + applicationInfo.packageName
12472                            + " activity: " + intent.activity.className
12473                            + " origPrio: " + intent.getPriority());
12474                }
12475                intent.setPriority(0);
12476                return;
12477            }
12478
12479            if (systemActivities == null) {
12480                // the system package is not disabled; we're parsing the system partition
12481                if (isProtectedAction(intent)) {
12482                    if (mDeferProtectedFilters) {
12483                        // We can't deal with these just yet. No component should ever obtain a
12484                        // >0 priority for a protected actions, with ONE exception -- the setup
12485                        // wizard. The setup wizard, however, cannot be known until we're able to
12486                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12487                        // until all intent filters have been processed. Chicken, meet egg.
12488                        // Let the filter temporarily have a high priority and rectify the
12489                        // priorities after all system packages have been scanned.
12490                        mProtectedFilters.add(intent);
12491                        if (DEBUG_FILTERS) {
12492                            Slog.i(TAG, "Protected action; save for later;"
12493                                    + " package: " + applicationInfo.packageName
12494                                    + " activity: " + intent.activity.className
12495                                    + " origPrio: " + intent.getPriority());
12496                        }
12497                        return;
12498                    } else {
12499                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12500                            Slog.i(TAG, "No setup wizard;"
12501                                + " All protected intents capped to priority 0");
12502                        }
12503                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12504                            if (DEBUG_FILTERS) {
12505                                Slog.i(TAG, "Found setup wizard;"
12506                                    + " allow priority " + intent.getPriority() + ";"
12507                                    + " package: " + intent.activity.info.packageName
12508                                    + " activity: " + intent.activity.className
12509                                    + " priority: " + intent.getPriority());
12510                            }
12511                            // setup wizard gets whatever it wants
12512                            return;
12513                        }
12514                        if (DEBUG_FILTERS) {
12515                            Slog.i(TAG, "Protected action; cap priority to 0;"
12516                                    + " package: " + intent.activity.info.packageName
12517                                    + " activity: " + intent.activity.className
12518                                    + " origPrio: " + intent.getPriority());
12519                        }
12520                        intent.setPriority(0);
12521                        return;
12522                    }
12523                }
12524                // privileged apps on the system image get whatever priority they request
12525                return;
12526            }
12527
12528            // privileged app unbundled update ... try to find the same activity
12529            final PackageParser.Activity foundActivity =
12530                    findMatchingActivity(systemActivities, activityInfo);
12531            if (foundActivity == null) {
12532                // this is a new activity; it cannot obtain >0 priority
12533                if (DEBUG_FILTERS) {
12534                    Slog.i(TAG, "New activity; cap priority to 0;"
12535                            + " package: " + applicationInfo.packageName
12536                            + " activity: " + intent.activity.className
12537                            + " origPrio: " + intent.getPriority());
12538                }
12539                intent.setPriority(0);
12540                return;
12541            }
12542
12543            // found activity, now check for filter equivalence
12544
12545            // a shallow copy is enough; we modify the list, not its contents
12546            final List<ActivityIntentInfo> intentListCopy =
12547                    new ArrayList<>(foundActivity.intents);
12548            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12549
12550            // find matching action subsets
12551            final Iterator<String> actionsIterator = intent.actionsIterator();
12552            if (actionsIterator != null) {
12553                getIntentListSubset(
12554                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12555                if (intentListCopy.size() == 0) {
12556                    // no more intents to match; we're not equivalent
12557                    if (DEBUG_FILTERS) {
12558                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12559                                + " package: " + applicationInfo.packageName
12560                                + " activity: " + intent.activity.className
12561                                + " origPrio: " + intent.getPriority());
12562                    }
12563                    intent.setPriority(0);
12564                    return;
12565                }
12566            }
12567
12568            // find matching category subsets
12569            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12570            if (categoriesIterator != null) {
12571                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12572                        categoriesIterator);
12573                if (intentListCopy.size() == 0) {
12574                    // no more intents to match; we're not equivalent
12575                    if (DEBUG_FILTERS) {
12576                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12577                                + " package: " + applicationInfo.packageName
12578                                + " activity: " + intent.activity.className
12579                                + " origPrio: " + intent.getPriority());
12580                    }
12581                    intent.setPriority(0);
12582                    return;
12583                }
12584            }
12585
12586            // find matching schemes subsets
12587            final Iterator<String> schemesIterator = intent.schemesIterator();
12588            if (schemesIterator != null) {
12589                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12590                        schemesIterator);
12591                if (intentListCopy.size() == 0) {
12592                    // no more intents to match; we're not equivalent
12593                    if (DEBUG_FILTERS) {
12594                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12595                                + " package: " + applicationInfo.packageName
12596                                + " activity: " + intent.activity.className
12597                                + " origPrio: " + intent.getPriority());
12598                    }
12599                    intent.setPriority(0);
12600                    return;
12601                }
12602            }
12603
12604            // find matching authorities subsets
12605            final Iterator<IntentFilter.AuthorityEntry>
12606                    authoritiesIterator = intent.authoritiesIterator();
12607            if (authoritiesIterator != null) {
12608                getIntentListSubset(intentListCopy,
12609                        new AuthoritiesIterGenerator(),
12610                        authoritiesIterator);
12611                if (intentListCopy.size() == 0) {
12612                    // no more intents to match; we're not equivalent
12613                    if (DEBUG_FILTERS) {
12614                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12615                                + " package: " + applicationInfo.packageName
12616                                + " activity: " + intent.activity.className
12617                                + " origPrio: " + intent.getPriority());
12618                    }
12619                    intent.setPriority(0);
12620                    return;
12621                }
12622            }
12623
12624            // we found matching filter(s); app gets the max priority of all intents
12625            int cappedPriority = 0;
12626            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12627                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12628            }
12629            if (intent.getPriority() > cappedPriority) {
12630                if (DEBUG_FILTERS) {
12631                    Slog.i(TAG, "Found matching filter(s);"
12632                            + " cap priority to " + cappedPriority + ";"
12633                            + " package: " + applicationInfo.packageName
12634                            + " activity: " + intent.activity.className
12635                            + " origPrio: " + intent.getPriority());
12636                }
12637                intent.setPriority(cappedPriority);
12638                return;
12639            }
12640            // all this for nothing; the requested priority was <= what was on the system
12641        }
12642
12643        public final void addActivity(PackageParser.Activity a, String type) {
12644            mActivities.put(a.getComponentName(), a);
12645            if (DEBUG_SHOW_INFO)
12646                Log.v(
12647                TAG, "  " + type + " " +
12648                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12649            if (DEBUG_SHOW_INFO)
12650                Log.v(TAG, "    Class=" + a.info.name);
12651            final int NI = a.intents.size();
12652            for (int j=0; j<NI; j++) {
12653                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12654                if ("activity".equals(type)) {
12655                    final PackageSetting ps =
12656                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12657                    final List<PackageParser.Activity> systemActivities =
12658                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12659                    adjustPriority(systemActivities, intent);
12660                }
12661                if (DEBUG_SHOW_INFO) {
12662                    Log.v(TAG, "    IntentFilter:");
12663                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12664                }
12665                if (!intent.debugCheck()) {
12666                    Log.w(TAG, "==> For Activity " + a.info.name);
12667                }
12668                addFilter(intent);
12669            }
12670        }
12671
12672        public final void removeActivity(PackageParser.Activity a, String type) {
12673            mActivities.remove(a.getComponentName());
12674            if (DEBUG_SHOW_INFO) {
12675                Log.v(TAG, "  " + type + " "
12676                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12677                                : a.info.name) + ":");
12678                Log.v(TAG, "    Class=" + a.info.name);
12679            }
12680            final int NI = a.intents.size();
12681            for (int j=0; j<NI; j++) {
12682                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12683                if (DEBUG_SHOW_INFO) {
12684                    Log.v(TAG, "    IntentFilter:");
12685                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12686                }
12687                removeFilter(intent);
12688            }
12689        }
12690
12691        @Override
12692        protected boolean allowFilterResult(
12693                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12694            ActivityInfo filterAi = filter.activity.info;
12695            for (int i=dest.size()-1; i>=0; i--) {
12696                ActivityInfo destAi = dest.get(i).activityInfo;
12697                if (destAi.name == filterAi.name
12698                        && destAi.packageName == filterAi.packageName) {
12699                    return false;
12700                }
12701            }
12702            return true;
12703        }
12704
12705        @Override
12706        protected ActivityIntentInfo[] newArray(int size) {
12707            return new ActivityIntentInfo[size];
12708        }
12709
12710        @Override
12711        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12712            if (!sUserManager.exists(userId)) return true;
12713            PackageParser.Package p = filter.activity.owner;
12714            if (p != null) {
12715                PackageSetting ps = (PackageSetting)p.mExtras;
12716                if (ps != null) {
12717                    // System apps are never considered stopped for purposes of
12718                    // filtering, because there may be no way for the user to
12719                    // actually re-launch them.
12720                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12721                            && ps.getStopped(userId);
12722                }
12723            }
12724            return false;
12725        }
12726
12727        @Override
12728        protected boolean isPackageForFilter(String packageName,
12729                PackageParser.ActivityIntentInfo info) {
12730            return packageName.equals(info.activity.owner.packageName);
12731        }
12732
12733        @Override
12734        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12735                int match, int userId) {
12736            if (!sUserManager.exists(userId)) return null;
12737            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12738                return null;
12739            }
12740            final PackageParser.Activity activity = info.activity;
12741            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12742            if (ps == null) {
12743                return null;
12744            }
12745            final PackageUserState userState = ps.readUserState(userId);
12746            ActivityInfo ai =
12747                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12748            if (ai == null) {
12749                return null;
12750            }
12751            final boolean matchExplicitlyVisibleOnly =
12752                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12753            final boolean matchVisibleToInstantApp =
12754                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12755            final boolean componentVisible =
12756                    matchVisibleToInstantApp
12757                    && info.isVisibleToInstantApp()
12758                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12759            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12760            // throw out filters that aren't visible to ephemeral apps
12761            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12762                return null;
12763            }
12764            // throw out instant app filters if we're not explicitly requesting them
12765            if (!matchInstantApp && userState.instantApp) {
12766                return null;
12767            }
12768            // throw out instant app filters if updates are available; will trigger
12769            // instant app resolution
12770            if (userState.instantApp && ps.isUpdateAvailable()) {
12771                return null;
12772            }
12773            final ResolveInfo res = new ResolveInfo();
12774            res.activityInfo = ai;
12775            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12776                res.filter = info;
12777            }
12778            if (info != null) {
12779                res.handleAllWebDataURI = info.handleAllWebDataURI();
12780            }
12781            res.priority = info.getPriority();
12782            res.preferredOrder = activity.owner.mPreferredOrder;
12783            //System.out.println("Result: " + res.activityInfo.className +
12784            //                   " = " + res.priority);
12785            res.match = match;
12786            res.isDefault = info.hasDefault;
12787            res.labelRes = info.labelRes;
12788            res.nonLocalizedLabel = info.nonLocalizedLabel;
12789            if (userNeedsBadging(userId)) {
12790                res.noResourceId = true;
12791            } else {
12792                res.icon = info.icon;
12793            }
12794            res.iconResourceId = info.icon;
12795            res.system = res.activityInfo.applicationInfo.isSystemApp();
12796            res.isInstantAppAvailable = userState.instantApp;
12797            return res;
12798        }
12799
12800        @Override
12801        protected void sortResults(List<ResolveInfo> results) {
12802            Collections.sort(results, mResolvePrioritySorter);
12803        }
12804
12805        @Override
12806        protected void dumpFilter(PrintWriter out, String prefix,
12807                PackageParser.ActivityIntentInfo filter) {
12808            out.print(prefix); out.print(
12809                    Integer.toHexString(System.identityHashCode(filter.activity)));
12810                    out.print(' ');
12811                    filter.activity.printComponentShortName(out);
12812                    out.print(" filter ");
12813                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12814        }
12815
12816        @Override
12817        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12818            return filter.activity;
12819        }
12820
12821        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12822            PackageParser.Activity activity = (PackageParser.Activity)label;
12823            out.print(prefix); out.print(
12824                    Integer.toHexString(System.identityHashCode(activity)));
12825                    out.print(' ');
12826                    activity.printComponentShortName(out);
12827            if (count > 1) {
12828                out.print(" ("); out.print(count); out.print(" filters)");
12829            }
12830            out.println();
12831        }
12832
12833        // Keys are String (activity class name), values are Activity.
12834        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12835                = new ArrayMap<ComponentName, PackageParser.Activity>();
12836        private int mFlags;
12837    }
12838
12839    private final class ServiceIntentResolver
12840            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12841        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12842                boolean defaultOnly, int userId) {
12843            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12844            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12845        }
12846
12847        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12848                int userId) {
12849            if (!sUserManager.exists(userId)) return null;
12850            mFlags = flags;
12851            return super.queryIntent(intent, resolvedType,
12852                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12853                    userId);
12854        }
12855
12856        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12857                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12858            if (!sUserManager.exists(userId)) return null;
12859            if (packageServices == null) {
12860                return null;
12861            }
12862            mFlags = flags;
12863            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12864            final int N = packageServices.size();
12865            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12866                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12867
12868            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12869            for (int i = 0; i < N; ++i) {
12870                intentFilters = packageServices.get(i).intents;
12871                if (intentFilters != null && intentFilters.size() > 0) {
12872                    PackageParser.ServiceIntentInfo[] array =
12873                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12874                    intentFilters.toArray(array);
12875                    listCut.add(array);
12876                }
12877            }
12878            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12879        }
12880
12881        public final void addService(PackageParser.Service s) {
12882            mServices.put(s.getComponentName(), s);
12883            if (DEBUG_SHOW_INFO) {
12884                Log.v(TAG, "  "
12885                        + (s.info.nonLocalizedLabel != null
12886                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12887                Log.v(TAG, "    Class=" + s.info.name);
12888            }
12889            final int NI = s.intents.size();
12890            int j;
12891            for (j=0; j<NI; j++) {
12892                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12893                if (DEBUG_SHOW_INFO) {
12894                    Log.v(TAG, "    IntentFilter:");
12895                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12896                }
12897                if (!intent.debugCheck()) {
12898                    Log.w(TAG, "==> For Service " + s.info.name);
12899                }
12900                addFilter(intent);
12901            }
12902        }
12903
12904        public final void removeService(PackageParser.Service s) {
12905            mServices.remove(s.getComponentName());
12906            if (DEBUG_SHOW_INFO) {
12907                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12908                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12909                Log.v(TAG, "    Class=" + s.info.name);
12910            }
12911            final int NI = s.intents.size();
12912            int j;
12913            for (j=0; j<NI; j++) {
12914                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12915                if (DEBUG_SHOW_INFO) {
12916                    Log.v(TAG, "    IntentFilter:");
12917                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12918                }
12919                removeFilter(intent);
12920            }
12921        }
12922
12923        @Override
12924        protected boolean allowFilterResult(
12925                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12926            ServiceInfo filterSi = filter.service.info;
12927            for (int i=dest.size()-1; i>=0; i--) {
12928                ServiceInfo destAi = dest.get(i).serviceInfo;
12929                if (destAi.name == filterSi.name
12930                        && destAi.packageName == filterSi.packageName) {
12931                    return false;
12932                }
12933            }
12934            return true;
12935        }
12936
12937        @Override
12938        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12939            return new PackageParser.ServiceIntentInfo[size];
12940        }
12941
12942        @Override
12943        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12944            if (!sUserManager.exists(userId)) return true;
12945            PackageParser.Package p = filter.service.owner;
12946            if (p != null) {
12947                PackageSetting ps = (PackageSetting)p.mExtras;
12948                if (ps != null) {
12949                    // System apps are never considered stopped for purposes of
12950                    // filtering, because there may be no way for the user to
12951                    // actually re-launch them.
12952                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12953                            && ps.getStopped(userId);
12954                }
12955            }
12956            return false;
12957        }
12958
12959        @Override
12960        protected boolean isPackageForFilter(String packageName,
12961                PackageParser.ServiceIntentInfo info) {
12962            return packageName.equals(info.service.owner.packageName);
12963        }
12964
12965        @Override
12966        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12967                int match, int userId) {
12968            if (!sUserManager.exists(userId)) return null;
12969            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12970            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12971                return null;
12972            }
12973            final PackageParser.Service service = info.service;
12974            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12975            if (ps == null) {
12976                return null;
12977            }
12978            final PackageUserState userState = ps.readUserState(userId);
12979            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12980                    userState, userId);
12981            if (si == null) {
12982                return null;
12983            }
12984            final boolean matchVisibleToInstantApp =
12985                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12986            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12987            // throw out filters that aren't visible to ephemeral apps
12988            if (matchVisibleToInstantApp
12989                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12990                return null;
12991            }
12992            // throw out ephemeral filters if we're not explicitly requesting them
12993            if (!isInstantApp && userState.instantApp) {
12994                return null;
12995            }
12996            // throw out instant app filters if updates are available; will trigger
12997            // instant app resolution
12998            if (userState.instantApp && ps.isUpdateAvailable()) {
12999                return null;
13000            }
13001            final ResolveInfo res = new ResolveInfo();
13002            res.serviceInfo = si;
13003            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13004                res.filter = filter;
13005            }
13006            res.priority = info.getPriority();
13007            res.preferredOrder = service.owner.mPreferredOrder;
13008            res.match = match;
13009            res.isDefault = info.hasDefault;
13010            res.labelRes = info.labelRes;
13011            res.nonLocalizedLabel = info.nonLocalizedLabel;
13012            res.icon = info.icon;
13013            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13014            return res;
13015        }
13016
13017        @Override
13018        protected void sortResults(List<ResolveInfo> results) {
13019            Collections.sort(results, mResolvePrioritySorter);
13020        }
13021
13022        @Override
13023        protected void dumpFilter(PrintWriter out, String prefix,
13024                PackageParser.ServiceIntentInfo filter) {
13025            out.print(prefix); out.print(
13026                    Integer.toHexString(System.identityHashCode(filter.service)));
13027                    out.print(' ');
13028                    filter.service.printComponentShortName(out);
13029                    out.print(" filter ");
13030                    out.print(Integer.toHexString(System.identityHashCode(filter)));
13031                    if (filter.service.info.permission != null) {
13032                        out.print(" permission "); out.println(filter.service.info.permission);
13033                    } else {
13034                        out.println();
13035                    }
13036        }
13037
13038        @Override
13039        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13040            return filter.service;
13041        }
13042
13043        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13044            PackageParser.Service service = (PackageParser.Service)label;
13045            out.print(prefix); out.print(
13046                    Integer.toHexString(System.identityHashCode(service)));
13047                    out.print(' ');
13048                    service.printComponentShortName(out);
13049            if (count > 1) {
13050                out.print(" ("); out.print(count); out.print(" filters)");
13051            }
13052            out.println();
13053        }
13054
13055//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13056//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13057//            final List<ResolveInfo> retList = Lists.newArrayList();
13058//            while (i.hasNext()) {
13059//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13060//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13061//                    retList.add(resolveInfo);
13062//                }
13063//            }
13064//            return retList;
13065//        }
13066
13067        // Keys are String (activity class name), values are Activity.
13068        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13069                = new ArrayMap<ComponentName, PackageParser.Service>();
13070        private int mFlags;
13071    }
13072
13073    private final class ProviderIntentResolver
13074            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13075        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13076                boolean defaultOnly, int userId) {
13077            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13078            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13079        }
13080
13081        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13082                int userId) {
13083            if (!sUserManager.exists(userId))
13084                return null;
13085            mFlags = flags;
13086            return super.queryIntent(intent, resolvedType,
13087                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13088                    userId);
13089        }
13090
13091        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13092                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13093            if (!sUserManager.exists(userId))
13094                return null;
13095            if (packageProviders == null) {
13096                return null;
13097            }
13098            mFlags = flags;
13099            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13100            final int N = packageProviders.size();
13101            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13102                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13103
13104            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13105            for (int i = 0; i < N; ++i) {
13106                intentFilters = packageProviders.get(i).intents;
13107                if (intentFilters != null && intentFilters.size() > 0) {
13108                    PackageParser.ProviderIntentInfo[] array =
13109                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13110                    intentFilters.toArray(array);
13111                    listCut.add(array);
13112                }
13113            }
13114            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13115        }
13116
13117        public final void addProvider(PackageParser.Provider p) {
13118            if (mProviders.containsKey(p.getComponentName())) {
13119                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13120                return;
13121            }
13122
13123            mProviders.put(p.getComponentName(), p);
13124            if (DEBUG_SHOW_INFO) {
13125                Log.v(TAG, "  "
13126                        + (p.info.nonLocalizedLabel != null
13127                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13128                Log.v(TAG, "    Class=" + p.info.name);
13129            }
13130            final int NI = p.intents.size();
13131            int j;
13132            for (j = 0; j < NI; j++) {
13133                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13134                if (DEBUG_SHOW_INFO) {
13135                    Log.v(TAG, "    IntentFilter:");
13136                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13137                }
13138                if (!intent.debugCheck()) {
13139                    Log.w(TAG, "==> For Provider " + p.info.name);
13140                }
13141                addFilter(intent);
13142            }
13143        }
13144
13145        public final void removeProvider(PackageParser.Provider p) {
13146            mProviders.remove(p.getComponentName());
13147            if (DEBUG_SHOW_INFO) {
13148                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13149                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13150                Log.v(TAG, "    Class=" + p.info.name);
13151            }
13152            final int NI = p.intents.size();
13153            int j;
13154            for (j = 0; j < NI; j++) {
13155                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13156                if (DEBUG_SHOW_INFO) {
13157                    Log.v(TAG, "    IntentFilter:");
13158                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13159                }
13160                removeFilter(intent);
13161            }
13162        }
13163
13164        @Override
13165        protected boolean allowFilterResult(
13166                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13167            ProviderInfo filterPi = filter.provider.info;
13168            for (int i = dest.size() - 1; i >= 0; i--) {
13169                ProviderInfo destPi = dest.get(i).providerInfo;
13170                if (destPi.name == filterPi.name
13171                        && destPi.packageName == filterPi.packageName) {
13172                    return false;
13173                }
13174            }
13175            return true;
13176        }
13177
13178        @Override
13179        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13180            return new PackageParser.ProviderIntentInfo[size];
13181        }
13182
13183        @Override
13184        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13185            if (!sUserManager.exists(userId))
13186                return true;
13187            PackageParser.Package p = filter.provider.owner;
13188            if (p != null) {
13189                PackageSetting ps = (PackageSetting) p.mExtras;
13190                if (ps != null) {
13191                    // System apps are never considered stopped for purposes of
13192                    // filtering, because there may be no way for the user to
13193                    // actually re-launch them.
13194                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13195                            && ps.getStopped(userId);
13196                }
13197            }
13198            return false;
13199        }
13200
13201        @Override
13202        protected boolean isPackageForFilter(String packageName,
13203                PackageParser.ProviderIntentInfo info) {
13204            return packageName.equals(info.provider.owner.packageName);
13205        }
13206
13207        @Override
13208        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13209                int match, int userId) {
13210            if (!sUserManager.exists(userId))
13211                return null;
13212            final PackageParser.ProviderIntentInfo info = filter;
13213            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13214                return null;
13215            }
13216            final PackageParser.Provider provider = info.provider;
13217            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13218            if (ps == null) {
13219                return null;
13220            }
13221            final PackageUserState userState = ps.readUserState(userId);
13222            final boolean matchVisibleToInstantApp =
13223                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13224            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13225            // throw out filters that aren't visible to instant applications
13226            if (matchVisibleToInstantApp
13227                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13228                return null;
13229            }
13230            // throw out instant application filters if we're not explicitly requesting them
13231            if (!isInstantApp && userState.instantApp) {
13232                return null;
13233            }
13234            // throw out instant application filters if updates are available; will trigger
13235            // instant application resolution
13236            if (userState.instantApp && ps.isUpdateAvailable()) {
13237                return null;
13238            }
13239            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13240                    userState, userId);
13241            if (pi == null) {
13242                return null;
13243            }
13244            final ResolveInfo res = new ResolveInfo();
13245            res.providerInfo = pi;
13246            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13247                res.filter = filter;
13248            }
13249            res.priority = info.getPriority();
13250            res.preferredOrder = provider.owner.mPreferredOrder;
13251            res.match = match;
13252            res.isDefault = info.hasDefault;
13253            res.labelRes = info.labelRes;
13254            res.nonLocalizedLabel = info.nonLocalizedLabel;
13255            res.icon = info.icon;
13256            res.system = res.providerInfo.applicationInfo.isSystemApp();
13257            return res;
13258        }
13259
13260        @Override
13261        protected void sortResults(List<ResolveInfo> results) {
13262            Collections.sort(results, mResolvePrioritySorter);
13263        }
13264
13265        @Override
13266        protected void dumpFilter(PrintWriter out, String prefix,
13267                PackageParser.ProviderIntentInfo filter) {
13268            out.print(prefix);
13269            out.print(
13270                    Integer.toHexString(System.identityHashCode(filter.provider)));
13271            out.print(' ');
13272            filter.provider.printComponentShortName(out);
13273            out.print(" filter ");
13274            out.println(Integer.toHexString(System.identityHashCode(filter)));
13275        }
13276
13277        @Override
13278        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13279            return filter.provider;
13280        }
13281
13282        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13283            PackageParser.Provider provider = (PackageParser.Provider)label;
13284            out.print(prefix); out.print(
13285                    Integer.toHexString(System.identityHashCode(provider)));
13286                    out.print(' ');
13287                    provider.printComponentShortName(out);
13288            if (count > 1) {
13289                out.print(" ("); out.print(count); out.print(" filters)");
13290            }
13291            out.println();
13292        }
13293
13294        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13295                = new ArrayMap<ComponentName, PackageParser.Provider>();
13296        private int mFlags;
13297    }
13298
13299    static final class InstantAppIntentResolver
13300            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13301            AuxiliaryResolveInfo.AuxiliaryFilter> {
13302        /**
13303         * The result that has the highest defined order. Ordering applies on a
13304         * per-package basis. Mapping is from package name to Pair of order and
13305         * EphemeralResolveInfo.
13306         * <p>
13307         * NOTE: This is implemented as a field variable for convenience and efficiency.
13308         * By having a field variable, we're able to track filter ordering as soon as
13309         * a non-zero order is defined. Otherwise, multiple loops across the result set
13310         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13311         * this needs to be contained entirely within {@link #filterResults}.
13312         */
13313        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13314
13315        @Override
13316        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13317            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13318        }
13319
13320        @Override
13321        protected boolean isPackageForFilter(String packageName,
13322                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13323            return true;
13324        }
13325
13326        @Override
13327        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13328                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13329            if (!sUserManager.exists(userId)) {
13330                return null;
13331            }
13332            final String packageName = responseObj.resolveInfo.getPackageName();
13333            final Integer order = responseObj.getOrder();
13334            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13335                    mOrderResult.get(packageName);
13336            // ordering is enabled and this item's order isn't high enough
13337            if (lastOrderResult != null && lastOrderResult.first >= order) {
13338                return null;
13339            }
13340            final InstantAppResolveInfo res = responseObj.resolveInfo;
13341            if (order > 0) {
13342                // non-zero order, enable ordering
13343                mOrderResult.put(packageName, new Pair<>(order, res));
13344            }
13345            return responseObj;
13346        }
13347
13348        @Override
13349        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13350            // only do work if ordering is enabled [most of the time it won't be]
13351            if (mOrderResult.size() == 0) {
13352                return;
13353            }
13354            int resultSize = results.size();
13355            for (int i = 0; i < resultSize; i++) {
13356                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13357                final String packageName = info.getPackageName();
13358                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13359                if (savedInfo == null) {
13360                    // package doesn't having ordering
13361                    continue;
13362                }
13363                if (savedInfo.second == info) {
13364                    // circled back to the highest ordered item; remove from order list
13365                    mOrderResult.remove(packageName);
13366                    if (mOrderResult.size() == 0) {
13367                        // no more ordered items
13368                        break;
13369                    }
13370                    continue;
13371                }
13372                // item has a worse order, remove it from the result list
13373                results.remove(i);
13374                resultSize--;
13375                i--;
13376            }
13377        }
13378    }
13379
13380    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13381            new Comparator<ResolveInfo>() {
13382        public int compare(ResolveInfo r1, ResolveInfo r2) {
13383            int v1 = r1.priority;
13384            int v2 = r2.priority;
13385            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13386            if (v1 != v2) {
13387                return (v1 > v2) ? -1 : 1;
13388            }
13389            v1 = r1.preferredOrder;
13390            v2 = r2.preferredOrder;
13391            if (v1 != v2) {
13392                return (v1 > v2) ? -1 : 1;
13393            }
13394            if (r1.isDefault != r2.isDefault) {
13395                return r1.isDefault ? -1 : 1;
13396            }
13397            v1 = r1.match;
13398            v2 = r2.match;
13399            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13400            if (v1 != v2) {
13401                return (v1 > v2) ? -1 : 1;
13402            }
13403            if (r1.system != r2.system) {
13404                return r1.system ? -1 : 1;
13405            }
13406            if (r1.activityInfo != null) {
13407                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13408            }
13409            if (r1.serviceInfo != null) {
13410                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13411            }
13412            if (r1.providerInfo != null) {
13413                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13414            }
13415            return 0;
13416        }
13417    };
13418
13419    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13420            new Comparator<ProviderInfo>() {
13421        public int compare(ProviderInfo p1, ProviderInfo p2) {
13422            final int v1 = p1.initOrder;
13423            final int v2 = p2.initOrder;
13424            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13425        }
13426    };
13427
13428    @Override
13429    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13430            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13431            final int[] userIds, int[] instantUserIds) {
13432        mHandler.post(new Runnable() {
13433            @Override
13434            public void run() {
13435                try {
13436                    final IActivityManager am = ActivityManager.getService();
13437                    if (am == null) return;
13438                    final int[] resolvedUserIds;
13439                    if (userIds == null) {
13440                        resolvedUserIds = am.getRunningUserIds();
13441                    } else {
13442                        resolvedUserIds = userIds;
13443                    }
13444                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13445                            resolvedUserIds, false);
13446                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13447                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13448                                instantUserIds, true);
13449                    }
13450                } catch (RemoteException ex) {
13451                }
13452            }
13453        });
13454    }
13455
13456    @Override
13457    public void notifyPackageAdded(String packageName) {
13458        final PackageListObserver[] observers;
13459        synchronized (mPackages) {
13460            if (mPackageListObservers.size() == 0) {
13461                return;
13462            }
13463            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13464        }
13465        for (int i = observers.length - 1; i >= 0; --i) {
13466            observers[i].onPackageAdded(packageName);
13467        }
13468    }
13469
13470    @Override
13471    public void notifyPackageRemoved(String packageName) {
13472        final PackageListObserver[] observers;
13473        synchronized (mPackages) {
13474            if (mPackageListObservers.size() == 0) {
13475                return;
13476            }
13477            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13478        }
13479        for (int i = observers.length - 1; i >= 0; --i) {
13480            observers[i].onPackageRemoved(packageName);
13481        }
13482    }
13483
13484    /**
13485     * Sends a broadcast for the given action.
13486     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13487     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13488     * the system and applications allowed to see instant applications to receive package
13489     * lifecycle events for instant applications.
13490     */
13491    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13492            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13493            int[] userIds, boolean isInstantApp)
13494                    throws RemoteException {
13495        for (int id : userIds) {
13496            final Intent intent = new Intent(action,
13497                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13498            final String[] requiredPermissions =
13499                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13500            if (extras != null) {
13501                intent.putExtras(extras);
13502            }
13503            if (targetPkg != null) {
13504                intent.setPackage(targetPkg);
13505            }
13506            // Modify the UID when posting to other users
13507            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13508            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13509                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13510                intent.putExtra(Intent.EXTRA_UID, uid);
13511            }
13512            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13513            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13514            if (DEBUG_BROADCASTS) {
13515                RuntimeException here = new RuntimeException("here");
13516                here.fillInStackTrace();
13517                Slog.d(TAG, "Sending to user " + id + ": "
13518                        + intent.toShortString(false, true, false, false)
13519                        + " " + intent.getExtras(), here);
13520            }
13521            am.broadcastIntent(null, intent, null, finishedReceiver,
13522                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13523                    null, finishedReceiver != null, false, id);
13524        }
13525    }
13526
13527    /**
13528     * Check if the external storage media is available. This is true if there
13529     * is a mounted external storage medium or if the external storage is
13530     * emulated.
13531     */
13532    private boolean isExternalMediaAvailable() {
13533        return mMediaMounted || Environment.isExternalStorageEmulated();
13534    }
13535
13536    @Override
13537    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13538        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13539            return null;
13540        }
13541        if (!isExternalMediaAvailable()) {
13542                // If the external storage is no longer mounted at this point,
13543                // the caller may not have been able to delete all of this
13544                // packages files and can not delete any more.  Bail.
13545            return null;
13546        }
13547        synchronized (mPackages) {
13548            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13549            if (lastPackage != null) {
13550                pkgs.remove(lastPackage);
13551            }
13552            if (pkgs.size() > 0) {
13553                return pkgs.get(0);
13554            }
13555        }
13556        return null;
13557    }
13558
13559    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13560        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13561                userId, andCode ? 1 : 0, packageName);
13562        if (mSystemReady) {
13563            msg.sendToTarget();
13564        } else {
13565            if (mPostSystemReadyMessages == null) {
13566                mPostSystemReadyMessages = new ArrayList<>();
13567            }
13568            mPostSystemReadyMessages.add(msg);
13569        }
13570    }
13571
13572    void startCleaningPackages() {
13573        // reader
13574        if (!isExternalMediaAvailable()) {
13575            return;
13576        }
13577        synchronized (mPackages) {
13578            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13579                return;
13580            }
13581        }
13582        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13583        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13584        IActivityManager am = ActivityManager.getService();
13585        if (am != null) {
13586            int dcsUid = -1;
13587            synchronized (mPackages) {
13588                if (!mDefaultContainerWhitelisted) {
13589                    mDefaultContainerWhitelisted = true;
13590                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13591                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13592                }
13593            }
13594            try {
13595                if (dcsUid > 0) {
13596                    am.backgroundWhitelistUid(dcsUid);
13597                }
13598                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13599                        UserHandle.USER_SYSTEM);
13600            } catch (RemoteException e) {
13601            }
13602        }
13603    }
13604
13605    /**
13606     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13607     * it is acting on behalf on an enterprise or the user).
13608     *
13609     * Note that the ordering of the conditionals in this method is important. The checks we perform
13610     * are as follows, in this order:
13611     *
13612     * 1) If the install is being performed by a system app, we can trust the app to have set the
13613     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13614     *    what it is.
13615     * 2) If the install is being performed by a device or profile owner app, the install reason
13616     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13617     *    set the install reason correctly. If the app targets an older SDK version where install
13618     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13619     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13620     * 3) In all other cases, the install is being performed by a regular app that is neither part
13621     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13622     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13623     *    set to enterprise policy and if so, change it to unknown instead.
13624     */
13625    private int fixUpInstallReason(String installerPackageName, int installerUid,
13626            int installReason) {
13627        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13628                == PERMISSION_GRANTED) {
13629            // If the install is being performed by a system app, we trust that app to have set the
13630            // install reason correctly.
13631            return installReason;
13632        }
13633
13634        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13635            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13636        if (dpm != null) {
13637            ComponentName owner = null;
13638            try {
13639                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13640                if (owner == null) {
13641                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13642                }
13643            } catch (RemoteException e) {
13644            }
13645            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13646                // If the install is being performed by a device or profile owner, the install
13647                // reason should be enterprise policy.
13648                return PackageManager.INSTALL_REASON_POLICY;
13649            }
13650        }
13651
13652        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13653            // If the install is being performed by a regular app (i.e. neither system app nor
13654            // device or profile owner), we have no reason to believe that the app is acting on
13655            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13656            // change it to unknown instead.
13657            return PackageManager.INSTALL_REASON_UNKNOWN;
13658        }
13659
13660        // If the install is being performed by a regular app and the install reason was set to any
13661        // value but enterprise policy, leave the install reason unchanged.
13662        return installReason;
13663    }
13664
13665    /**
13666     * Attempts to bind to the default container service explicitly instead of doing so lazily on
13667     * install commit.
13668     */
13669    void earlyBindToDefContainer() {
13670        mHandler.sendMessage(mHandler.obtainMessage(DEF_CONTAINER_BIND));
13671    }
13672
13673    void installStage(String packageName, File stagedDir,
13674            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13675            String installerPackageName, int installerUid, UserHandle user,
13676            PackageParser.SigningDetails signingDetails) {
13677        if (DEBUG_INSTANT) {
13678            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13679                Slog.d(TAG, "Ephemeral install of " + packageName);
13680            }
13681        }
13682        final VerificationInfo verificationInfo = new VerificationInfo(
13683                sessionParams.originatingUri, sessionParams.referrerUri,
13684                sessionParams.originatingUid, installerUid);
13685
13686        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13687
13688        final Message msg = mHandler.obtainMessage(INIT_COPY);
13689        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13690                sessionParams.installReason);
13691        final InstallParams params = new InstallParams(origin, null, observer,
13692                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13693                verificationInfo, user, sessionParams.abiOverride,
13694                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13695        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13696        msg.obj = params;
13697
13698        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13699                System.identityHashCode(msg.obj));
13700        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13701                System.identityHashCode(msg.obj));
13702
13703        mHandler.sendMessage(msg);
13704    }
13705
13706    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13707            int userId) {
13708        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13709        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13710        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13711        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13712        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13713                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13714
13715        // Send a session commit broadcast
13716        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13717        info.installReason = pkgSetting.getInstallReason(userId);
13718        info.appPackageName = packageName;
13719        sendSessionCommitBroadcast(info, userId);
13720    }
13721
13722    @Override
13723    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13724            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13725        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13726            return;
13727        }
13728        Bundle extras = new Bundle(1);
13729        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13730        final int uid = UserHandle.getUid(
13731                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13732        extras.putInt(Intent.EXTRA_UID, uid);
13733
13734        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13735                packageName, extras, 0, null, null, userIds, instantUserIds);
13736        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13737            mHandler.post(() -> {
13738                        for (int userId : userIds) {
13739                            sendBootCompletedBroadcastToSystemApp(
13740                                    packageName, includeStopped, userId);
13741                        }
13742                    }
13743            );
13744        }
13745    }
13746
13747    /**
13748     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13749     * automatically without needing an explicit launch.
13750     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13751     */
13752    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13753            int userId) {
13754        // If user is not running, the app didn't miss any broadcast
13755        if (!mUserManagerInternal.isUserRunning(userId)) {
13756            return;
13757        }
13758        final IActivityManager am = ActivityManager.getService();
13759        try {
13760            // Deliver LOCKED_BOOT_COMPLETED first
13761            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13762                    .setPackage(packageName);
13763            if (includeStopped) {
13764                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13765            }
13766            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13767            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13768                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13769
13770            // Deliver BOOT_COMPLETED only if user is unlocked
13771            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13772                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13773                if (includeStopped) {
13774                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13775                }
13776                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13777                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13778            }
13779        } catch (RemoteException e) {
13780            throw e.rethrowFromSystemServer();
13781        }
13782    }
13783
13784    @Override
13785    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13786            int userId) {
13787        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13788        PackageSetting pkgSetting;
13789        final int callingUid = Binder.getCallingUid();
13790        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13791                true /* requireFullPermission */, true /* checkShell */,
13792                "setApplicationHiddenSetting for user " + userId);
13793
13794        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13795            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13796            return false;
13797        }
13798
13799        long callingId = Binder.clearCallingIdentity();
13800        try {
13801            boolean sendAdded = false;
13802            boolean sendRemoved = false;
13803            // writer
13804            synchronized (mPackages) {
13805                pkgSetting = mSettings.mPackages.get(packageName);
13806                if (pkgSetting == null) {
13807                    return false;
13808                }
13809                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13810                    return false;
13811                }
13812                // Do not allow "android" is being disabled
13813                if ("android".equals(packageName)) {
13814                    Slog.w(TAG, "Cannot hide package: android");
13815                    return false;
13816                }
13817                // Cannot hide static shared libs as they are considered
13818                // a part of the using app (emulating static linking). Also
13819                // static libs are installed always on internal storage.
13820                PackageParser.Package pkg = mPackages.get(packageName);
13821                if (pkg != null && pkg.staticSharedLibName != null) {
13822                    Slog.w(TAG, "Cannot hide package: " + packageName
13823                            + " providing static shared library: "
13824                            + pkg.staticSharedLibName);
13825                    return false;
13826                }
13827                // Only allow protected packages to hide themselves.
13828                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13829                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13830                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13831                    return false;
13832                }
13833
13834                if (pkgSetting.getHidden(userId) != hidden) {
13835                    pkgSetting.setHidden(hidden, userId);
13836                    mSettings.writePackageRestrictionsLPr(userId);
13837                    if (hidden) {
13838                        sendRemoved = true;
13839                    } else {
13840                        sendAdded = true;
13841                    }
13842                }
13843            }
13844            if (sendAdded) {
13845                sendPackageAddedForUser(packageName, pkgSetting, userId);
13846                return true;
13847            }
13848            if (sendRemoved) {
13849                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13850                        "hiding pkg");
13851                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13852                return true;
13853            }
13854        } finally {
13855            Binder.restoreCallingIdentity(callingId);
13856        }
13857        return false;
13858    }
13859
13860    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13861            int userId) {
13862        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13863        info.removedPackage = packageName;
13864        info.installerPackageName = pkgSetting.installerPackageName;
13865        info.removedUsers = new int[] {userId};
13866        info.broadcastUsers = new int[] {userId};
13867        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13868        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13869    }
13870
13871    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended,
13872            PersistableBundle launcherExtras) {
13873        if (pkgList.length > 0) {
13874            Bundle extras = new Bundle(1);
13875            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13876            if (launcherExtras != null) {
13877                extras.putBundle(Intent.EXTRA_LAUNCHER_EXTRAS,
13878                        new Bundle(launcherExtras.deepCopy()));
13879            }
13880            sendPackageBroadcast(
13881                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13882                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13883                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13884                    new int[] {userId}, null);
13885        }
13886    }
13887
13888    /**
13889     * Returns true if application is not found or there was an error. Otherwise it returns
13890     * the hidden state of the package for the given user.
13891     */
13892    @Override
13893    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13894        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13895        final int callingUid = Binder.getCallingUid();
13896        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13897                true /* requireFullPermission */, false /* checkShell */,
13898                "getApplicationHidden for user " + userId);
13899        PackageSetting ps;
13900        long callingId = Binder.clearCallingIdentity();
13901        try {
13902            // writer
13903            synchronized (mPackages) {
13904                ps = mSettings.mPackages.get(packageName);
13905                if (ps == null) {
13906                    return true;
13907                }
13908                if (filterAppAccessLPr(ps, callingUid, userId)) {
13909                    return true;
13910                }
13911                return ps.getHidden(userId);
13912            }
13913        } finally {
13914            Binder.restoreCallingIdentity(callingId);
13915        }
13916    }
13917
13918    /**
13919     * @hide
13920     */
13921    @Override
13922    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13923            int installReason) {
13924        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13925                null);
13926        PackageSetting pkgSetting;
13927        final int callingUid = Binder.getCallingUid();
13928        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13929                true /* requireFullPermission */, true /* checkShell */,
13930                "installExistingPackage for user " + userId);
13931        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13932            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13933        }
13934
13935        long callingId = Binder.clearCallingIdentity();
13936        try {
13937            boolean installed = false;
13938            final boolean instantApp =
13939                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13940            final boolean fullApp =
13941                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13942
13943            // writer
13944            synchronized (mPackages) {
13945                pkgSetting = mSettings.mPackages.get(packageName);
13946                if (pkgSetting == null) {
13947                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13948                }
13949                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13950                    // only allow the existing package to be used if it's installed as a full
13951                    // application for at least one user
13952                    boolean installAllowed = false;
13953                    for (int checkUserId : sUserManager.getUserIds()) {
13954                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13955                        if (installAllowed) {
13956                            break;
13957                        }
13958                    }
13959                    if (!installAllowed) {
13960                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13961                    }
13962                }
13963                if (!pkgSetting.getInstalled(userId)) {
13964                    pkgSetting.setInstalled(true, userId);
13965                    pkgSetting.setHidden(false, userId);
13966                    pkgSetting.setInstallReason(installReason, userId);
13967                    mSettings.writePackageRestrictionsLPr(userId);
13968                    mSettings.writeKernelMappingLPr(pkgSetting);
13969                    installed = true;
13970                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13971                    // upgrade app from instant to full; we don't allow app downgrade
13972                    installed = true;
13973                }
13974                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13975            }
13976
13977            if (installed) {
13978                if (pkgSetting.pkg != null) {
13979                    synchronized (mInstallLock) {
13980                        // We don't need to freeze for a brand new install
13981                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13982                    }
13983                }
13984                sendPackageAddedForUser(packageName, pkgSetting, userId);
13985                synchronized (mPackages) {
13986                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13987                }
13988            }
13989        } finally {
13990            Binder.restoreCallingIdentity(callingId);
13991        }
13992
13993        return PackageManager.INSTALL_SUCCEEDED;
13994    }
13995
13996    static void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13997            boolean instantApp, boolean fullApp) {
13998        // no state specified; do nothing
13999        if (!instantApp && !fullApp) {
14000            return;
14001        }
14002        if (userId != UserHandle.USER_ALL) {
14003            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14004                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14005            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14006                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14007            }
14008        } else {
14009            for (int currentUserId : sUserManager.getUserIds()) {
14010                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14011                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14012                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14013                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14014                }
14015            }
14016        }
14017    }
14018
14019    boolean isUserRestricted(int userId, String restrictionKey) {
14020        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14021        if (restrictions.getBoolean(restrictionKey, false)) {
14022            Log.w(TAG, "User is restricted: " + restrictionKey);
14023            return true;
14024        }
14025        return false;
14026    }
14027
14028    @Override
14029    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14030            PersistableBundle appExtras, PersistableBundle launcherExtras, String dialogMessage,
14031            String callingPackage, int userId) {
14032        try {
14033            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS, null);
14034        } catch (SecurityException e) {
14035            mContext.enforceCallingOrSelfPermission(Manifest.permission.MANAGE_USERS,
14036                    "Callers need to have either " + Manifest.permission.SUSPEND_APPS + " or "
14037                            + Manifest.permission.MANAGE_USERS);
14038        }
14039        final int callingUid = Binder.getCallingUid();
14040        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14041                true /* requireFullPermission */, true /* checkShell */,
14042                "setPackagesSuspended for user " + userId);
14043        if (callingUid != Process.ROOT_UID &&
14044                !UserHandle.isSameApp(getPackageUid(callingPackage, 0, userId), callingUid)) {
14045            throw new IllegalArgumentException("CallingPackage " + callingPackage + " does not"
14046                    + " belong to calling app id " + UserHandle.getAppId(callingUid));
14047        }
14048
14049        if (ArrayUtils.isEmpty(packageNames)) {
14050            return packageNames;
14051        }
14052
14053        final List<String> changedPackagesList = new ArrayList<>(packageNames.length);
14054        final List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14055        final long callingId = Binder.clearCallingIdentity();
14056        try {
14057            synchronized (mPackages) {
14058                for (int i = 0; i < packageNames.length; i++) {
14059                    final String packageName = packageNames[i];
14060                    if (callingPackage.equals(packageName)) {
14061                        Slog.w(TAG, "Calling package: " + callingPackage + " trying to "
14062                                + (suspended ? "" : "un") + "suspend itself. Ignoring");
14063                        unactionedPackages.add(packageName);
14064                        continue;
14065                    }
14066                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14067                    if (pkgSetting == null
14068                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14069                        Slog.w(TAG, "Could not find package setting for package: " + packageName
14070                                + ". Skipping suspending/un-suspending.");
14071                        unactionedPackages.add(packageName);
14072                        continue;
14073                    }
14074                    if (!canSuspendPackageForUserLocked(packageName, userId)) {
14075                        unactionedPackages.add(packageName);
14076                        continue;
14077                    }
14078                    pkgSetting.setSuspended(suspended, callingPackage, dialogMessage, appExtras,
14079                            launcherExtras, userId);
14080                    changedPackagesList.add(packageName);
14081                }
14082            }
14083        } finally {
14084            Binder.restoreCallingIdentity(callingId);
14085        }
14086        if (!changedPackagesList.isEmpty()) {
14087            final String[] changedPackages = changedPackagesList.toArray(
14088                    new String[changedPackagesList.size()]);
14089            sendPackagesSuspendedForUser(changedPackages, userId, suspended, launcherExtras);
14090            sendMyPackageSuspendedOrUnsuspended(changedPackages, suspended, appExtras, userId);
14091            synchronized (mPackages) {
14092                scheduleWritePackageRestrictionsLocked(userId);
14093            }
14094        }
14095        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14096    }
14097
14098    @Override
14099    public PersistableBundle getSuspendedPackageAppExtras(String packageName, int userId) {
14100        final int callingUid = Binder.getCallingUid();
14101        if (getPackageUid(packageName, 0, userId) != callingUid) {
14102            throw new SecurityException("Calling package " + packageName
14103                    + " does not belong to calling uid " + callingUid);
14104        }
14105        synchronized (mPackages) {
14106            final PackageSetting ps = mSettings.mPackages.get(packageName);
14107            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14108                throw new IllegalArgumentException("Unknown target package: " + packageName);
14109            }
14110            final PackageUserState packageUserState = ps.readUserState(userId);
14111            if (packageUserState.suspended) {
14112                return packageUserState.suspendedAppExtras;
14113            }
14114            return null;
14115        }
14116    }
14117
14118    private void sendMyPackageSuspendedOrUnsuspended(String[] affectedPackages, boolean suspended,
14119            PersistableBundle appExtras, int userId) {
14120        final String action;
14121        final Bundle intentExtras = new Bundle();
14122        if (suspended) {
14123            action = Intent.ACTION_MY_PACKAGE_SUSPENDED;
14124            if (appExtras != null) {
14125                final Bundle bundledAppExtras = new Bundle(appExtras.deepCopy());
14126                intentExtras.putBundle(Intent.EXTRA_SUSPENDED_PACKAGE_EXTRAS, bundledAppExtras);
14127            }
14128        } else {
14129            action = Intent.ACTION_MY_PACKAGE_UNSUSPENDED;
14130        }
14131        mHandler.post(new Runnable() {
14132            @Override
14133            public void run() {
14134                try {
14135                    final IActivityManager am = ActivityManager.getService();
14136                    if (am == null) {
14137                        Slog.wtf(TAG, "IActivityManager null. Cannot send MY_PACKAGE_ "
14138                                + (suspended ? "" : "UN") + "SUSPENDED broadcasts");
14139                        return;
14140                    }
14141                    final int[] targetUserIds = new int[] {userId};
14142                    for (String packageName : affectedPackages) {
14143                        doSendBroadcast(am, action, null, intentExtras,
14144                                Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, packageName, null,
14145                                targetUserIds, false);
14146                    }
14147                } catch (RemoteException ex) {
14148                    // Shouldn't happen as AMS is in the same process.
14149                }
14150            }
14151        });
14152    }
14153
14154    @Override
14155    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14156        final int callingUid = Binder.getCallingUid();
14157        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14158                true /* requireFullPermission */, false /* checkShell */,
14159                "isPackageSuspendedForUser for user " + userId);
14160        synchronized (mPackages) {
14161            final PackageSetting ps = mSettings.mPackages.get(packageName);
14162            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14163                throw new IllegalArgumentException("Unknown target package: " + packageName);
14164            }
14165            return ps.getSuspended(userId);
14166        }
14167    }
14168
14169    void onSuspendingPackageRemoved(String packageName, int removedForUser) {
14170        final int[] userIds = (removedForUser == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14171                : new int[] {removedForUser};
14172        for (int userId : userIds) {
14173            List<String> affectedPackages = new ArrayList<>();
14174            synchronized (mPackages) {
14175                for (PackageSetting ps : mSettings.mPackages.values()) {
14176                    final PackageUserState pus = ps.readUserState(userId);
14177                    if (pus.suspended && packageName.equals(pus.suspendingPackage)) {
14178                        ps.setSuspended(false, null, null, null, null, userId);
14179                        affectedPackages.add(ps.name);
14180                    }
14181                }
14182            }
14183            if (!affectedPackages.isEmpty()) {
14184                final String[] packageArray = affectedPackages.toArray(
14185                        new String[affectedPackages.size()]);
14186                sendMyPackageSuspendedOrUnsuspended(packageArray, false, null, userId);
14187                sendPackagesSuspendedForUser(packageArray, userId, false, null);
14188            }
14189        }
14190    }
14191
14192    @GuardedBy("mPackages")
14193    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14194        if (isPackageDeviceAdmin(packageName, userId)) {
14195            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14196                    + "\": has an active device admin");
14197            return false;
14198        }
14199
14200        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14201        if (packageName.equals(activeLauncherPackageName)) {
14202            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14203                    + "\": contains the active launcher");
14204            return false;
14205        }
14206
14207        if (packageName.equals(mRequiredInstallerPackage)) {
14208            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14209                    + "\": required for package installation");
14210            return false;
14211        }
14212
14213        if (packageName.equals(mRequiredUninstallerPackage)) {
14214            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14215                    + "\": required for package uninstallation");
14216            return false;
14217        }
14218
14219        if (packageName.equals(mRequiredVerifierPackage)) {
14220            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14221                    + "\": required for package verification");
14222            return false;
14223        }
14224
14225        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14226            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14227                    + "\": is the default dialer");
14228            return false;
14229        }
14230
14231        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14232            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14233                    + "\": protected package");
14234            return false;
14235        }
14236
14237        // Cannot suspend static shared libs as they are considered
14238        // a part of the using app (emulating static linking). Also
14239        // static libs are installed always on internal storage.
14240        PackageParser.Package pkg = mPackages.get(packageName);
14241        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14242            Slog.w(TAG, "Cannot suspend package: " + packageName
14243                    + " providing static shared library: "
14244                    + pkg.staticSharedLibName);
14245            return false;
14246        }
14247
14248        if (PLATFORM_PACKAGE_NAME.equals(packageName)) {
14249            Slog.w(TAG, "Cannot suspend package: " + packageName);
14250            return false;
14251        }
14252
14253        return true;
14254    }
14255
14256    private String getActiveLauncherPackageName(int userId) {
14257        Intent intent = new Intent(Intent.ACTION_MAIN);
14258        intent.addCategory(Intent.CATEGORY_HOME);
14259        ResolveInfo resolveInfo = resolveIntent(
14260                intent,
14261                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14262                PackageManager.MATCH_DEFAULT_ONLY,
14263                userId);
14264
14265        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14266    }
14267
14268    private String getDefaultDialerPackageName(int userId) {
14269        synchronized (mPackages) {
14270            return mSettings.getDefaultDialerPackageNameLPw(userId);
14271        }
14272    }
14273
14274    @Override
14275    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14276        mContext.enforceCallingOrSelfPermission(
14277                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14278                "Only package verification agents can verify applications");
14279
14280        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14281        final PackageVerificationResponse response = new PackageVerificationResponse(
14282                verificationCode, Binder.getCallingUid());
14283        msg.arg1 = id;
14284        msg.obj = response;
14285        mHandler.sendMessage(msg);
14286    }
14287
14288    @Override
14289    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14290            long millisecondsToDelay) {
14291        mContext.enforceCallingOrSelfPermission(
14292                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14293                "Only package verification agents can extend verification timeouts");
14294
14295        final PackageVerificationState state = mPendingVerification.get(id);
14296        final PackageVerificationResponse response = new PackageVerificationResponse(
14297                verificationCodeAtTimeout, Binder.getCallingUid());
14298
14299        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14300            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14301        }
14302        if (millisecondsToDelay < 0) {
14303            millisecondsToDelay = 0;
14304        }
14305        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14306                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14307            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14308        }
14309
14310        if ((state != null) && !state.timeoutExtended()) {
14311            state.extendTimeout();
14312
14313            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14314            msg.arg1 = id;
14315            msg.obj = response;
14316            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14317        }
14318    }
14319
14320    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14321            int verificationCode, UserHandle user) {
14322        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14323        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14324        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14325        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14326        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14327
14328        mContext.sendBroadcastAsUser(intent, user,
14329                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14330    }
14331
14332    private ComponentName matchComponentForVerifier(String packageName,
14333            List<ResolveInfo> receivers) {
14334        ActivityInfo targetReceiver = null;
14335
14336        final int NR = receivers.size();
14337        for (int i = 0; i < NR; i++) {
14338            final ResolveInfo info = receivers.get(i);
14339            if (info.activityInfo == null) {
14340                continue;
14341            }
14342
14343            if (packageName.equals(info.activityInfo.packageName)) {
14344                targetReceiver = info.activityInfo;
14345                break;
14346            }
14347        }
14348
14349        if (targetReceiver == null) {
14350            return null;
14351        }
14352
14353        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14354    }
14355
14356    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14357            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14358        if (pkgInfo.verifiers.length == 0) {
14359            return null;
14360        }
14361
14362        final int N = pkgInfo.verifiers.length;
14363        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14364        for (int i = 0; i < N; i++) {
14365            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14366
14367            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14368                    receivers);
14369            if (comp == null) {
14370                continue;
14371            }
14372
14373            final int verifierUid = getUidForVerifier(verifierInfo);
14374            if (verifierUid == -1) {
14375                continue;
14376            }
14377
14378            if (DEBUG_VERIFY) {
14379                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14380                        + " with the correct signature");
14381            }
14382            sufficientVerifiers.add(comp);
14383            verificationState.addSufficientVerifier(verifierUid);
14384        }
14385
14386        return sufficientVerifiers;
14387    }
14388
14389    private int getUidForVerifier(VerifierInfo verifierInfo) {
14390        synchronized (mPackages) {
14391            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14392            if (pkg == null) {
14393                return -1;
14394            } else if (pkg.mSigningDetails.signatures.length != 1) {
14395                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14396                        + " has more than one signature; ignoring");
14397                return -1;
14398            }
14399
14400            /*
14401             * If the public key of the package's signature does not match
14402             * our expected public key, then this is a different package and
14403             * we should skip.
14404             */
14405
14406            final byte[] expectedPublicKey;
14407            try {
14408                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14409                final PublicKey publicKey = verifierSig.getPublicKey();
14410                expectedPublicKey = publicKey.getEncoded();
14411            } catch (CertificateException e) {
14412                return -1;
14413            }
14414
14415            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14416
14417            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14418                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14419                        + " does not have the expected public key; ignoring");
14420                return -1;
14421            }
14422
14423            return pkg.applicationInfo.uid;
14424        }
14425    }
14426
14427    @Override
14428    public void finishPackageInstall(int token, boolean didLaunch) {
14429        enforceSystemOrRoot("Only the system is allowed to finish installs");
14430
14431        if (DEBUG_INSTALL) {
14432            Slog.v(TAG, "BM finishing package install for " + token);
14433        }
14434        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14435
14436        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14437        mHandler.sendMessage(msg);
14438    }
14439
14440    /**
14441     * Get the verification agent timeout.  Used for both the APK verifier and the
14442     * intent filter verifier.
14443     *
14444     * @return verification timeout in milliseconds
14445     */
14446    private long getVerificationTimeout() {
14447        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14448                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14449                DEFAULT_VERIFICATION_TIMEOUT);
14450    }
14451
14452    /**
14453     * Get the default verification agent response code.
14454     *
14455     * @return default verification response code
14456     */
14457    private int getDefaultVerificationResponse(UserHandle user) {
14458        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14459            return PackageManager.VERIFICATION_REJECT;
14460        }
14461        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14462                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14463                DEFAULT_VERIFICATION_RESPONSE);
14464    }
14465
14466    /**
14467     * Check whether or not package verification has been enabled.
14468     *
14469     * @return true if verification should be performed
14470     */
14471    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14472        if (!DEFAULT_VERIFY_ENABLE) {
14473            return false;
14474        }
14475
14476        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14477
14478        // Check if installing from ADB
14479        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14480            // Do not run verification in a test harness environment
14481            if (ActivityManager.isRunningInTestHarness()) {
14482                return false;
14483            }
14484            if (ensureVerifyAppsEnabled) {
14485                return true;
14486            }
14487            // Check if the developer does not want package verification for ADB installs
14488            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14489                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14490                return false;
14491            }
14492        } else {
14493            // only when not installed from ADB, skip verification for instant apps when
14494            // the installer and verifier are the same.
14495            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14496                if (mInstantAppInstallerActivity != null
14497                        && mInstantAppInstallerActivity.packageName.equals(
14498                                mRequiredVerifierPackage)) {
14499                    try {
14500                        mContext.getSystemService(AppOpsManager.class)
14501                                .checkPackage(installerUid, mRequiredVerifierPackage);
14502                        if (DEBUG_VERIFY) {
14503                            Slog.i(TAG, "disable verification for instant app");
14504                        }
14505                        return false;
14506                    } catch (SecurityException ignore) { }
14507                }
14508            }
14509        }
14510
14511        if (ensureVerifyAppsEnabled) {
14512            return true;
14513        }
14514
14515        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14516                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14517    }
14518
14519    @Override
14520    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14521            throws RemoteException {
14522        mContext.enforceCallingOrSelfPermission(
14523                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14524                "Only intentfilter verification agents can verify applications");
14525
14526        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14527        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14528                Binder.getCallingUid(), verificationCode, failedDomains);
14529        msg.arg1 = id;
14530        msg.obj = response;
14531        mHandler.sendMessage(msg);
14532    }
14533
14534    @Override
14535    public int getIntentVerificationStatus(String packageName, int userId) {
14536        final int callingUid = Binder.getCallingUid();
14537        if (UserHandle.getUserId(callingUid) != userId) {
14538            mContext.enforceCallingOrSelfPermission(
14539                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14540                    "getIntentVerificationStatus" + userId);
14541        }
14542        if (getInstantAppPackageName(callingUid) != null) {
14543            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14544        }
14545        synchronized (mPackages) {
14546            final PackageSetting ps = mSettings.mPackages.get(packageName);
14547            if (ps == null
14548                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14549                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14550            }
14551            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14552        }
14553    }
14554
14555    @Override
14556    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14557        mContext.enforceCallingOrSelfPermission(
14558                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14559
14560        boolean result = false;
14561        synchronized (mPackages) {
14562            final PackageSetting ps = mSettings.mPackages.get(packageName);
14563            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14564                return false;
14565            }
14566            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14567        }
14568        if (result) {
14569            scheduleWritePackageRestrictionsLocked(userId);
14570        }
14571        return result;
14572    }
14573
14574    @Override
14575    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14576            String packageName) {
14577        final int callingUid = Binder.getCallingUid();
14578        if (getInstantAppPackageName(callingUid) != null) {
14579            return ParceledListSlice.emptyList();
14580        }
14581        synchronized (mPackages) {
14582            final PackageSetting ps = mSettings.mPackages.get(packageName);
14583            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14584                return ParceledListSlice.emptyList();
14585            }
14586            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14587        }
14588    }
14589
14590    @Override
14591    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14592        if (TextUtils.isEmpty(packageName)) {
14593            return ParceledListSlice.emptyList();
14594        }
14595        final int callingUid = Binder.getCallingUid();
14596        final int callingUserId = UserHandle.getUserId(callingUid);
14597        synchronized (mPackages) {
14598            PackageParser.Package pkg = mPackages.get(packageName);
14599            if (pkg == null || pkg.activities == null) {
14600                return ParceledListSlice.emptyList();
14601            }
14602            if (pkg.mExtras == null) {
14603                return ParceledListSlice.emptyList();
14604            }
14605            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14606            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14607                return ParceledListSlice.emptyList();
14608            }
14609            final int count = pkg.activities.size();
14610            ArrayList<IntentFilter> result = new ArrayList<>();
14611            for (int n=0; n<count; n++) {
14612                PackageParser.Activity activity = pkg.activities.get(n);
14613                if (activity.intents != null && activity.intents.size() > 0) {
14614                    result.addAll(activity.intents);
14615                }
14616            }
14617            return new ParceledListSlice<>(result);
14618        }
14619    }
14620
14621    @Override
14622    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14623        mContext.enforceCallingOrSelfPermission(
14624                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14625        if (UserHandle.getCallingUserId() != userId) {
14626            mContext.enforceCallingOrSelfPermission(
14627                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14628        }
14629
14630        synchronized (mPackages) {
14631            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14632            if (packageName != null) {
14633                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14634                        packageName, userId);
14635            }
14636            return result;
14637        }
14638    }
14639
14640    @Override
14641    public String getDefaultBrowserPackageName(int userId) {
14642        if (UserHandle.getCallingUserId() != userId) {
14643            mContext.enforceCallingOrSelfPermission(
14644                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14645        }
14646        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14647            return null;
14648        }
14649        synchronized (mPackages) {
14650            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14651        }
14652    }
14653
14654    /**
14655     * Get the "allow unknown sources" setting.
14656     *
14657     * @return the current "allow unknown sources" setting
14658     */
14659    private int getUnknownSourcesSettings() {
14660        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14661                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14662                -1);
14663    }
14664
14665    @Override
14666    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14667        final int callingUid = Binder.getCallingUid();
14668        if (getInstantAppPackageName(callingUid) != null) {
14669            return;
14670        }
14671        // writer
14672        synchronized (mPackages) {
14673            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14674            if (targetPackageSetting == null
14675                    || filterAppAccessLPr(
14676                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14677                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14678            }
14679
14680            PackageSetting installerPackageSetting;
14681            if (installerPackageName != null) {
14682                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14683                if (installerPackageSetting == null) {
14684                    throw new IllegalArgumentException("Unknown installer package: "
14685                            + installerPackageName);
14686                }
14687            } else {
14688                installerPackageSetting = null;
14689            }
14690
14691            Signature[] callerSignature;
14692            Object obj = mSettings.getUserIdLPr(callingUid);
14693            if (obj != null) {
14694                if (obj instanceof SharedUserSetting) {
14695                    callerSignature =
14696                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14697                } else if (obj instanceof PackageSetting) {
14698                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14699                } else {
14700                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14701                }
14702            } else {
14703                throw new SecurityException("Unknown calling UID: " + callingUid);
14704            }
14705
14706            // Verify: can't set installerPackageName to a package that is
14707            // not signed with the same cert as the caller.
14708            if (installerPackageSetting != null) {
14709                if (compareSignatures(callerSignature,
14710                        installerPackageSetting.signatures.mSigningDetails.signatures)
14711                        != PackageManager.SIGNATURE_MATCH) {
14712                    throw new SecurityException(
14713                            "Caller does not have same cert as new installer package "
14714                            + installerPackageName);
14715                }
14716            }
14717
14718            // Verify: if target already has an installer package, it must
14719            // be signed with the same cert as the caller.
14720            if (targetPackageSetting.installerPackageName != null) {
14721                PackageSetting setting = mSettings.mPackages.get(
14722                        targetPackageSetting.installerPackageName);
14723                // If the currently set package isn't valid, then it's always
14724                // okay to change it.
14725                if (setting != null) {
14726                    if (compareSignatures(callerSignature,
14727                            setting.signatures.mSigningDetails.signatures)
14728                            != PackageManager.SIGNATURE_MATCH) {
14729                        throw new SecurityException(
14730                                "Caller does not have same cert as old installer package "
14731                                + targetPackageSetting.installerPackageName);
14732                    }
14733                }
14734            }
14735
14736            // Okay!
14737            targetPackageSetting.installerPackageName = installerPackageName;
14738            if (installerPackageName != null) {
14739                mSettings.mInstallerPackages.add(installerPackageName);
14740            }
14741            scheduleWriteSettingsLocked();
14742        }
14743    }
14744
14745    @Override
14746    public void setApplicationCategoryHint(String packageName, int categoryHint,
14747            String callerPackageName) {
14748        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14749            throw new SecurityException("Instant applications don't have access to this method");
14750        }
14751        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14752                callerPackageName);
14753        synchronized (mPackages) {
14754            PackageSetting ps = mSettings.mPackages.get(packageName);
14755            if (ps == null) {
14756                throw new IllegalArgumentException("Unknown target package " + packageName);
14757            }
14758            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14759                throw new IllegalArgumentException("Unknown target package " + packageName);
14760            }
14761            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14762                throw new IllegalArgumentException("Calling package " + callerPackageName
14763                        + " is not installer for " + packageName);
14764            }
14765
14766            if (ps.categoryHint != categoryHint) {
14767                ps.categoryHint = categoryHint;
14768                scheduleWriteSettingsLocked();
14769            }
14770        }
14771    }
14772
14773    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14774        // Queue up an async operation since the package installation may take a little while.
14775        mHandler.post(new Runnable() {
14776            public void run() {
14777                mHandler.removeCallbacks(this);
14778                 // Result object to be returned
14779                PackageInstalledInfo res = new PackageInstalledInfo();
14780                res.setReturnCode(currentStatus);
14781                res.uid = -1;
14782                res.pkg = null;
14783                res.removedInfo = null;
14784                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14785                    args.doPreInstall(res.returnCode);
14786                    synchronized (mInstallLock) {
14787                        installPackageTracedLI(args, res);
14788                    }
14789                    args.doPostInstall(res.returnCode, res.uid);
14790                }
14791
14792                // A restore should be performed at this point if (a) the install
14793                // succeeded, (b) the operation is not an update, and (c) the new
14794                // package has not opted out of backup participation.
14795                final boolean update = res.removedInfo != null
14796                        && res.removedInfo.removedPackage != null;
14797                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14798                boolean doRestore = !update
14799                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14800
14801                // Set up the post-install work request bookkeeping.  This will be used
14802                // and cleaned up by the post-install event handling regardless of whether
14803                // there's a restore pass performed.  Token values are >= 1.
14804                int token;
14805                if (mNextInstallToken < 0) mNextInstallToken = 1;
14806                token = mNextInstallToken++;
14807
14808                PostInstallData data = new PostInstallData(args, res);
14809                mRunningInstalls.put(token, data);
14810                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14811
14812                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14813                    // Pass responsibility to the Backup Manager.  It will perform a
14814                    // restore if appropriate, then pass responsibility back to the
14815                    // Package Manager to run the post-install observer callbacks
14816                    // and broadcasts.
14817                    IBackupManager bm = IBackupManager.Stub.asInterface(
14818                            ServiceManager.getService(Context.BACKUP_SERVICE));
14819                    if (bm != null) {
14820                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14821                                + " to BM for possible restore");
14822                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14823                        try {
14824                            // TODO: http://b/22388012
14825                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14826                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14827                            } else {
14828                                doRestore = false;
14829                            }
14830                        } catch (RemoteException e) {
14831                            // can't happen; the backup manager is local
14832                        } catch (Exception e) {
14833                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14834                            doRestore = false;
14835                        }
14836                    } else {
14837                        Slog.e(TAG, "Backup Manager not found!");
14838                        doRestore = false;
14839                    }
14840                }
14841
14842                if (!doRestore) {
14843                    // No restore possible, or the Backup Manager was mysteriously not
14844                    // available -- just fire the post-install work request directly.
14845                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14846
14847                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14848
14849                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14850                    mHandler.sendMessage(msg);
14851                }
14852            }
14853        });
14854    }
14855
14856    /**
14857     * Callback from PackageSettings whenever an app is first transitioned out of the
14858     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14859     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14860     * here whether the app is the target of an ongoing install, and only send the
14861     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14862     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14863     * handling.
14864     */
14865    void notifyFirstLaunch(final String packageName, final String installerPackage,
14866            final int userId) {
14867        // Serialize this with the rest of the install-process message chain.  In the
14868        // restore-at-install case, this Runnable will necessarily run before the
14869        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14870        // are coherent.  In the non-restore case, the app has already completed install
14871        // and been launched through some other means, so it is not in a problematic
14872        // state for observers to see the FIRST_LAUNCH signal.
14873        mHandler.post(new Runnable() {
14874            @Override
14875            public void run() {
14876                for (int i = 0; i < mRunningInstalls.size(); i++) {
14877                    final PostInstallData data = mRunningInstalls.valueAt(i);
14878                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14879                        continue;
14880                    }
14881                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14882                        // right package; but is it for the right user?
14883                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14884                            if (userId == data.res.newUsers[uIndex]) {
14885                                if (DEBUG_BACKUP) {
14886                                    Slog.i(TAG, "Package " + packageName
14887                                            + " being restored so deferring FIRST_LAUNCH");
14888                                }
14889                                return;
14890                            }
14891                        }
14892                    }
14893                }
14894                // didn't find it, so not being restored
14895                if (DEBUG_BACKUP) {
14896                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14897                }
14898                final boolean isInstantApp = isInstantApp(packageName, userId);
14899                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14900                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14901                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14902            }
14903        });
14904    }
14905
14906    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14907            int[] userIds, int[] instantUserIds) {
14908        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14909                installerPkg, null, userIds, instantUserIds);
14910    }
14911
14912    private abstract class HandlerParams {
14913        private static final int MAX_RETRIES = 4;
14914
14915        /**
14916         * Number of times startCopy() has been attempted and had a non-fatal
14917         * error.
14918         */
14919        private int mRetries = 0;
14920
14921        /** User handle for the user requesting the information or installation. */
14922        private final UserHandle mUser;
14923        String traceMethod;
14924        int traceCookie;
14925
14926        HandlerParams(UserHandle user) {
14927            mUser = user;
14928        }
14929
14930        UserHandle getUser() {
14931            return mUser;
14932        }
14933
14934        HandlerParams setTraceMethod(String traceMethod) {
14935            this.traceMethod = traceMethod;
14936            return this;
14937        }
14938
14939        HandlerParams setTraceCookie(int traceCookie) {
14940            this.traceCookie = traceCookie;
14941            return this;
14942        }
14943
14944        final boolean startCopy() {
14945            boolean res;
14946            try {
14947                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14948
14949                if (++mRetries > MAX_RETRIES) {
14950                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14951                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14952                    handleServiceError();
14953                    return false;
14954                } else {
14955                    handleStartCopy();
14956                    res = true;
14957                }
14958            } catch (RemoteException e) {
14959                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14960                mHandler.sendEmptyMessage(MCS_RECONNECT);
14961                res = false;
14962            }
14963            handleReturnCode();
14964            return res;
14965        }
14966
14967        final void serviceError() {
14968            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14969            handleServiceError();
14970            handleReturnCode();
14971        }
14972
14973        abstract void handleStartCopy() throws RemoteException;
14974        abstract void handleServiceError();
14975        abstract void handleReturnCode();
14976    }
14977
14978    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14979        for (File path : paths) {
14980            try {
14981                mcs.clearDirectory(path.getAbsolutePath());
14982            } catch (RemoteException e) {
14983            }
14984        }
14985    }
14986
14987    static class OriginInfo {
14988        /**
14989         * Location where install is coming from, before it has been
14990         * copied/renamed into place. This could be a single monolithic APK
14991         * file, or a cluster directory. This location may be untrusted.
14992         */
14993        final File file;
14994
14995        /**
14996         * Flag indicating that {@link #file} or {@link #cid} has already been
14997         * staged, meaning downstream users don't need to defensively copy the
14998         * contents.
14999         */
15000        final boolean staged;
15001
15002        /**
15003         * Flag indicating that {@link #file} or {@link #cid} is an already
15004         * installed app that is being moved.
15005         */
15006        final boolean existing;
15007
15008        final String resolvedPath;
15009        final File resolvedFile;
15010
15011        static OriginInfo fromNothing() {
15012            return new OriginInfo(null, false, false);
15013        }
15014
15015        static OriginInfo fromUntrustedFile(File file) {
15016            return new OriginInfo(file, false, false);
15017        }
15018
15019        static OriginInfo fromExistingFile(File file) {
15020            return new OriginInfo(file, false, true);
15021        }
15022
15023        static OriginInfo fromStagedFile(File file) {
15024            return new OriginInfo(file, true, false);
15025        }
15026
15027        private OriginInfo(File file, boolean staged, boolean existing) {
15028            this.file = file;
15029            this.staged = staged;
15030            this.existing = existing;
15031
15032            if (file != null) {
15033                resolvedPath = file.getAbsolutePath();
15034                resolvedFile = file;
15035            } else {
15036                resolvedPath = null;
15037                resolvedFile = null;
15038            }
15039        }
15040    }
15041
15042    static class MoveInfo {
15043        final int moveId;
15044        final String fromUuid;
15045        final String toUuid;
15046        final String packageName;
15047        final String dataAppName;
15048        final int appId;
15049        final String seinfo;
15050        final int targetSdkVersion;
15051
15052        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15053                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15054            this.moveId = moveId;
15055            this.fromUuid = fromUuid;
15056            this.toUuid = toUuid;
15057            this.packageName = packageName;
15058            this.dataAppName = dataAppName;
15059            this.appId = appId;
15060            this.seinfo = seinfo;
15061            this.targetSdkVersion = targetSdkVersion;
15062        }
15063    }
15064
15065    static class VerificationInfo {
15066        /** A constant used to indicate that a uid value is not present. */
15067        public static final int NO_UID = -1;
15068
15069        /** URI referencing where the package was downloaded from. */
15070        final Uri originatingUri;
15071
15072        /** HTTP referrer URI associated with the originatingURI. */
15073        final Uri referrer;
15074
15075        /** UID of the application that the install request originated from. */
15076        final int originatingUid;
15077
15078        /** UID of application requesting the install */
15079        final int installerUid;
15080
15081        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15082            this.originatingUri = originatingUri;
15083            this.referrer = referrer;
15084            this.originatingUid = originatingUid;
15085            this.installerUid = installerUid;
15086        }
15087    }
15088
15089    class InstallParams extends HandlerParams {
15090        final OriginInfo origin;
15091        final MoveInfo move;
15092        final IPackageInstallObserver2 observer;
15093        int installFlags;
15094        final String installerPackageName;
15095        final String volumeUuid;
15096        private InstallArgs mArgs;
15097        private int mRet;
15098        final String packageAbiOverride;
15099        final String[] grantedRuntimePermissions;
15100        final VerificationInfo verificationInfo;
15101        final PackageParser.SigningDetails signingDetails;
15102        final int installReason;
15103
15104        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15105                int installFlags, String installerPackageName, String volumeUuid,
15106                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15107                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
15108            super(user);
15109            this.origin = origin;
15110            this.move = move;
15111            this.observer = observer;
15112            this.installFlags = installFlags;
15113            this.installerPackageName = installerPackageName;
15114            this.volumeUuid = volumeUuid;
15115            this.verificationInfo = verificationInfo;
15116            this.packageAbiOverride = packageAbiOverride;
15117            this.grantedRuntimePermissions = grantedPermissions;
15118            this.signingDetails = signingDetails;
15119            this.installReason = installReason;
15120        }
15121
15122        @Override
15123        public String toString() {
15124            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15125                    + " file=" + origin.file + "}";
15126        }
15127
15128        private int installLocationPolicy(PackageInfoLite pkgLite) {
15129            String packageName = pkgLite.packageName;
15130            int installLocation = pkgLite.installLocation;
15131            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15132            // reader
15133            synchronized (mPackages) {
15134                // Currently installed package which the new package is attempting to replace or
15135                // null if no such package is installed.
15136                PackageParser.Package installedPkg = mPackages.get(packageName);
15137                // Package which currently owns the data which the new package will own if installed.
15138                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15139                // will be null whereas dataOwnerPkg will contain information about the package
15140                // which was uninstalled while keeping its data.
15141                PackageParser.Package dataOwnerPkg = installedPkg;
15142                if (dataOwnerPkg  == null) {
15143                    PackageSetting ps = mSettings.mPackages.get(packageName);
15144                    if (ps != null) {
15145                        dataOwnerPkg = ps.pkg;
15146                    }
15147                }
15148
15149                if (dataOwnerPkg != null) {
15150                    // If installed, the package will get access to data left on the device by its
15151                    // predecessor. As a security measure, this is permited only if this is not a
15152                    // version downgrade or if the predecessor package is marked as debuggable and
15153                    // a downgrade is explicitly requested.
15154                    //
15155                    // On debuggable platform builds, downgrades are permitted even for
15156                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15157                    // not offer security guarantees and thus it's OK to disable some security
15158                    // mechanisms to make debugging/testing easier on those builds. However, even on
15159                    // debuggable builds downgrades of packages are permitted only if requested via
15160                    // installFlags. This is because we aim to keep the behavior of debuggable
15161                    // platform builds as close as possible to the behavior of non-debuggable
15162                    // platform builds.
15163                    final boolean downgradeRequested =
15164                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15165                    final boolean packageDebuggable =
15166                                (dataOwnerPkg.applicationInfo.flags
15167                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15168                    final boolean downgradePermitted =
15169                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15170                    if (!downgradePermitted) {
15171                        try {
15172                            checkDowngrade(dataOwnerPkg, pkgLite);
15173                        } catch (PackageManagerException e) {
15174                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15175                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15176                        }
15177                    }
15178                }
15179
15180                if (installedPkg != null) {
15181                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15182                        // Check for updated system application.
15183                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15184                            if (onSd) {
15185                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15186                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15187                            }
15188                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15189                        } else {
15190                            if (onSd) {
15191                                // Install flag overrides everything.
15192                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15193                            }
15194                            // If current upgrade specifies particular preference
15195                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15196                                // Application explicitly specified internal.
15197                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15198                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15199                                // App explictly prefers external. Let policy decide
15200                            } else {
15201                                // Prefer previous location
15202                                if (isExternal(installedPkg)) {
15203                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15204                                }
15205                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15206                            }
15207                        }
15208                    } else {
15209                        // Invalid install. Return error code
15210                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15211                    }
15212                }
15213            }
15214            // All the special cases have been taken care of.
15215            // Return result based on recommended install location.
15216            if (onSd) {
15217                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15218            }
15219            return pkgLite.recommendedInstallLocation;
15220        }
15221
15222        /*
15223         * Invoke remote method to get package information and install
15224         * location values. Override install location based on default
15225         * policy if needed and then create install arguments based
15226         * on the install location.
15227         */
15228        public void handleStartCopy() throws RemoteException {
15229            int ret = PackageManager.INSTALL_SUCCEEDED;
15230
15231            // If we're already staged, we've firmly committed to an install location
15232            if (origin.staged) {
15233                if (origin.file != null) {
15234                    installFlags |= PackageManager.INSTALL_INTERNAL;
15235                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15236                } else {
15237                    throw new IllegalStateException("Invalid stage location");
15238                }
15239            }
15240
15241            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15242            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15243            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15244            PackageInfoLite pkgLite = null;
15245
15246            if (onInt && onSd) {
15247                // Check if both bits are set.
15248                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15249                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15250            } else if (onSd && ephemeral) {
15251                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15252                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15253            } else {
15254                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15255                        packageAbiOverride);
15256
15257                if (DEBUG_INSTANT && ephemeral) {
15258                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15259                }
15260
15261                /*
15262                 * If we have too little free space, try to free cache
15263                 * before giving up.
15264                 */
15265                if (!origin.staged && pkgLite.recommendedInstallLocation
15266                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15267                    // TODO: focus freeing disk space on the target device
15268                    final StorageManager storage = StorageManager.from(mContext);
15269                    final long lowThreshold = storage.getStorageLowBytes(
15270                            Environment.getDataDirectory());
15271
15272                    final long sizeBytes = mContainerService.calculateInstalledSize(
15273                            origin.resolvedPath, packageAbiOverride);
15274
15275                    try {
15276                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15277                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15278                                installFlags, packageAbiOverride);
15279                    } catch (InstallerException e) {
15280                        Slog.w(TAG, "Failed to free cache", e);
15281                    }
15282
15283                    /*
15284                     * The cache free must have deleted the file we
15285                     * downloaded to install.
15286                     *
15287                     * TODO: fix the "freeCache" call to not delete
15288                     *       the file we care about.
15289                     */
15290                    if (pkgLite.recommendedInstallLocation
15291                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15292                        pkgLite.recommendedInstallLocation
15293                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15294                    }
15295                }
15296            }
15297
15298            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15299                int loc = pkgLite.recommendedInstallLocation;
15300                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15301                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15302                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15303                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15304                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15305                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15306                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15307                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15308                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15309                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15310                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15311                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15312                } else {
15313                    // Override with defaults if needed.
15314                    loc = installLocationPolicy(pkgLite);
15315                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15316                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15317                    } else if (!onSd && !onInt) {
15318                        // Override install location with flags
15319                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15320                            // Set the flag to install on external media.
15321                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15322                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15323                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15324                            if (DEBUG_INSTANT) {
15325                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15326                            }
15327                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15328                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15329                                    |PackageManager.INSTALL_INTERNAL);
15330                        } else {
15331                            // Make sure the flag for installing on external
15332                            // media is unset
15333                            installFlags |= PackageManager.INSTALL_INTERNAL;
15334                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15335                        }
15336                    }
15337                }
15338            }
15339
15340            final InstallArgs args = createInstallArgs(this);
15341            mArgs = args;
15342
15343            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15344                // TODO: http://b/22976637
15345                // Apps installed for "all" users use the device owner to verify the app
15346                UserHandle verifierUser = getUser();
15347                if (verifierUser == UserHandle.ALL) {
15348                    verifierUser = UserHandle.SYSTEM;
15349                }
15350
15351                /*
15352                 * Determine if we have any installed package verifiers. If we
15353                 * do, then we'll defer to them to verify the packages.
15354                 */
15355                final int requiredUid = mRequiredVerifierPackage == null ? -1
15356                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15357                                verifierUser.getIdentifier());
15358                final int installerUid =
15359                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15360                if (!origin.existing && requiredUid != -1
15361                        && isVerificationEnabled(
15362                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15363                    final Intent verification = new Intent(
15364                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15365                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15366                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15367                            PACKAGE_MIME_TYPE);
15368                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15369
15370                    // Query all live verifiers based on current user state
15371                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15372                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15373                            false /*allowDynamicSplits*/);
15374
15375                    if (DEBUG_VERIFY) {
15376                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15377                                + verification.toString() + " with " + pkgLite.verifiers.length
15378                                + " optional verifiers");
15379                    }
15380
15381                    final int verificationId = mPendingVerificationToken++;
15382
15383                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15384
15385                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15386                            installerPackageName);
15387
15388                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15389                            installFlags);
15390
15391                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15392                            pkgLite.packageName);
15393
15394                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15395                            pkgLite.versionCode);
15396
15397                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15398                            pkgLite.getLongVersionCode());
15399
15400                    if (verificationInfo != null) {
15401                        if (verificationInfo.originatingUri != null) {
15402                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15403                                    verificationInfo.originatingUri);
15404                        }
15405                        if (verificationInfo.referrer != null) {
15406                            verification.putExtra(Intent.EXTRA_REFERRER,
15407                                    verificationInfo.referrer);
15408                        }
15409                        if (verificationInfo.originatingUid >= 0) {
15410                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15411                                    verificationInfo.originatingUid);
15412                        }
15413                        if (verificationInfo.installerUid >= 0) {
15414                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15415                                    verificationInfo.installerUid);
15416                        }
15417                    }
15418
15419                    final PackageVerificationState verificationState = new PackageVerificationState(
15420                            requiredUid, args);
15421
15422                    mPendingVerification.append(verificationId, verificationState);
15423
15424                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15425                            receivers, verificationState);
15426
15427                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15428                    final long idleDuration = getVerificationTimeout();
15429
15430                    /*
15431                     * If any sufficient verifiers were listed in the package
15432                     * manifest, attempt to ask them.
15433                     */
15434                    if (sufficientVerifiers != null) {
15435                        final int N = sufficientVerifiers.size();
15436                        if (N == 0) {
15437                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15438                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15439                        } else {
15440                            for (int i = 0; i < N; i++) {
15441                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15442                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15443                                        verifierComponent.getPackageName(), idleDuration,
15444                                        verifierUser.getIdentifier(), false, "package verifier");
15445
15446                                final Intent sufficientIntent = new Intent(verification);
15447                                sufficientIntent.setComponent(verifierComponent);
15448                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15449                            }
15450                        }
15451                    }
15452
15453                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15454                            mRequiredVerifierPackage, receivers);
15455                    if (ret == PackageManager.INSTALL_SUCCEEDED
15456                            && mRequiredVerifierPackage != null) {
15457                        Trace.asyncTraceBegin(
15458                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15459                        /*
15460                         * Send the intent to the required verification agent,
15461                         * but only start the verification timeout after the
15462                         * target BroadcastReceivers have run.
15463                         */
15464                        verification.setComponent(requiredVerifierComponent);
15465                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15466                                mRequiredVerifierPackage, idleDuration,
15467                                verifierUser.getIdentifier(), false, "package verifier");
15468                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15469                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15470                                new BroadcastReceiver() {
15471                                    @Override
15472                                    public void onReceive(Context context, Intent intent) {
15473                                        final Message msg = mHandler
15474                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15475                                        msg.arg1 = verificationId;
15476                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15477                                    }
15478                                }, null, 0, null, null);
15479
15480                        /*
15481                         * We don't want the copy to proceed until verification
15482                         * succeeds, so null out this field.
15483                         */
15484                        mArgs = null;
15485                    }
15486                } else {
15487                    /*
15488                     * No package verification is enabled, so immediately start
15489                     * the remote call to initiate copy using temporary file.
15490                     */
15491                    ret = args.copyApk(mContainerService, true);
15492                }
15493            }
15494
15495            mRet = ret;
15496        }
15497
15498        @Override
15499        void handleReturnCode() {
15500            // If mArgs is null, then MCS couldn't be reached. When it
15501            // reconnects, it will try again to install. At that point, this
15502            // will succeed.
15503            if (mArgs != null) {
15504                processPendingInstall(mArgs, mRet);
15505            }
15506        }
15507
15508        @Override
15509        void handleServiceError() {
15510            mArgs = createInstallArgs(this);
15511            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15512        }
15513    }
15514
15515    private InstallArgs createInstallArgs(InstallParams params) {
15516        if (params.move != null) {
15517            return new MoveInstallArgs(params);
15518        } else {
15519            return new FileInstallArgs(params);
15520        }
15521    }
15522
15523    /**
15524     * Create args that describe an existing installed package. Typically used
15525     * when cleaning up old installs, or used as a move source.
15526     */
15527    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15528            String resourcePath, String[] instructionSets) {
15529        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15530    }
15531
15532    static abstract class InstallArgs {
15533        /** @see InstallParams#origin */
15534        final OriginInfo origin;
15535        /** @see InstallParams#move */
15536        final MoveInfo move;
15537
15538        final IPackageInstallObserver2 observer;
15539        // Always refers to PackageManager flags only
15540        final int installFlags;
15541        final String installerPackageName;
15542        final String volumeUuid;
15543        final UserHandle user;
15544        final String abiOverride;
15545        final String[] installGrantPermissions;
15546        /** If non-null, drop an async trace when the install completes */
15547        final String traceMethod;
15548        final int traceCookie;
15549        final PackageParser.SigningDetails signingDetails;
15550        final int installReason;
15551
15552        // The list of instruction sets supported by this app. This is currently
15553        // only used during the rmdex() phase to clean up resources. We can get rid of this
15554        // if we move dex files under the common app path.
15555        /* nullable */ String[] instructionSets;
15556
15557        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15558                int installFlags, String installerPackageName, String volumeUuid,
15559                UserHandle user, String[] instructionSets,
15560                String abiOverride, String[] installGrantPermissions,
15561                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15562                int installReason) {
15563            this.origin = origin;
15564            this.move = move;
15565            this.installFlags = installFlags;
15566            this.observer = observer;
15567            this.installerPackageName = installerPackageName;
15568            this.volumeUuid = volumeUuid;
15569            this.user = user;
15570            this.instructionSets = instructionSets;
15571            this.abiOverride = abiOverride;
15572            this.installGrantPermissions = installGrantPermissions;
15573            this.traceMethod = traceMethod;
15574            this.traceCookie = traceCookie;
15575            this.signingDetails = signingDetails;
15576            this.installReason = installReason;
15577        }
15578
15579        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15580        abstract int doPreInstall(int status);
15581
15582        /**
15583         * Rename package into final resting place. All paths on the given
15584         * scanned package should be updated to reflect the rename.
15585         */
15586        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15587        abstract int doPostInstall(int status, int uid);
15588
15589        /** @see PackageSettingBase#codePathString */
15590        abstract String getCodePath();
15591        /** @see PackageSettingBase#resourcePathString */
15592        abstract String getResourcePath();
15593
15594        // Need installer lock especially for dex file removal.
15595        abstract void cleanUpResourcesLI();
15596        abstract boolean doPostDeleteLI(boolean delete);
15597
15598        /**
15599         * Called before the source arguments are copied. This is used mostly
15600         * for MoveParams when it needs to read the source file to put it in the
15601         * destination.
15602         */
15603        int doPreCopy() {
15604            return PackageManager.INSTALL_SUCCEEDED;
15605        }
15606
15607        /**
15608         * Called after the source arguments are copied. This is used mostly for
15609         * MoveParams when it needs to read the source file to put it in the
15610         * destination.
15611         */
15612        int doPostCopy(int uid) {
15613            return PackageManager.INSTALL_SUCCEEDED;
15614        }
15615
15616        protected boolean isFwdLocked() {
15617            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15618        }
15619
15620        protected boolean isExternalAsec() {
15621            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15622        }
15623
15624        protected boolean isEphemeral() {
15625            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15626        }
15627
15628        UserHandle getUser() {
15629            return user;
15630        }
15631    }
15632
15633    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15634        if (!allCodePaths.isEmpty()) {
15635            if (instructionSets == null) {
15636                throw new IllegalStateException("instructionSet == null");
15637            }
15638            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15639            for (String codePath : allCodePaths) {
15640                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15641                    try {
15642                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15643                    } catch (InstallerException ignored) {
15644                    }
15645                }
15646            }
15647        }
15648    }
15649
15650    /**
15651     * Logic to handle installation of non-ASEC applications, including copying
15652     * and renaming logic.
15653     */
15654    class FileInstallArgs extends InstallArgs {
15655        private File codeFile;
15656        private File resourceFile;
15657
15658        // Example topology:
15659        // /data/app/com.example/base.apk
15660        // /data/app/com.example/split_foo.apk
15661        // /data/app/com.example/lib/arm/libfoo.so
15662        // /data/app/com.example/lib/arm64/libfoo.so
15663        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15664
15665        /** New install */
15666        FileInstallArgs(InstallParams params) {
15667            super(params.origin, params.move, params.observer, params.installFlags,
15668                    params.installerPackageName, params.volumeUuid,
15669                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15670                    params.grantedRuntimePermissions,
15671                    params.traceMethod, params.traceCookie, params.signingDetails,
15672                    params.installReason);
15673            if (isFwdLocked()) {
15674                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15675            }
15676        }
15677
15678        /** Existing install */
15679        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15680            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15681                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15682                    PackageManager.INSTALL_REASON_UNKNOWN);
15683            this.codeFile = (codePath != null) ? new File(codePath) : null;
15684            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15685        }
15686
15687        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15688            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15689            try {
15690                return doCopyApk(imcs, temp);
15691            } finally {
15692                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15693            }
15694        }
15695
15696        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15697            if (origin.staged) {
15698                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15699                codeFile = origin.file;
15700                resourceFile = origin.file;
15701                return PackageManager.INSTALL_SUCCEEDED;
15702            }
15703
15704            try {
15705                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15706                final File tempDir =
15707                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15708                codeFile = tempDir;
15709                resourceFile = tempDir;
15710            } catch (IOException e) {
15711                Slog.w(TAG, "Failed to create copy file: " + e);
15712                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15713            }
15714
15715            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15716                @Override
15717                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15718                    if (!FileUtils.isValidExtFilename(name)) {
15719                        throw new IllegalArgumentException("Invalid filename: " + name);
15720                    }
15721                    try {
15722                        final File file = new File(codeFile, name);
15723                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15724                                O_RDWR | O_CREAT, 0644);
15725                        Os.chmod(file.getAbsolutePath(), 0644);
15726                        return new ParcelFileDescriptor(fd);
15727                    } catch (ErrnoException e) {
15728                        throw new RemoteException("Failed to open: " + e.getMessage());
15729                    }
15730                }
15731            };
15732
15733            int ret = PackageManager.INSTALL_SUCCEEDED;
15734            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15735            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15736                Slog.e(TAG, "Failed to copy package");
15737                return ret;
15738            }
15739
15740            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15741            NativeLibraryHelper.Handle handle = null;
15742            try {
15743                handle = NativeLibraryHelper.Handle.create(codeFile);
15744                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15745                        abiOverride);
15746            } catch (IOException e) {
15747                Slog.e(TAG, "Copying native libraries failed", e);
15748                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15749            } finally {
15750                IoUtils.closeQuietly(handle);
15751            }
15752
15753            return ret;
15754        }
15755
15756        int doPreInstall(int status) {
15757            if (status != PackageManager.INSTALL_SUCCEEDED) {
15758                cleanUp();
15759            }
15760            return status;
15761        }
15762
15763        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15764            if (status != PackageManager.INSTALL_SUCCEEDED) {
15765                cleanUp();
15766                return false;
15767            }
15768
15769            final File targetDir = codeFile.getParentFile();
15770            final File beforeCodeFile = codeFile;
15771            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15772
15773            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15774            try {
15775                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15776            } catch (ErrnoException e) {
15777                Slog.w(TAG, "Failed to rename", e);
15778                return false;
15779            }
15780
15781            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15782                Slog.w(TAG, "Failed to restorecon");
15783                return false;
15784            }
15785
15786            // Reflect the rename internally
15787            codeFile = afterCodeFile;
15788            resourceFile = afterCodeFile;
15789
15790            // Reflect the rename in scanned details
15791            try {
15792                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15793            } catch (IOException e) {
15794                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15795                return false;
15796            }
15797            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15798                    afterCodeFile, pkg.baseCodePath));
15799            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15800                    afterCodeFile, pkg.splitCodePaths));
15801
15802            // Reflect the rename in app info
15803            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15804            pkg.setApplicationInfoCodePath(pkg.codePath);
15805            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15806            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15807            pkg.setApplicationInfoResourcePath(pkg.codePath);
15808            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15809            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15810
15811            return true;
15812        }
15813
15814        int doPostInstall(int status, int uid) {
15815            if (status != PackageManager.INSTALL_SUCCEEDED) {
15816                cleanUp();
15817            }
15818            return status;
15819        }
15820
15821        @Override
15822        String getCodePath() {
15823            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15824        }
15825
15826        @Override
15827        String getResourcePath() {
15828            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15829        }
15830
15831        private boolean cleanUp() {
15832            if (codeFile == null || !codeFile.exists()) {
15833                return false;
15834            }
15835
15836            removeCodePathLI(codeFile);
15837
15838            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15839                resourceFile.delete();
15840            }
15841
15842            return true;
15843        }
15844
15845        void cleanUpResourcesLI() {
15846            // Try enumerating all code paths before deleting
15847            List<String> allCodePaths = Collections.EMPTY_LIST;
15848            if (codeFile != null && codeFile.exists()) {
15849                try {
15850                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15851                    allCodePaths = pkg.getAllCodePaths();
15852                } catch (PackageParserException e) {
15853                    // Ignored; we tried our best
15854                }
15855            }
15856
15857            cleanUp();
15858            removeDexFiles(allCodePaths, instructionSets);
15859        }
15860
15861        boolean doPostDeleteLI(boolean delete) {
15862            // XXX err, shouldn't we respect the delete flag?
15863            cleanUpResourcesLI();
15864            return true;
15865        }
15866    }
15867
15868    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15869            PackageManagerException {
15870        if (copyRet < 0) {
15871            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15872                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15873                throw new PackageManagerException(copyRet, message);
15874            }
15875        }
15876    }
15877
15878    /**
15879     * Extract the StorageManagerService "container ID" from the full code path of an
15880     * .apk.
15881     */
15882    static String cidFromCodePath(String fullCodePath) {
15883        int eidx = fullCodePath.lastIndexOf("/");
15884        String subStr1 = fullCodePath.substring(0, eidx);
15885        int sidx = subStr1.lastIndexOf("/");
15886        return subStr1.substring(sidx+1, eidx);
15887    }
15888
15889    /**
15890     * Logic to handle movement of existing installed applications.
15891     */
15892    class MoveInstallArgs extends InstallArgs {
15893        private File codeFile;
15894        private File resourceFile;
15895
15896        /** New install */
15897        MoveInstallArgs(InstallParams params) {
15898            super(params.origin, params.move, params.observer, params.installFlags,
15899                    params.installerPackageName, params.volumeUuid,
15900                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15901                    params.grantedRuntimePermissions,
15902                    params.traceMethod, params.traceCookie, params.signingDetails,
15903                    params.installReason);
15904        }
15905
15906        int copyApk(IMediaContainerService imcs, boolean temp) {
15907            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15908                    + move.fromUuid + " to " + move.toUuid);
15909            synchronized (mInstaller) {
15910                try {
15911                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15912                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15913                } catch (InstallerException e) {
15914                    Slog.w(TAG, "Failed to move app", e);
15915                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15916                }
15917            }
15918
15919            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15920            resourceFile = codeFile;
15921            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15922
15923            return PackageManager.INSTALL_SUCCEEDED;
15924        }
15925
15926        int doPreInstall(int status) {
15927            if (status != PackageManager.INSTALL_SUCCEEDED) {
15928                cleanUp(move.toUuid);
15929            }
15930            return status;
15931        }
15932
15933        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15934            if (status != PackageManager.INSTALL_SUCCEEDED) {
15935                cleanUp(move.toUuid);
15936                return false;
15937            }
15938
15939            // Reflect the move in app info
15940            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15941            pkg.setApplicationInfoCodePath(pkg.codePath);
15942            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15943            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15944            pkg.setApplicationInfoResourcePath(pkg.codePath);
15945            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15946            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15947
15948            return true;
15949        }
15950
15951        int doPostInstall(int status, int uid) {
15952            if (status == PackageManager.INSTALL_SUCCEEDED) {
15953                cleanUp(move.fromUuid);
15954            } else {
15955                cleanUp(move.toUuid);
15956            }
15957            return status;
15958        }
15959
15960        @Override
15961        String getCodePath() {
15962            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15963        }
15964
15965        @Override
15966        String getResourcePath() {
15967            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15968        }
15969
15970        private boolean cleanUp(String volumeUuid) {
15971            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15972                    move.dataAppName);
15973            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15974            final int[] userIds = sUserManager.getUserIds();
15975            synchronized (mInstallLock) {
15976                // Clean up both app data and code
15977                // All package moves are frozen until finished
15978                for (int userId : userIds) {
15979                    try {
15980                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15981                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15982                    } catch (InstallerException e) {
15983                        Slog.w(TAG, String.valueOf(e));
15984                    }
15985                }
15986                removeCodePathLI(codeFile);
15987            }
15988            return true;
15989        }
15990
15991        void cleanUpResourcesLI() {
15992            throw new UnsupportedOperationException();
15993        }
15994
15995        boolean doPostDeleteLI(boolean delete) {
15996            throw new UnsupportedOperationException();
15997        }
15998    }
15999
16000    static String getAsecPackageName(String packageCid) {
16001        int idx = packageCid.lastIndexOf("-");
16002        if (idx == -1) {
16003            return packageCid;
16004        }
16005        return packageCid.substring(0, idx);
16006    }
16007
16008    // Utility method used to create code paths based on package name and available index.
16009    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16010        String idxStr = "";
16011        int idx = 1;
16012        // Fall back to default value of idx=1 if prefix is not
16013        // part of oldCodePath
16014        if (oldCodePath != null) {
16015            String subStr = oldCodePath;
16016            // Drop the suffix right away
16017            if (suffix != null && subStr.endsWith(suffix)) {
16018                subStr = subStr.substring(0, subStr.length() - suffix.length());
16019            }
16020            // If oldCodePath already contains prefix find out the
16021            // ending index to either increment or decrement.
16022            int sidx = subStr.lastIndexOf(prefix);
16023            if (sidx != -1) {
16024                subStr = subStr.substring(sidx + prefix.length());
16025                if (subStr != null) {
16026                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16027                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16028                    }
16029                    try {
16030                        idx = Integer.parseInt(subStr);
16031                        if (idx <= 1) {
16032                            idx++;
16033                        } else {
16034                            idx--;
16035                        }
16036                    } catch(NumberFormatException e) {
16037                    }
16038                }
16039            }
16040        }
16041        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16042        return prefix + idxStr;
16043    }
16044
16045    private File getNextCodePath(File targetDir, String packageName) {
16046        File result;
16047        SecureRandom random = new SecureRandom();
16048        byte[] bytes = new byte[16];
16049        do {
16050            random.nextBytes(bytes);
16051            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16052            result = new File(targetDir, packageName + "-" + suffix);
16053        } while (result.exists());
16054        return result;
16055    }
16056
16057    // Utility method that returns the relative package path with respect
16058    // to the installation directory. Like say for /data/data/com.test-1.apk
16059    // string com.test-1 is returned.
16060    static String deriveCodePathName(String codePath) {
16061        if (codePath == null) {
16062            return null;
16063        }
16064        final File codeFile = new File(codePath);
16065        final String name = codeFile.getName();
16066        if (codeFile.isDirectory()) {
16067            return name;
16068        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16069            final int lastDot = name.lastIndexOf('.');
16070            return name.substring(0, lastDot);
16071        } else {
16072            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16073            return null;
16074        }
16075    }
16076
16077    static class PackageInstalledInfo {
16078        String name;
16079        int uid;
16080        // The set of users that originally had this package installed.
16081        int[] origUsers;
16082        // The set of users that now have this package installed.
16083        int[] newUsers;
16084        PackageParser.Package pkg;
16085        int returnCode;
16086        String returnMsg;
16087        String installerPackageName;
16088        PackageRemovedInfo removedInfo;
16089        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16090
16091        public void setError(int code, String msg) {
16092            setReturnCode(code);
16093            setReturnMessage(msg);
16094            Slog.w(TAG, msg);
16095        }
16096
16097        public void setError(String msg, PackageParserException e) {
16098            setReturnCode(e.error);
16099            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16100            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16101            for (int i = 0; i < childCount; i++) {
16102                addedChildPackages.valueAt(i).setError(msg, e);
16103            }
16104            Slog.w(TAG, msg, e);
16105        }
16106
16107        public void setError(String msg, PackageManagerException e) {
16108            returnCode = e.error;
16109            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16110            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16111            for (int i = 0; i < childCount; i++) {
16112                addedChildPackages.valueAt(i).setError(msg, e);
16113            }
16114            Slog.w(TAG, msg, e);
16115        }
16116
16117        public void setReturnCode(int returnCode) {
16118            this.returnCode = returnCode;
16119            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16120            for (int i = 0; i < childCount; i++) {
16121                addedChildPackages.valueAt(i).returnCode = returnCode;
16122            }
16123        }
16124
16125        private void setReturnMessage(String returnMsg) {
16126            this.returnMsg = returnMsg;
16127            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16128            for (int i = 0; i < childCount; i++) {
16129                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16130            }
16131        }
16132
16133        // In some error cases we want to convey more info back to the observer
16134        String origPackage;
16135        String origPermission;
16136    }
16137
16138    /*
16139     * Install a non-existing package.
16140     */
16141    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16142            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16143            String volumeUuid, PackageInstalledInfo res, int installReason) {
16144        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16145
16146        // Remember this for later, in case we need to rollback this install
16147        String pkgName = pkg.packageName;
16148
16149        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16150
16151        synchronized(mPackages) {
16152            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16153            if (renamedPackage != null) {
16154                // A package with the same name is already installed, though
16155                // it has been renamed to an older name.  The package we
16156                // are trying to install should be installed as an update to
16157                // the existing one, but that has not been requested, so bail.
16158                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16159                        + " without first uninstalling package running as "
16160                        + renamedPackage);
16161                return;
16162            }
16163            if (mPackages.containsKey(pkgName)) {
16164                // Don't allow installation over an existing package with the same name.
16165                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16166                        + " without first uninstalling.");
16167                return;
16168            }
16169        }
16170
16171        try {
16172            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
16173                    System.currentTimeMillis(), user);
16174
16175            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16176
16177            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16178                prepareAppDataAfterInstallLIF(newPackage);
16179
16180            } else {
16181                // Remove package from internal structures, but keep around any
16182                // data that might have already existed
16183                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16184                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16185            }
16186        } catch (PackageManagerException e) {
16187            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16188        }
16189
16190        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16191    }
16192
16193    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16194        try (DigestInputStream digestStream =
16195                new DigestInputStream(new FileInputStream(file), digest)) {
16196            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16197        }
16198    }
16199
16200    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16201            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16202            PackageInstalledInfo res, int installReason) {
16203        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16204
16205        final PackageParser.Package oldPackage;
16206        final PackageSetting ps;
16207        final String pkgName = pkg.packageName;
16208        final int[] allUsers;
16209        final int[] installedUsers;
16210
16211        synchronized(mPackages) {
16212            oldPackage = mPackages.get(pkgName);
16213            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16214
16215            // don't allow upgrade to target a release SDK from a pre-release SDK
16216            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16217                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16218            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16219                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16220            if (oldTargetsPreRelease
16221                    && !newTargetsPreRelease
16222                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16223                Slog.w(TAG, "Can't install package targeting released sdk");
16224                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16225                return;
16226            }
16227
16228            ps = mSettings.mPackages.get(pkgName);
16229
16230            // verify signatures are valid
16231            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16232            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16233                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16234                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16235                            "New package not signed by keys specified by upgrade-keysets: "
16236                                    + pkgName);
16237                    return;
16238                }
16239            } else {
16240
16241                // default to original signature matching
16242                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16243                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
16244                                && !oldPackage.mSigningDetails.checkCapability(
16245                                        pkg.mSigningDetails,
16246                                        PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
16247                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16248                            "New package has a different signature: " + pkgName);
16249                    return;
16250                }
16251            }
16252
16253            // don't allow a system upgrade unless the upgrade hash matches
16254            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16255                byte[] digestBytes = null;
16256                try {
16257                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16258                    updateDigest(digest, new File(pkg.baseCodePath));
16259                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16260                        for (String path : pkg.splitCodePaths) {
16261                            updateDigest(digest, new File(path));
16262                        }
16263                    }
16264                    digestBytes = digest.digest();
16265                } catch (NoSuchAlgorithmException | IOException e) {
16266                    res.setError(INSTALL_FAILED_INVALID_APK,
16267                            "Could not compute hash: " + pkgName);
16268                    return;
16269                }
16270                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16271                    res.setError(INSTALL_FAILED_INVALID_APK,
16272                            "New package fails restrict-update check: " + pkgName);
16273                    return;
16274                }
16275                // retain upgrade restriction
16276                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16277            }
16278
16279            // Check for shared user id changes
16280            String invalidPackageName =
16281                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16282            if (invalidPackageName != null) {
16283                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16284                        "Package " + invalidPackageName + " tried to change user "
16285                                + oldPackage.mSharedUserId);
16286                return;
16287            }
16288
16289            // check if the new package supports all of the abis which the old package supports
16290            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16291            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16292            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16293                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16294                        "Update to package " + pkgName + " doesn't support multi arch");
16295                return;
16296            }
16297
16298            // In case of rollback, remember per-user/profile install state
16299            allUsers = sUserManager.getUserIds();
16300            installedUsers = ps.queryInstalledUsers(allUsers, true);
16301
16302            // don't allow an upgrade from full to ephemeral
16303            if (isInstantApp) {
16304                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16305                    for (int currentUser : allUsers) {
16306                        if (!ps.getInstantApp(currentUser)) {
16307                            // can't downgrade from full to instant
16308                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16309                                    + " for user: " + currentUser);
16310                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16311                            return;
16312                        }
16313                    }
16314                } else if (!ps.getInstantApp(user.getIdentifier())) {
16315                    // can't downgrade from full to instant
16316                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16317                            + " for user: " + user.getIdentifier());
16318                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16319                    return;
16320                }
16321            }
16322        }
16323
16324        // Update what is removed
16325        res.removedInfo = new PackageRemovedInfo(this);
16326        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16327        res.removedInfo.removedPackage = oldPackage.packageName;
16328        res.removedInfo.installerPackageName = ps.installerPackageName;
16329        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16330        res.removedInfo.isUpdate = true;
16331        res.removedInfo.origUsers = installedUsers;
16332        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16333        for (int i = 0; i < installedUsers.length; i++) {
16334            final int userId = installedUsers[i];
16335            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16336        }
16337
16338        final int childCount = (oldPackage.childPackages != null)
16339                ? oldPackage.childPackages.size() : 0;
16340        for (int i = 0; i < childCount; i++) {
16341            boolean childPackageUpdated = false;
16342            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16343            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16344            if (res.addedChildPackages != null) {
16345                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16346                if (childRes != null) {
16347                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16348                    childRes.removedInfo.removedPackage = childPkg.packageName;
16349                    if (childPs != null) {
16350                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16351                    }
16352                    childRes.removedInfo.isUpdate = true;
16353                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16354                    childPackageUpdated = true;
16355                }
16356            }
16357            if (!childPackageUpdated) {
16358                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16359                childRemovedRes.removedPackage = childPkg.packageName;
16360                if (childPs != null) {
16361                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16362                }
16363                childRemovedRes.isUpdate = false;
16364                childRemovedRes.dataRemoved = true;
16365                synchronized (mPackages) {
16366                    if (childPs != null) {
16367                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16368                    }
16369                }
16370                if (res.removedInfo.removedChildPackages == null) {
16371                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16372                }
16373                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16374            }
16375        }
16376
16377        boolean sysPkg = (isSystemApp(oldPackage));
16378        if (sysPkg) {
16379            // Set the system/privileged/oem/vendor/product flags as needed
16380            final boolean privileged =
16381                    (oldPackage.applicationInfo.privateFlags
16382                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16383            final boolean oem =
16384                    (oldPackage.applicationInfo.privateFlags
16385                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16386            final boolean vendor =
16387                    (oldPackage.applicationInfo.privateFlags
16388                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16389            final boolean product =
16390                    (oldPackage.applicationInfo.privateFlags
16391                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16392            final @ParseFlags int systemParseFlags = parseFlags;
16393            final @ScanFlags int systemScanFlags = scanFlags
16394                    | SCAN_AS_SYSTEM
16395                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16396                    | (oem ? SCAN_AS_OEM : 0)
16397                    | (vendor ? SCAN_AS_VENDOR : 0)
16398                    | (product ? SCAN_AS_PRODUCT : 0);
16399
16400            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16401                    user, allUsers, installerPackageName, res, installReason);
16402        } else {
16403            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16404                    user, allUsers, installerPackageName, res, installReason);
16405        }
16406    }
16407
16408    @Override
16409    public List<String> getPreviousCodePaths(String packageName) {
16410        final int callingUid = Binder.getCallingUid();
16411        final List<String> result = new ArrayList<>();
16412        if (getInstantAppPackageName(callingUid) != null) {
16413            return result;
16414        }
16415        final PackageSetting ps = mSettings.mPackages.get(packageName);
16416        if (ps != null
16417                && ps.oldCodePaths != null
16418                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16419            result.addAll(ps.oldCodePaths);
16420        }
16421        return result;
16422    }
16423
16424    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16425            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16426            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16427            String installerPackageName, PackageInstalledInfo res, int installReason) {
16428        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16429                + deletedPackage);
16430
16431        String pkgName = deletedPackage.packageName;
16432        boolean deletedPkg = true;
16433        boolean addedPkg = false;
16434        boolean updatedSettings = false;
16435        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16436        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16437                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16438
16439        final long origUpdateTime = (pkg.mExtras != null)
16440                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16441
16442        // First delete the existing package while retaining the data directory
16443        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16444                res.removedInfo, true, pkg)) {
16445            // If the existing package wasn't successfully deleted
16446            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16447            deletedPkg = false;
16448        } else {
16449            // Successfully deleted the old package; proceed with replace.
16450
16451            // If deleted package lived in a container, give users a chance to
16452            // relinquish resources before killing.
16453            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16454                if (DEBUG_INSTALL) {
16455                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16456                }
16457                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16458                final ArrayList<String> pkgList = new ArrayList<String>(1);
16459                pkgList.add(deletedPackage.applicationInfo.packageName);
16460                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16461            }
16462
16463            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16464                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16465
16466            try {
16467                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16468                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16469                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16470                        installReason);
16471
16472                // Update the in-memory copy of the previous code paths.
16473                PackageSetting ps = mSettings.mPackages.get(pkgName);
16474                if (!killApp) {
16475                    if (ps.oldCodePaths == null) {
16476                        ps.oldCodePaths = new ArraySet<>();
16477                    }
16478                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16479                    if (deletedPackage.splitCodePaths != null) {
16480                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16481                    }
16482                } else {
16483                    ps.oldCodePaths = null;
16484                }
16485                if (ps.childPackageNames != null) {
16486                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16487                        final String childPkgName = ps.childPackageNames.get(i);
16488                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16489                        childPs.oldCodePaths = ps.oldCodePaths;
16490                    }
16491                }
16492                prepareAppDataAfterInstallLIF(newPackage);
16493                addedPkg = true;
16494                mDexManager.notifyPackageUpdated(newPackage.packageName,
16495                        newPackage.baseCodePath, newPackage.splitCodePaths);
16496            } catch (PackageManagerException e) {
16497                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16498            }
16499        }
16500
16501        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16502            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16503
16504            // Revert all internal state mutations and added folders for the failed install
16505            if (addedPkg) {
16506                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16507                        res.removedInfo, true, null);
16508            }
16509
16510            // Restore the old package
16511            if (deletedPkg) {
16512                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16513                File restoreFile = new File(deletedPackage.codePath);
16514                // Parse old package
16515                boolean oldExternal = isExternal(deletedPackage);
16516                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16517                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16518                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16519                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16520                try {
16521                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16522                            null);
16523                } catch (PackageManagerException e) {
16524                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16525                            + e.getMessage());
16526                    return;
16527                }
16528
16529                synchronized (mPackages) {
16530                    // Ensure the installer package name up to date
16531                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16532
16533                    // Update permissions for restored package
16534                    mPermissionManager.updatePermissions(
16535                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16536                            mPermissionCallback);
16537
16538                    mSettings.writeLPr();
16539                }
16540
16541                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16542            }
16543        } else {
16544            synchronized (mPackages) {
16545                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16546                if (ps != null) {
16547                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16548                    if (res.removedInfo.removedChildPackages != null) {
16549                        final int childCount = res.removedInfo.removedChildPackages.size();
16550                        // Iterate in reverse as we may modify the collection
16551                        for (int i = childCount - 1; i >= 0; i--) {
16552                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16553                            if (res.addedChildPackages.containsKey(childPackageName)) {
16554                                res.removedInfo.removedChildPackages.removeAt(i);
16555                            } else {
16556                                PackageRemovedInfo childInfo = res.removedInfo
16557                                        .removedChildPackages.valueAt(i);
16558                                childInfo.removedForAllUsers = mPackages.get(
16559                                        childInfo.removedPackage) == null;
16560                            }
16561                        }
16562                    }
16563                }
16564            }
16565        }
16566    }
16567
16568    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16569            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16570            final @ScanFlags int scanFlags, UserHandle user,
16571            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16572            int installReason) {
16573        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16574                + ", old=" + deletedPackage);
16575
16576        final boolean disabledSystem;
16577
16578        // Remove existing system package
16579        removePackageLI(deletedPackage, true);
16580
16581        synchronized (mPackages) {
16582            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16583        }
16584        if (!disabledSystem) {
16585            // We didn't need to disable the .apk as a current system package,
16586            // which means we are replacing another update that is already
16587            // installed.  We need to make sure to delete the older one's .apk.
16588            res.removedInfo.args = createInstallArgsForExisting(0,
16589                    deletedPackage.applicationInfo.getCodePath(),
16590                    deletedPackage.applicationInfo.getResourcePath(),
16591                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16592        } else {
16593            res.removedInfo.args = null;
16594        }
16595
16596        // Successfully disabled the old package. Now proceed with re-installation
16597        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16598                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16599
16600        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16601        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16602                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16603
16604        PackageParser.Package newPackage = null;
16605        try {
16606            // Add the package to the internal data structures
16607            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16608
16609            // Set the update and install times
16610            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16611            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16612                    System.currentTimeMillis());
16613
16614            // Update the package dynamic state if succeeded
16615            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16616                // Now that the install succeeded make sure we remove data
16617                // directories for any child package the update removed.
16618                final int deletedChildCount = (deletedPackage.childPackages != null)
16619                        ? deletedPackage.childPackages.size() : 0;
16620                final int newChildCount = (newPackage.childPackages != null)
16621                        ? newPackage.childPackages.size() : 0;
16622                for (int i = 0; i < deletedChildCount; i++) {
16623                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16624                    boolean childPackageDeleted = true;
16625                    for (int j = 0; j < newChildCount; j++) {
16626                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16627                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16628                            childPackageDeleted = false;
16629                            break;
16630                        }
16631                    }
16632                    if (childPackageDeleted) {
16633                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16634                                deletedChildPkg.packageName);
16635                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16636                            PackageRemovedInfo removedChildRes = res.removedInfo
16637                                    .removedChildPackages.get(deletedChildPkg.packageName);
16638                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16639                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16640                        }
16641                    }
16642                }
16643
16644                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16645                        installReason);
16646                prepareAppDataAfterInstallLIF(newPackage);
16647
16648                mDexManager.notifyPackageUpdated(newPackage.packageName,
16649                            newPackage.baseCodePath, newPackage.splitCodePaths);
16650            }
16651        } catch (PackageManagerException e) {
16652            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16653            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16654        }
16655
16656        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16657            // Re installation failed. Restore old information
16658            // Remove new pkg information
16659            if (newPackage != null) {
16660                removeInstalledPackageLI(newPackage, true);
16661            }
16662            // Add back the old system package
16663            try {
16664                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16665            } catch (PackageManagerException e) {
16666                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16667            }
16668
16669            synchronized (mPackages) {
16670                if (disabledSystem) {
16671                    enableSystemPackageLPw(deletedPackage);
16672                }
16673
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 : " + deletedPackage.packageName
16686                    + " after failed upgrade");
16687        }
16688    }
16689
16690    /**
16691     * Checks whether the parent or any of the child packages have a change shared
16692     * user. For a package to be a valid update the shred users of the parent and
16693     * the children should match. We may later support changing child shared users.
16694     * @param oldPkg The updated package.
16695     * @param newPkg The update package.
16696     * @return The shared user that change between the versions.
16697     */
16698    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16699            PackageParser.Package newPkg) {
16700        // Check parent shared user
16701        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16702            return newPkg.packageName;
16703        }
16704        // Check child shared users
16705        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16706        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16707        for (int i = 0; i < newChildCount; i++) {
16708            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16709            // If this child was present, did it have the same shared user?
16710            for (int j = 0; j < oldChildCount; j++) {
16711                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16712                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16713                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16714                    return newChildPkg.packageName;
16715                }
16716            }
16717        }
16718        return null;
16719    }
16720
16721    private void removeNativeBinariesLI(PackageSetting ps) {
16722        // Remove the lib path for the parent package
16723        if (ps != null) {
16724            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16725            // Remove the lib path for the child packages
16726            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16727            for (int i = 0; i < childCount; i++) {
16728                PackageSetting childPs = null;
16729                synchronized (mPackages) {
16730                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16731                }
16732                if (childPs != null) {
16733                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16734                            .legacyNativeLibraryPathString);
16735                }
16736            }
16737        }
16738    }
16739
16740    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16741        // Enable the parent package
16742        mSettings.enableSystemPackageLPw(pkg.packageName);
16743        // Enable the child packages
16744        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16745        for (int i = 0; i < childCount; i++) {
16746            PackageParser.Package childPkg = pkg.childPackages.get(i);
16747            mSettings.enableSystemPackageLPw(childPkg.packageName);
16748        }
16749    }
16750
16751    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16752            PackageParser.Package newPkg) {
16753        // Disable the parent package (parent always replaced)
16754        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16755        // Disable the child packages
16756        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16757        for (int i = 0; i < childCount; i++) {
16758            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16759            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16760            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16761        }
16762        return disabled;
16763    }
16764
16765    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16766            String installerPackageName) {
16767        // Enable the parent package
16768        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16769        // Enable the child packages
16770        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16771        for (int i = 0; i < childCount; i++) {
16772            PackageParser.Package childPkg = pkg.childPackages.get(i);
16773            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16774        }
16775    }
16776
16777    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16778            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16779        // Update the parent package setting
16780        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16781                res, user, installReason);
16782        // Update the child packages setting
16783        final int childCount = (newPackage.childPackages != null)
16784                ? newPackage.childPackages.size() : 0;
16785        for (int i = 0; i < childCount; i++) {
16786            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16787            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16788            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16789                    childRes.origUsers, childRes, user, installReason);
16790        }
16791    }
16792
16793    private void updateSettingsInternalLI(PackageParser.Package pkg,
16794            String installerPackageName, int[] allUsers, int[] installedForUsers,
16795            PackageInstalledInfo res, UserHandle user, int installReason) {
16796        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16797
16798        final String pkgName = pkg.packageName;
16799
16800        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16801        synchronized (mPackages) {
16802// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16803            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16804                    mPermissionCallback);
16805            // For system-bundled packages, we assume that installing an upgraded version
16806            // of the package implies that the user actually wants to run that new code,
16807            // so we enable the package.
16808            PackageSetting ps = mSettings.mPackages.get(pkgName);
16809            final int userId = user.getIdentifier();
16810            if (ps != null) {
16811                if (isSystemApp(pkg)) {
16812                    if (DEBUG_INSTALL) {
16813                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16814                    }
16815                    // Enable system package for requested users
16816                    if (res.origUsers != null) {
16817                        for (int origUserId : res.origUsers) {
16818                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16819                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16820                                        origUserId, installerPackageName);
16821                            }
16822                        }
16823                    }
16824                    // Also convey the prior install/uninstall state
16825                    if (allUsers != null && installedForUsers != null) {
16826                        for (int currentUserId : allUsers) {
16827                            final boolean installed = ArrayUtils.contains(
16828                                    installedForUsers, currentUserId);
16829                            if (DEBUG_INSTALL) {
16830                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16831                            }
16832                            ps.setInstalled(installed, currentUserId);
16833                        }
16834                        // these install state changes will be persisted in the
16835                        // upcoming call to mSettings.writeLPr().
16836                    }
16837                }
16838                // It's implied that when a user requests installation, they want the app to be
16839                // installed and enabled.
16840                if (userId != UserHandle.USER_ALL) {
16841                    ps.setInstalled(true, userId);
16842                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16843                }
16844
16845                // When replacing an existing package, preserve the original install reason for all
16846                // users that had the package installed before.
16847                final Set<Integer> previousUserIds = new ArraySet<>();
16848                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16849                    final int installReasonCount = res.removedInfo.installReasons.size();
16850                    for (int i = 0; i < installReasonCount; i++) {
16851                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16852                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16853                        ps.setInstallReason(previousInstallReason, previousUserId);
16854                        previousUserIds.add(previousUserId);
16855                    }
16856                }
16857
16858                // Set install reason for users that are having the package newly installed.
16859                if (userId == UserHandle.USER_ALL) {
16860                    for (int currentUserId : sUserManager.getUserIds()) {
16861                        if (!previousUserIds.contains(currentUserId)) {
16862                            ps.setInstallReason(installReason, currentUserId);
16863                        }
16864                    }
16865                } else if (!previousUserIds.contains(userId)) {
16866                    ps.setInstallReason(installReason, userId);
16867                }
16868                mSettings.writeKernelMappingLPr(ps);
16869            }
16870            res.name = pkgName;
16871            res.uid = pkg.applicationInfo.uid;
16872            res.pkg = pkg;
16873            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16874            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16875            //to update install status
16876            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16877            mSettings.writeLPr();
16878            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16879        }
16880
16881        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16882    }
16883
16884    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16885        try {
16886            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16887            installPackageLI(args, res);
16888        } finally {
16889            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16890        }
16891    }
16892
16893    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16894        final int installFlags = args.installFlags;
16895        final String installerPackageName = args.installerPackageName;
16896        final String volumeUuid = args.volumeUuid;
16897        final File tmpPackageFile = new File(args.getCodePath());
16898        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16899        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16900                || (args.volumeUuid != null));
16901        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16902        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16903        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16904        final boolean virtualPreload =
16905                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16906        boolean replace = false;
16907        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16908        if (args.move != null) {
16909            // moving a complete application; perform an initial scan on the new install location
16910            scanFlags |= SCAN_INITIAL;
16911        }
16912        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16913            scanFlags |= SCAN_DONT_KILL_APP;
16914        }
16915        if (instantApp) {
16916            scanFlags |= SCAN_AS_INSTANT_APP;
16917        }
16918        if (fullApp) {
16919            scanFlags |= SCAN_AS_FULL_APP;
16920        }
16921        if (virtualPreload) {
16922            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16923        }
16924
16925        // Result object to be returned
16926        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16927        res.installerPackageName = installerPackageName;
16928
16929        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16930
16931        // Sanity check
16932        if (instantApp && (forwardLocked || onExternal)) {
16933            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16934                    + " external=" + onExternal);
16935            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16936            return;
16937        }
16938
16939        // Retrieve PackageSettings and parse package
16940        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16941                | PackageParser.PARSE_ENFORCE_CODE
16942                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16943                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16944                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16945        PackageParser pp = new PackageParser();
16946        pp.setSeparateProcesses(mSeparateProcesses);
16947        pp.setDisplayMetrics(mMetrics);
16948        pp.setCallback(mPackageParserCallback);
16949
16950        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16951        final PackageParser.Package pkg;
16952        try {
16953            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16954            DexMetadataHelper.validatePackageDexMetadata(pkg);
16955        } catch (PackageParserException e) {
16956            res.setError("Failed parse during installPackageLI", e);
16957            return;
16958        } finally {
16959            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16960        }
16961
16962        // Instant apps have several additional install-time checks.
16963        if (instantApp) {
16964            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16965                Slog.w(TAG,
16966                        "Instant app package " + pkg.packageName + " does not target at least O");
16967                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16968                        "Instant app package must target at least O");
16969                return;
16970            }
16971            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16972                Slog.w(TAG, "Instant app package " + pkg.packageName
16973                        + " does not target targetSandboxVersion 2");
16974                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16975                        "Instant app package must use targetSandboxVersion 2");
16976                return;
16977            }
16978            if (pkg.mSharedUserId != null) {
16979                Slog.w(TAG, "Instant app package " + pkg.packageName
16980                        + " may not declare sharedUserId.");
16981                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16982                        "Instant app package may not declare a sharedUserId");
16983                return;
16984            }
16985        }
16986
16987        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16988            // Static shared libraries have synthetic package names
16989            renameStaticSharedLibraryPackage(pkg);
16990
16991            // No static shared libs on external storage
16992            if (onExternal) {
16993                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16994                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16995                        "Packages declaring static-shared libs cannot be updated");
16996                return;
16997            }
16998        }
16999
17000        // If we are installing a clustered package add results for the children
17001        if (pkg.childPackages != null) {
17002            synchronized (mPackages) {
17003                final int childCount = pkg.childPackages.size();
17004                for (int i = 0; i < childCount; i++) {
17005                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17006                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17007                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17008                    childRes.pkg = childPkg;
17009                    childRes.name = childPkg.packageName;
17010                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17011                    if (childPs != null) {
17012                        childRes.origUsers = childPs.queryInstalledUsers(
17013                                sUserManager.getUserIds(), true);
17014                    }
17015                    if ((mPackages.containsKey(childPkg.packageName))) {
17016                        childRes.removedInfo = new PackageRemovedInfo(this);
17017                        childRes.removedInfo.removedPackage = childPkg.packageName;
17018                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17019                    }
17020                    if (res.addedChildPackages == null) {
17021                        res.addedChildPackages = new ArrayMap<>();
17022                    }
17023                    res.addedChildPackages.put(childPkg.packageName, childRes);
17024                }
17025            }
17026        }
17027
17028        // If package doesn't declare API override, mark that we have an install
17029        // time CPU ABI override.
17030        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17031            pkg.cpuAbiOverride = args.abiOverride;
17032        }
17033
17034        String pkgName = res.name = pkg.packageName;
17035        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17036            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17037                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17038                return;
17039            }
17040        }
17041
17042        try {
17043            // either use what we've been given or parse directly from the APK
17044            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
17045                pkg.setSigningDetails(args.signingDetails);
17046            } else {
17047                PackageParser.collectCertificates(pkg, false /* skipVerify */);
17048            }
17049        } catch (PackageParserException e) {
17050            res.setError("Failed collect during installPackageLI", e);
17051            return;
17052        }
17053
17054        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
17055                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
17056            Slog.w(TAG, "Instant app package " + pkg.packageName
17057                    + " is not signed with at least APK Signature Scheme v2");
17058            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17059                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
17060            return;
17061        }
17062
17063        // Get rid of all references to package scan path via parser.
17064        pp = null;
17065        String oldCodePath = null;
17066        boolean systemApp = false;
17067        synchronized (mPackages) {
17068            // Check if installing already existing package
17069            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17070                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17071                if (pkg.mOriginalPackages != null
17072                        && pkg.mOriginalPackages.contains(oldName)
17073                        && mPackages.containsKey(oldName)) {
17074                    // This package is derived from an original package,
17075                    // and this device has been updating from that original
17076                    // name.  We must continue using the original name, so
17077                    // rename the new package here.
17078                    pkg.setPackageName(oldName);
17079                    pkgName = pkg.packageName;
17080                    replace = true;
17081                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17082                            + oldName + " pkgName=" + pkgName);
17083                } else if (mPackages.containsKey(pkgName)) {
17084                    // This package, under its official name, already exists
17085                    // on the device; we should replace it.
17086                    replace = true;
17087                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17088                }
17089
17090                // Child packages are installed through the parent package
17091                if (pkg.parentPackage != null) {
17092                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17093                            "Package " + pkg.packageName + " is child of package "
17094                                    + pkg.parentPackage.parentPackage + ". Child packages "
17095                                    + "can be updated only through the parent package.");
17096                    return;
17097                }
17098
17099                if (replace) {
17100                    // Prevent apps opting out from runtime permissions
17101                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17102                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17103                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17104                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17105                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17106                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17107                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17108                                        + " doesn't support runtime permissions but the old"
17109                                        + " target SDK " + oldTargetSdk + " does.");
17110                        return;
17111                    }
17112                    // Prevent persistent apps from being updated
17113                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
17114                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
17115                                "Package " + oldPackage.packageName + " is a persistent app. "
17116                                        + "Persistent apps are not updateable.");
17117                        return;
17118                    }
17119                    // Prevent apps from downgrading their targetSandbox.
17120                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17121                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17122                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17123                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17124                                "Package " + pkg.packageName + " new target sandbox "
17125                                + newTargetSandbox + " is incompatible with the previous value of"
17126                                + oldTargetSandbox + ".");
17127                        return;
17128                    }
17129
17130                    // Prevent installing of child packages
17131                    if (oldPackage.parentPackage != null) {
17132                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17133                                "Package " + pkg.packageName + " is child of package "
17134                                        + oldPackage.parentPackage + ". Child packages "
17135                                        + "can be updated only through the parent package.");
17136                        return;
17137                    }
17138                }
17139            }
17140
17141            PackageSetting ps = mSettings.mPackages.get(pkgName);
17142            if (ps != null) {
17143                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17144
17145                // Static shared libs have same package with different versions where
17146                // we internally use a synthetic package name to allow multiple versions
17147                // of the same package, therefore we need to compare signatures against
17148                // the package setting for the latest library version.
17149                PackageSetting signatureCheckPs = ps;
17150                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17151                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17152                    if (libraryEntry != null) {
17153                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17154                    }
17155                }
17156
17157                // Quick sanity check that we're signed correctly if updating;
17158                // we'll check this again later when scanning, but we want to
17159                // bail early here before tripping over redefined permissions.
17160                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17161                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
17162                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
17163                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17164                                + pkg.packageName + " upgrade keys do not match the "
17165                                + "previously installed version");
17166                        return;
17167                    }
17168                } else {
17169                    try {
17170                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
17171                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
17172                        // We don't care about disabledPkgSetting on install for now.
17173                        final boolean compatMatch = verifySignatures(
17174                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
17175                                compareRecover);
17176                        // The new KeySets will be re-added later in the scanning process.
17177                        if (compatMatch) {
17178                            synchronized (mPackages) {
17179                                ksms.removeAppKeySetDataLPw(pkg.packageName);
17180                            }
17181                        }
17182                    } catch (PackageManagerException e) {
17183                        res.setError(e.error, e.getMessage());
17184                        return;
17185                    }
17186                }
17187
17188                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17189                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17190                    systemApp = (ps.pkg.applicationInfo.flags &
17191                            ApplicationInfo.FLAG_SYSTEM) != 0;
17192                }
17193                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17194            }
17195
17196            int N = pkg.permissions.size();
17197            for (int i = N-1; i >= 0; i--) {
17198                final PackageParser.Permission perm = pkg.permissions.get(i);
17199                final BasePermission bp =
17200                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17201
17202                // Don't allow anyone but the system to define ephemeral permissions.
17203                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17204                        && !systemApp) {
17205                    Slog.w(TAG, "Non-System package " + pkg.packageName
17206                            + " attempting to delcare ephemeral permission "
17207                            + perm.info.name + "; Removing ephemeral.");
17208                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17209                }
17210
17211                // Check whether the newly-scanned package wants to define an already-defined perm
17212                if (bp != null) {
17213                    // If the defining package is signed with our cert, it's okay.  This
17214                    // also includes the "updating the same package" case, of course.
17215                    // "updating same package" could also involve key-rotation.
17216                    final boolean sigsOk;
17217                    final String sourcePackageName = bp.getSourcePackageName();
17218                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17219                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17220                    if (sourcePackageName.equals(pkg.packageName)
17221                            && (ksms.shouldCheckUpgradeKeySetLocked(
17222                                    sourcePackageSetting, scanFlags))) {
17223                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17224                    } else {
17225
17226                        // in the event of signing certificate rotation, we need to see if the
17227                        // package's certificate has rotated from the current one, or if it is an
17228                        // older certificate with which the current is ok with sharing permissions
17229                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17230                                        pkg.mSigningDetails,
17231                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17232                            sigsOk = true;
17233                        } else if (pkg.mSigningDetails.checkCapability(
17234                                        sourcePackageSetting.signatures.mSigningDetails,
17235                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17236
17237                            // the scanned package checks out, has signing certificate rotation
17238                            // history, and is newer; bring it over
17239                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17240                            sigsOk = true;
17241                        } else {
17242                            sigsOk = false;
17243                        }
17244                    }
17245                    if (!sigsOk) {
17246                        // If the owning package is the system itself, we log but allow
17247                        // install to proceed; we fail the install on all other permission
17248                        // redefinitions.
17249                        if (!sourcePackageName.equals("android")) {
17250                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17251                                    + pkg.packageName + " attempting to redeclare permission "
17252                                    + perm.info.name + " already owned by " + sourcePackageName);
17253                            res.origPermission = perm.info.name;
17254                            res.origPackage = sourcePackageName;
17255                            return;
17256                        } else {
17257                            Slog.w(TAG, "Package " + pkg.packageName
17258                                    + " attempting to redeclare system permission "
17259                                    + perm.info.name + "; ignoring new declaration");
17260                            pkg.permissions.remove(i);
17261                        }
17262                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17263                        // Prevent apps to change protection level to dangerous from any other
17264                        // type as this would allow a privilege escalation where an app adds a
17265                        // normal/signature permission in other app's group and later redefines
17266                        // it as dangerous leading to the group auto-grant.
17267                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17268                                == PermissionInfo.PROTECTION_DANGEROUS) {
17269                            if (bp != null && !bp.isRuntime()) {
17270                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17271                                        + "non-runtime permission " + perm.info.name
17272                                        + " to runtime; keeping old protection level");
17273                                perm.info.protectionLevel = bp.getProtectionLevel();
17274                            }
17275                        }
17276                    }
17277                }
17278            }
17279        }
17280
17281        if (systemApp) {
17282            if (onExternal) {
17283                // Abort update; system app can't be replaced with app on sdcard
17284                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17285                        "Cannot install updates to system apps on sdcard");
17286                return;
17287            } else if (instantApp) {
17288                // Abort update; system app can't be replaced with an instant app
17289                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17290                        "Cannot update a system app with an instant app");
17291                return;
17292            }
17293        }
17294
17295        if (args.move != null) {
17296            // We did an in-place move, so dex is ready to roll
17297            scanFlags |= SCAN_NO_DEX;
17298            scanFlags |= SCAN_MOVE;
17299
17300            synchronized (mPackages) {
17301                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17302                if (ps == null) {
17303                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17304                            "Missing settings for moved package " + pkgName);
17305                }
17306
17307                // We moved the entire application as-is, so bring over the
17308                // previously derived ABI information.
17309                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17310                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17311            }
17312
17313        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17314            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17315            scanFlags |= SCAN_NO_DEX;
17316
17317            try {
17318                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17319                    args.abiOverride : pkg.cpuAbiOverride);
17320                final boolean extractNativeLibs = !pkg.isLibrary();
17321                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17322            } catch (PackageManagerException pme) {
17323                Slog.e(TAG, "Error deriving application ABI", pme);
17324                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17325                return;
17326            }
17327
17328            // Shared libraries for the package need to be updated.
17329            synchronized (mPackages) {
17330                try {
17331                    updateSharedLibrariesLPr(pkg, null);
17332                } catch (PackageManagerException e) {
17333                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17334                }
17335            }
17336        }
17337
17338        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17339            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17340            return;
17341        }
17342
17343        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17344            String apkPath = null;
17345            synchronized (mPackages) {
17346                // Note that if the attacker managed to skip verify setup, for example by tampering
17347                // with the package settings, upon reboot we will do full apk verification when
17348                // verity is not detected.
17349                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17350                if (ps != null && ps.isPrivileged()) {
17351                    apkPath = pkg.baseCodePath;
17352                }
17353            }
17354
17355            if (apkPath != null) {
17356                final VerityUtils.SetupResult result =
17357                        VerityUtils.generateApkVeritySetupData(apkPath);
17358                if (result.isOk()) {
17359                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17360                    FileDescriptor fd = result.getUnownedFileDescriptor();
17361                    try {
17362                        final byte[] signedRootHash = VerityUtils.generateFsverityRootHash(apkPath);
17363                        mInstaller.installApkVerity(apkPath, fd, result.getContentSize());
17364                        mInstaller.assertFsverityRootHashMatches(apkPath, signedRootHash);
17365                    } catch (InstallerException | IOException | DigestException |
17366                             NoSuchAlgorithmException e) {
17367                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17368                                "Failed to set up verity: " + e);
17369                        return;
17370                    } finally {
17371                        IoUtils.closeQuietly(fd);
17372                    }
17373                } else if (result.isFailed()) {
17374                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17375                    return;
17376                } else {
17377                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17378                    // reboot.
17379                }
17380            }
17381        }
17382
17383        if (!instantApp) {
17384            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17385        } else {
17386            if (DEBUG_DOMAIN_VERIFICATION) {
17387                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17388            }
17389        }
17390
17391        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17392                "installPackageLI")) {
17393            if (replace) {
17394                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17395                    // Static libs have a synthetic package name containing the version
17396                    // and cannot be updated as an update would get a new package name,
17397                    // unless this is the exact same version code which is useful for
17398                    // development.
17399                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17400                    if (existingPkg != null &&
17401                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17402                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17403                                + "static-shared libs cannot be updated");
17404                        return;
17405                    }
17406                }
17407                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17408                        installerPackageName, res, args.installReason);
17409            } else {
17410                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17411                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17412            }
17413        }
17414
17415        // Prepare the application profiles for the new code paths.
17416        // This needs to be done before invoking dexopt so that any install-time profile
17417        // can be used for optimizations.
17418        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17419
17420        // Check whether we need to dexopt the app.
17421        //
17422        // NOTE: it is IMPORTANT to call dexopt:
17423        //   - after doRename which will sync the package data from PackageParser.Package and its
17424        //     corresponding ApplicationInfo.
17425        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17426        //     uid of the application (pkg.applicationInfo.uid).
17427        //     This update happens in place!
17428        //
17429        // We only need to dexopt if the package meets ALL of the following conditions:
17430        //   1) it is not forward locked.
17431        //   2) it is not on on an external ASEC container.
17432        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17433        //
17434        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17435        // complete, so we skip this step during installation. Instead, we'll take extra time
17436        // the first time the instant app starts. It's preferred to do it this way to provide
17437        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17438        // middle of running an instant app. The default behaviour can be overridden
17439        // via gservices.
17440        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17441                && !forwardLocked
17442                && !pkg.applicationInfo.isExternalAsec()
17443                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17444                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17445
17446        if (performDexopt) {
17447            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17448            // Do not run PackageDexOptimizer through the local performDexOpt
17449            // method because `pkg` may not be in `mPackages` yet.
17450            //
17451            // Also, don't fail application installs if the dexopt step fails.
17452            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17453                    REASON_INSTALL,
17454                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17455                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17456            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17457                    null /* instructionSets */,
17458                    getOrCreateCompilerPackageStats(pkg),
17459                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17460                    dexoptOptions);
17461            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17462        }
17463
17464        // Notify BackgroundDexOptService that the package has been changed.
17465        // If this is an update of a package which used to fail to compile,
17466        // BackgroundDexOptService will remove it from its blacklist.
17467        // TODO: Layering violation
17468        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17469
17470        synchronized (mPackages) {
17471            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17472            if (ps != null) {
17473                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17474                ps.setUpdateAvailable(false /*updateAvailable*/);
17475            }
17476
17477            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17478            for (int i = 0; i < childCount; i++) {
17479                PackageParser.Package childPkg = pkg.childPackages.get(i);
17480                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17481                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17482                if (childPs != null) {
17483                    childRes.newUsers = childPs.queryInstalledUsers(
17484                            sUserManager.getUserIds(), true);
17485                }
17486            }
17487
17488            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17489                updateSequenceNumberLP(ps, res.newUsers);
17490                updateInstantAppInstallerLocked(pkgName);
17491            }
17492        }
17493    }
17494
17495    private void startIntentFilterVerifications(int userId, boolean replacing,
17496            PackageParser.Package pkg) {
17497        if (mIntentFilterVerifierComponent == null) {
17498            Slog.w(TAG, "No IntentFilter verification will not be done as "
17499                    + "there is no IntentFilterVerifier available!");
17500            return;
17501        }
17502
17503        final int verifierUid = getPackageUid(
17504                mIntentFilterVerifierComponent.getPackageName(),
17505                MATCH_DEBUG_TRIAGED_MISSING,
17506                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17507
17508        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17509        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17510        mHandler.sendMessage(msg);
17511
17512        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17513        for (int i = 0; i < childCount; i++) {
17514            PackageParser.Package childPkg = pkg.childPackages.get(i);
17515            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17516            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17517            mHandler.sendMessage(msg);
17518        }
17519    }
17520
17521    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17522            PackageParser.Package pkg) {
17523        int size = pkg.activities.size();
17524        if (size == 0) {
17525            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17526                    "No activity, so no need to verify any IntentFilter!");
17527            return;
17528        }
17529
17530        final boolean hasDomainURLs = hasDomainURLs(pkg);
17531        if (!hasDomainURLs) {
17532            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17533                    "No domain URLs, so no need to verify any IntentFilter!");
17534            return;
17535        }
17536
17537        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17538                + " if any IntentFilter from the " + size
17539                + " Activities needs verification ...");
17540
17541        int count = 0;
17542        final String packageName = pkg.packageName;
17543
17544        synchronized (mPackages) {
17545            // If this is a new install and we see that we've already run verification for this
17546            // package, we have nothing to do: it means the state was restored from backup.
17547            if (!replacing) {
17548                IntentFilterVerificationInfo ivi =
17549                        mSettings.getIntentFilterVerificationLPr(packageName);
17550                if (ivi != null) {
17551                    if (DEBUG_DOMAIN_VERIFICATION) {
17552                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17553                                + ivi.getStatusString());
17554                    }
17555                    return;
17556                }
17557            }
17558
17559            // If any filters need to be verified, then all need to be.
17560            boolean needToVerify = false;
17561            for (PackageParser.Activity a : pkg.activities) {
17562                for (ActivityIntentInfo filter : a.intents) {
17563                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17564                        if (DEBUG_DOMAIN_VERIFICATION) {
17565                            Slog.d(TAG,
17566                                    "Intent filter needs verification, so processing all filters");
17567                        }
17568                        needToVerify = true;
17569                        break;
17570                    }
17571                }
17572            }
17573
17574            if (needToVerify) {
17575                final int verificationId = mIntentFilterVerificationToken++;
17576                for (PackageParser.Activity a : pkg.activities) {
17577                    for (ActivityIntentInfo filter : a.intents) {
17578                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17579                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17580                                    "Verification needed for IntentFilter:" + filter.toString());
17581                            mIntentFilterVerifier.addOneIntentFilterVerification(
17582                                    verifierUid, userId, verificationId, filter, packageName);
17583                            count++;
17584                        }
17585                    }
17586                }
17587            }
17588        }
17589
17590        if (count > 0) {
17591            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17592                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17593                    +  " for userId:" + userId);
17594            mIntentFilterVerifier.startVerifications(userId);
17595        } else {
17596            if (DEBUG_DOMAIN_VERIFICATION) {
17597                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17598            }
17599        }
17600    }
17601
17602    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17603        final ComponentName cn  = filter.activity.getComponentName();
17604        final String packageName = cn.getPackageName();
17605
17606        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17607                packageName);
17608        if (ivi == null) {
17609            return true;
17610        }
17611        int status = ivi.getStatus();
17612        switch (status) {
17613            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17614            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17615                return true;
17616
17617            default:
17618                // Nothing to do
17619                return false;
17620        }
17621    }
17622
17623    private static boolean isMultiArch(ApplicationInfo info) {
17624        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17625    }
17626
17627    private static boolean isExternal(PackageParser.Package pkg) {
17628        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17629    }
17630
17631    private static boolean isExternal(PackageSetting ps) {
17632        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17633    }
17634
17635    private static boolean isSystemApp(PackageParser.Package pkg) {
17636        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17637    }
17638
17639    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17640        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17641    }
17642
17643    private static boolean isOemApp(PackageParser.Package pkg) {
17644        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17645    }
17646
17647    private static boolean isVendorApp(PackageParser.Package pkg) {
17648        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17649    }
17650
17651    private static boolean isProductApp(PackageParser.Package pkg) {
17652        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17653    }
17654
17655    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17656        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17657    }
17658
17659    private static boolean isSystemApp(PackageSetting ps) {
17660        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17661    }
17662
17663    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17664        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17665    }
17666
17667    private int packageFlagsToInstallFlags(PackageSetting ps) {
17668        int installFlags = 0;
17669        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17670            // This existing package was an external ASEC install when we have
17671            // the external flag without a UUID
17672            installFlags |= PackageManager.INSTALL_EXTERNAL;
17673        }
17674        if (ps.isForwardLocked()) {
17675            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17676        }
17677        return installFlags;
17678    }
17679
17680    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17681        if (isExternal(pkg)) {
17682            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17683                return mSettings.getExternalVersion();
17684            } else {
17685                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17686            }
17687        } else {
17688            return mSettings.getInternalVersion();
17689        }
17690    }
17691
17692    private void deleteTempPackageFiles() {
17693        final FilenameFilter filter = new FilenameFilter() {
17694            public boolean accept(File dir, String name) {
17695                return name.startsWith("vmdl") && name.endsWith(".tmp");
17696            }
17697        };
17698        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17699            file.delete();
17700        }
17701    }
17702
17703    @Override
17704    public void deletePackageAsUser(String packageName, int versionCode,
17705            IPackageDeleteObserver observer, int userId, int flags) {
17706        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17707                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17708    }
17709
17710    @Override
17711    public void deletePackageVersioned(VersionedPackage versionedPackage,
17712            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17713        final int callingUid = Binder.getCallingUid();
17714        mContext.enforceCallingOrSelfPermission(
17715                android.Manifest.permission.DELETE_PACKAGES, null);
17716        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17717        Preconditions.checkNotNull(versionedPackage);
17718        Preconditions.checkNotNull(observer);
17719        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17720                PackageManager.VERSION_CODE_HIGHEST,
17721                Long.MAX_VALUE, "versionCode must be >= -1");
17722
17723        final String packageName = versionedPackage.getPackageName();
17724        final long versionCode = versionedPackage.getLongVersionCode();
17725        final String internalPackageName;
17726        synchronized (mPackages) {
17727            // Normalize package name to handle renamed packages and static libs
17728            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17729        }
17730
17731        final int uid = Binder.getCallingUid();
17732        if (!isOrphaned(internalPackageName)
17733                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17734            try {
17735                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17736                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17737                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17738                observer.onUserActionRequired(intent);
17739            } catch (RemoteException re) {
17740            }
17741            return;
17742        }
17743        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17744        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17745        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17746            mContext.enforceCallingOrSelfPermission(
17747                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17748                    "deletePackage for user " + userId);
17749        }
17750
17751        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17752            try {
17753                observer.onPackageDeleted(packageName,
17754                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17755            } catch (RemoteException re) {
17756            }
17757            return;
17758        }
17759
17760        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17761            try {
17762                observer.onPackageDeleted(packageName,
17763                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17764            } catch (RemoteException re) {
17765            }
17766            return;
17767        }
17768
17769        if (DEBUG_REMOVE) {
17770            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17771                    + " deleteAllUsers: " + deleteAllUsers + " version="
17772                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17773                    ? "VERSION_CODE_HIGHEST" : versionCode));
17774        }
17775        // Queue up an async operation since the package deletion may take a little while.
17776        mHandler.post(new Runnable() {
17777            public void run() {
17778                mHandler.removeCallbacks(this);
17779                int returnCode;
17780                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17781                boolean doDeletePackage = true;
17782                if (ps != null) {
17783                    final boolean targetIsInstantApp =
17784                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17785                    doDeletePackage = !targetIsInstantApp
17786                            || canViewInstantApps;
17787                }
17788                if (doDeletePackage) {
17789                    if (!deleteAllUsers) {
17790                        returnCode = deletePackageX(internalPackageName, versionCode,
17791                                userId, deleteFlags);
17792                    } else {
17793                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17794                                internalPackageName, users);
17795                        // If nobody is blocking uninstall, proceed with delete for all users
17796                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17797                            returnCode = deletePackageX(internalPackageName, versionCode,
17798                                    userId, deleteFlags);
17799                        } else {
17800                            // Otherwise uninstall individually for users with blockUninstalls=false
17801                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17802                            for (int userId : users) {
17803                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17804                                    returnCode = deletePackageX(internalPackageName, versionCode,
17805                                            userId, userFlags);
17806                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17807                                        Slog.w(TAG, "Package delete failed for user " + userId
17808                                                + ", returnCode " + returnCode);
17809                                    }
17810                                }
17811                            }
17812                            // The app has only been marked uninstalled for certain users.
17813                            // We still need to report that delete was blocked
17814                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17815                        }
17816                    }
17817                } else {
17818                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17819                }
17820                try {
17821                    observer.onPackageDeleted(packageName, returnCode, null);
17822                } catch (RemoteException e) {
17823                    Log.i(TAG, "Observer no longer exists.");
17824                } //end catch
17825            } //end run
17826        });
17827    }
17828
17829    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17830        if (pkg.staticSharedLibName != null) {
17831            return pkg.manifestPackageName;
17832        }
17833        return pkg.packageName;
17834    }
17835
17836    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17837        // Handle renamed packages
17838        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17839        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17840
17841        // Is this a static library?
17842        LongSparseArray<SharedLibraryEntry> versionedLib =
17843                mStaticLibsByDeclaringPackage.get(packageName);
17844        if (versionedLib == null || versionedLib.size() <= 0) {
17845            return packageName;
17846        }
17847
17848        // Figure out which lib versions the caller can see
17849        LongSparseLongArray versionsCallerCanSee = null;
17850        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17851        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17852                && callingAppId != Process.ROOT_UID) {
17853            versionsCallerCanSee = new LongSparseLongArray();
17854            String libName = versionedLib.valueAt(0).info.getName();
17855            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17856            if (uidPackages != null) {
17857                for (String uidPackage : uidPackages) {
17858                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17859                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17860                    if (libIdx >= 0) {
17861                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17862                        versionsCallerCanSee.append(libVersion, libVersion);
17863                    }
17864                }
17865            }
17866        }
17867
17868        // Caller can see nothing - done
17869        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17870            return packageName;
17871        }
17872
17873        // Find the version the caller can see and the app version code
17874        SharedLibraryEntry highestVersion = null;
17875        final int versionCount = versionedLib.size();
17876        for (int i = 0; i < versionCount; i++) {
17877            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17878            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17879                    libEntry.info.getLongVersion()) < 0) {
17880                continue;
17881            }
17882            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17883            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17884                if (libVersionCode == versionCode) {
17885                    return libEntry.apk;
17886                }
17887            } else if (highestVersion == null) {
17888                highestVersion = libEntry;
17889            } else if (libVersionCode  > highestVersion.info
17890                    .getDeclaringPackage().getLongVersionCode()) {
17891                highestVersion = libEntry;
17892            }
17893        }
17894
17895        if (highestVersion != null) {
17896            return highestVersion.apk;
17897        }
17898
17899        return packageName;
17900    }
17901
17902    boolean isCallerVerifier(int callingUid) {
17903        final int callingUserId = UserHandle.getUserId(callingUid);
17904        return mRequiredVerifierPackage != null &&
17905                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17906    }
17907
17908    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17909        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17910              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17911            return true;
17912        }
17913        final int callingUserId = UserHandle.getUserId(callingUid);
17914        // If the caller installed the pkgName, then allow it to silently uninstall.
17915        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17916            return true;
17917        }
17918
17919        // Allow package verifier to silently uninstall.
17920        if (mRequiredVerifierPackage != null &&
17921                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17922            return true;
17923        }
17924
17925        // Allow package uninstaller to silently uninstall.
17926        if (mRequiredUninstallerPackage != null &&
17927                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17928            return true;
17929        }
17930
17931        // Allow storage manager to silently uninstall.
17932        if (mStorageManagerPackage != null &&
17933                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17934            return true;
17935        }
17936
17937        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17938        // uninstall for device owner provisioning.
17939        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17940                == PERMISSION_GRANTED) {
17941            return true;
17942        }
17943
17944        return false;
17945    }
17946
17947    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17948        int[] result = EMPTY_INT_ARRAY;
17949        for (int userId : userIds) {
17950            if (getBlockUninstallForUser(packageName, userId)) {
17951                result = ArrayUtils.appendInt(result, userId);
17952            }
17953        }
17954        return result;
17955    }
17956
17957    @Override
17958    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17959        final int callingUid = Binder.getCallingUid();
17960        if (getInstantAppPackageName(callingUid) != null
17961                && !isCallerSameApp(packageName, callingUid)) {
17962            return false;
17963        }
17964        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17965    }
17966
17967    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17968        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17969                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17970        try {
17971            if (dpm != null) {
17972                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17973                        /* callingUserOnly =*/ false);
17974                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17975                        : deviceOwnerComponentName.getPackageName();
17976                // Does the package contains the device owner?
17977                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17978                // this check is probably not needed, since DO should be registered as a device
17979                // admin on some user too. (Original bug for this: b/17657954)
17980                if (packageName.equals(deviceOwnerPackageName)) {
17981                    return true;
17982                }
17983                // Does it contain a device admin for any user?
17984                int[] users;
17985                if (userId == UserHandle.USER_ALL) {
17986                    users = sUserManager.getUserIds();
17987                } else {
17988                    users = new int[]{userId};
17989                }
17990                for (int i = 0; i < users.length; ++i) {
17991                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17992                        return true;
17993                    }
17994                }
17995            }
17996        } catch (RemoteException e) {
17997        }
17998        return false;
17999    }
18000
18001    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18002        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18003    }
18004
18005    /**
18006     *  This method is an internal method that could be get invoked either
18007     *  to delete an installed package or to clean up a failed installation.
18008     *  After deleting an installed package, a broadcast is sent to notify any
18009     *  listeners that the package has been removed. For cleaning up a failed
18010     *  installation, the broadcast is not necessary since the package's
18011     *  installation wouldn't have sent the initial broadcast either
18012     *  The key steps in deleting a package are
18013     *  deleting the package information in internal structures like mPackages,
18014     *  deleting the packages base directories through installd
18015     *  updating mSettings to reflect current status
18016     *  persisting settings for later use
18017     *  sending a broadcast if necessary
18018     */
18019    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
18020        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18021        final boolean res;
18022
18023        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18024                ? UserHandle.USER_ALL : userId;
18025
18026        if (isPackageDeviceAdmin(packageName, removeUser)) {
18027            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18028            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18029        }
18030
18031        PackageSetting uninstalledPs = null;
18032        PackageParser.Package pkg = null;
18033
18034        // for the uninstall-updates case and restricted profiles, remember the per-
18035        // user handle installed state
18036        int[] allUsers;
18037        synchronized (mPackages) {
18038            uninstalledPs = mSettings.mPackages.get(packageName);
18039            if (uninstalledPs == null) {
18040                Slog.w(TAG, "Not removing non-existent package " + packageName);
18041                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18042            }
18043
18044            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18045                    && uninstalledPs.versionCode != versionCode) {
18046                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18047                        + uninstalledPs.versionCode + " != " + versionCode);
18048                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18049            }
18050
18051            // Static shared libs can be declared by any package, so let us not
18052            // allow removing a package if it provides a lib others depend on.
18053            pkg = mPackages.get(packageName);
18054
18055            allUsers = sUserManager.getUserIds();
18056
18057            if (pkg != null && pkg.staticSharedLibName != null) {
18058                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18059                        pkg.staticSharedLibVersion);
18060                if (libEntry != null) {
18061                    for (int currUserId : allUsers) {
18062                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18063                            continue;
18064                        }
18065                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18066                                libEntry.info, 0, currUserId);
18067                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18068                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18069                                    + " hosting lib " + libEntry.info.getName() + " version "
18070                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
18071                                    + " for user " + currUserId);
18072                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18073                        }
18074                    }
18075                }
18076            }
18077
18078            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18079        }
18080
18081        final int freezeUser;
18082        if (isUpdatedSystemApp(uninstalledPs)
18083                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18084            // We're downgrading a system app, which will apply to all users, so
18085            // freeze them all during the downgrade
18086            freezeUser = UserHandle.USER_ALL;
18087        } else {
18088            freezeUser = removeUser;
18089        }
18090
18091        synchronized (mInstallLock) {
18092            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18093            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18094                    deleteFlags, "deletePackageX")) {
18095                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18096                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
18097            }
18098            synchronized (mPackages) {
18099                if (res) {
18100                    if (pkg != null) {
18101                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18102                    }
18103                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18104                    updateInstantAppInstallerLocked(packageName);
18105                }
18106            }
18107        }
18108
18109        if (res) {
18110            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18111            info.sendPackageRemovedBroadcasts(killApp);
18112            info.sendSystemPackageUpdatedBroadcasts();
18113            info.sendSystemPackageAppearedBroadcasts();
18114        }
18115        // Force a gc here.
18116        Runtime.getRuntime().gc();
18117        // Delete the resources here after sending the broadcast to let
18118        // other processes clean up before deleting resources.
18119        if (info.args != null) {
18120            synchronized (mInstallLock) {
18121                info.args.doPostDeleteLI(true);
18122            }
18123        }
18124
18125        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18126    }
18127
18128    static class PackageRemovedInfo {
18129        final PackageSender packageSender;
18130        String removedPackage;
18131        String installerPackageName;
18132        int uid = -1;
18133        int removedAppId = -1;
18134        int[] origUsers;
18135        int[] removedUsers = null;
18136        int[] broadcastUsers = null;
18137        int[] instantUserIds = null;
18138        SparseArray<Integer> installReasons;
18139        boolean isRemovedPackageSystemUpdate = false;
18140        boolean isUpdate;
18141        boolean dataRemoved;
18142        boolean removedForAllUsers;
18143        boolean isStaticSharedLib;
18144        // Clean up resources deleted packages.
18145        InstallArgs args = null;
18146        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18147        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18148
18149        PackageRemovedInfo(PackageSender packageSender) {
18150            this.packageSender = packageSender;
18151        }
18152
18153        void sendPackageRemovedBroadcasts(boolean killApp) {
18154            sendPackageRemovedBroadcastInternal(killApp);
18155            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18156            for (int i = 0; i < childCount; i++) {
18157                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18158                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18159            }
18160        }
18161
18162        void sendSystemPackageUpdatedBroadcasts() {
18163            if (isRemovedPackageSystemUpdate) {
18164                sendSystemPackageUpdatedBroadcastsInternal();
18165                final int childCount = (removedChildPackages != null)
18166                        ? removedChildPackages.size() : 0;
18167                for (int i = 0; i < childCount; i++) {
18168                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18169                    if (childInfo.isRemovedPackageSystemUpdate) {
18170                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18171                    }
18172                }
18173            }
18174        }
18175
18176        void sendSystemPackageAppearedBroadcasts() {
18177            final int packageCount = (appearedChildPackages != null)
18178                    ? appearedChildPackages.size() : 0;
18179            for (int i = 0; i < packageCount; i++) {
18180                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18181                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18182                    true /*sendBootCompleted*/, false /*startReceiver*/,
18183                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
18184            }
18185        }
18186
18187        private void sendSystemPackageUpdatedBroadcastsInternal() {
18188            Bundle extras = new Bundle(2);
18189            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18190            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18191            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18192                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18193            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18194                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18195            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18196                null, null, 0, removedPackage, null, null, null);
18197            if (installerPackageName != null) {
18198                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18199                        removedPackage, extras, 0 /*flags*/,
18200                        installerPackageName, null, null, null);
18201                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18202                        removedPackage, extras, 0 /*flags*/,
18203                        installerPackageName, null, null, null);
18204            }
18205        }
18206
18207        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18208            // Don't send static shared library removal broadcasts as these
18209            // libs are visible only the the apps that depend on them an one
18210            // cannot remove the library if it has a dependency.
18211            if (isStaticSharedLib) {
18212                return;
18213            }
18214            Bundle extras = new Bundle(2);
18215            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18216            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18217            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18218            if (isUpdate || isRemovedPackageSystemUpdate) {
18219                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18220            }
18221            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18222            if (removedPackage != null) {
18223                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18224                    removedPackage, extras, 0, null /*targetPackage*/, null,
18225                    broadcastUsers, instantUserIds);
18226                if (installerPackageName != null) {
18227                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18228                            removedPackage, extras, 0 /*flags*/,
18229                            installerPackageName, null, broadcastUsers, instantUserIds);
18230                }
18231                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18232                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18233                        removedPackage, extras,
18234                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18235                        null, null, broadcastUsers, instantUserIds);
18236                    packageSender.notifyPackageRemoved(removedPackage);
18237                }
18238            }
18239            if (removedAppId >= 0) {
18240                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18241                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18242                    null, null, broadcastUsers, instantUserIds);
18243            }
18244        }
18245
18246        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18247            removedUsers = userIds;
18248            if (removedUsers == null) {
18249                broadcastUsers = null;
18250                return;
18251            }
18252
18253            broadcastUsers = EMPTY_INT_ARRAY;
18254            instantUserIds = EMPTY_INT_ARRAY;
18255            for (int i = userIds.length - 1; i >= 0; --i) {
18256                final int userId = userIds[i];
18257                if (deletedPackageSetting.getInstantApp(userId)) {
18258                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18259                } else {
18260                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18261                }
18262            }
18263        }
18264    }
18265
18266    /*
18267     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18268     * flag is not set, the data directory is removed as well.
18269     * make sure this flag is set for partially installed apps. If not its meaningless to
18270     * delete a partially installed application.
18271     */
18272    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18273            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18274        String packageName = ps.name;
18275        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18276        // Retrieve object to delete permissions for shared user later on
18277        final PackageParser.Package deletedPkg;
18278        final PackageSetting deletedPs;
18279        // reader
18280        synchronized (mPackages) {
18281            deletedPkg = mPackages.get(packageName);
18282            deletedPs = mSettings.mPackages.get(packageName);
18283            if (outInfo != null) {
18284                outInfo.removedPackage = packageName;
18285                outInfo.installerPackageName = ps.installerPackageName;
18286                outInfo.isStaticSharedLib = deletedPkg != null
18287                        && deletedPkg.staticSharedLibName != null;
18288                outInfo.populateUsers(deletedPs == null ? null
18289                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18290            }
18291        }
18292
18293        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18294
18295        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18296            final PackageParser.Package resolvedPkg;
18297            if (deletedPkg != null) {
18298                resolvedPkg = deletedPkg;
18299            } else {
18300                // We don't have a parsed package when it lives on an ejected
18301                // adopted storage device, so fake something together
18302                resolvedPkg = new PackageParser.Package(ps.name);
18303                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18304            }
18305            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18306                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18307            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18308            if (outInfo != null) {
18309                outInfo.dataRemoved = true;
18310            }
18311            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18312        }
18313
18314        int removedAppId = -1;
18315
18316        // writer
18317        synchronized (mPackages) {
18318            boolean installedStateChanged = false;
18319            if (deletedPs != null) {
18320                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18321                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18322                    clearDefaultBrowserIfNeeded(packageName);
18323                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18324                    removedAppId = mSettings.removePackageLPw(packageName);
18325                    if (outInfo != null) {
18326                        outInfo.removedAppId = removedAppId;
18327                    }
18328                    mPermissionManager.updatePermissions(
18329                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18330                    if (deletedPs.sharedUser != null) {
18331                        // Remove permissions associated with package. Since runtime
18332                        // permissions are per user we have to kill the removed package
18333                        // or packages running under the shared user of the removed
18334                        // package if revoking the permissions requested only by the removed
18335                        // package is successful and this causes a change in gids.
18336                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18337                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18338                                    userId);
18339                            if (userIdToKill == UserHandle.USER_ALL
18340                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18341                                // If gids changed for this user, kill all affected packages.
18342                                mHandler.post(new Runnable() {
18343                                    @Override
18344                                    public void run() {
18345                                        // This has to happen with no lock held.
18346                                        killApplication(deletedPs.name, deletedPs.appId,
18347                                                KILL_APP_REASON_GIDS_CHANGED);
18348                                    }
18349                                });
18350                                break;
18351                            }
18352                        }
18353                    }
18354                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18355                }
18356                // make sure to preserve per-user disabled state if this removal was just
18357                // a downgrade of a system app to the factory package
18358                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18359                    if (DEBUG_REMOVE) {
18360                        Slog.d(TAG, "Propagating install state across downgrade");
18361                    }
18362                    for (int userId : allUserHandles) {
18363                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18364                        if (DEBUG_REMOVE) {
18365                            Slog.d(TAG, "    user " + userId + " => " + installed);
18366                        }
18367                        if (installed != ps.getInstalled(userId)) {
18368                            installedStateChanged = true;
18369                        }
18370                        ps.setInstalled(installed, userId);
18371                    }
18372                }
18373            }
18374            // can downgrade to reader
18375            if (writeSettings) {
18376                // Save settings now
18377                mSettings.writeLPr();
18378            }
18379            if (installedStateChanged) {
18380                mSettings.writeKernelMappingLPr(ps);
18381            }
18382        }
18383        if (removedAppId != -1) {
18384            // A user ID was deleted here. Go through all users and remove it
18385            // from KeyStore.
18386            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18387        }
18388    }
18389
18390    static boolean locationIsPrivileged(String path) {
18391        try {
18392            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18393            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18394            final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app");
18395            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18396            return path.startsWith(privilegedAppDir.getCanonicalPath())
18397                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18398                    || path.startsWith(privilegedOdmAppDir.getCanonicalPath())
18399                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18400        } catch (IOException e) {
18401            Slog.e(TAG, "Unable to access code path " + path);
18402        }
18403        return false;
18404    }
18405
18406    static boolean locationIsOem(String path) {
18407        try {
18408            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18409        } catch (IOException e) {
18410            Slog.e(TAG, "Unable to access code path " + path);
18411        }
18412        return false;
18413    }
18414
18415    static boolean locationIsVendor(String path) {
18416        try {
18417            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath())
18418                    || path.startsWith(Environment.getOdmDirectory().getCanonicalPath());
18419        } catch (IOException e) {
18420            Slog.e(TAG, "Unable to access code path " + path);
18421        }
18422        return false;
18423    }
18424
18425    static boolean locationIsProduct(String path) {
18426        try {
18427            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18428        } catch (IOException e) {
18429            Slog.e(TAG, "Unable to access code path " + path);
18430        }
18431        return false;
18432    }
18433
18434    /*
18435     * Tries to delete system package.
18436     */
18437    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18438            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18439            boolean writeSettings) {
18440        if (deletedPs.parentPackageName != null) {
18441            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18442            return false;
18443        }
18444
18445        final boolean applyUserRestrictions
18446                = (allUserHandles != null) && (outInfo.origUsers != null);
18447        final PackageSetting disabledPs;
18448        // Confirm if the system package has been updated
18449        // An updated system app can be deleted. This will also have to restore
18450        // the system pkg from system partition
18451        // reader
18452        synchronized (mPackages) {
18453            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18454        }
18455
18456        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18457                + " disabledPs=" + disabledPs);
18458
18459        if (disabledPs == null) {
18460            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18461            return false;
18462        } else if (DEBUG_REMOVE) {
18463            Slog.d(TAG, "Deleting system pkg from data partition");
18464        }
18465
18466        if (DEBUG_REMOVE) {
18467            if (applyUserRestrictions) {
18468                Slog.d(TAG, "Remembering install states:");
18469                for (int userId : allUserHandles) {
18470                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18471                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18472                }
18473            }
18474        }
18475
18476        // Delete the updated package
18477        outInfo.isRemovedPackageSystemUpdate = true;
18478        if (outInfo.removedChildPackages != null) {
18479            final int childCount = (deletedPs.childPackageNames != null)
18480                    ? deletedPs.childPackageNames.size() : 0;
18481            for (int i = 0; i < childCount; i++) {
18482                String childPackageName = deletedPs.childPackageNames.get(i);
18483                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18484                        .contains(childPackageName)) {
18485                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18486                            childPackageName);
18487                    if (childInfo != null) {
18488                        childInfo.isRemovedPackageSystemUpdate = true;
18489                    }
18490                }
18491            }
18492        }
18493
18494        if (disabledPs.versionCode < deletedPs.versionCode) {
18495            // Delete data for downgrades
18496            flags &= ~PackageManager.DELETE_KEEP_DATA;
18497        } else {
18498            // Preserve data by setting flag
18499            flags |= PackageManager.DELETE_KEEP_DATA;
18500        }
18501
18502        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18503                outInfo, writeSettings, disabledPs.pkg);
18504        if (!ret) {
18505            return false;
18506        }
18507
18508        // writer
18509        synchronized (mPackages) {
18510            // NOTE: The system package always needs to be enabled; even if it's for
18511            // a compressed stub. If we don't, installing the system package fails
18512            // during scan [scanning checks the disabled packages]. We will reverse
18513            // this later, after we've "installed" the stub.
18514            // Reinstate the old system package
18515            enableSystemPackageLPw(disabledPs.pkg);
18516            // Remove any native libraries from the upgraded package.
18517            removeNativeBinariesLI(deletedPs);
18518        }
18519
18520        // Install the system package
18521        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18522        try {
18523            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18524                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18525        } catch (PackageManagerException e) {
18526            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18527                    + e.getMessage());
18528            return false;
18529        } finally {
18530            if (disabledPs.pkg.isStub) {
18531                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18532            }
18533        }
18534        return true;
18535    }
18536
18537    /**
18538     * Installs a package that's already on the system partition.
18539     */
18540    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18541            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18542            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18543                    throws PackageManagerException {
18544        @ParseFlags int parseFlags =
18545                mDefParseFlags
18546                | PackageParser.PARSE_MUST_BE_APK
18547                | PackageParser.PARSE_IS_SYSTEM_DIR;
18548        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18549        if (isPrivileged || locationIsPrivileged(codePathString)) {
18550            scanFlags |= SCAN_AS_PRIVILEGED;
18551        }
18552        if (locationIsOem(codePathString)) {
18553            scanFlags |= SCAN_AS_OEM;
18554        }
18555        if (locationIsVendor(codePathString)) {
18556            scanFlags |= SCAN_AS_VENDOR;
18557        }
18558        if (locationIsProduct(codePathString)) {
18559            scanFlags |= SCAN_AS_PRODUCT;
18560        }
18561
18562        final File codePath = new File(codePathString);
18563        final PackageParser.Package pkg =
18564                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18565
18566        try {
18567            // update shared libraries for the newly re-installed system package
18568            updateSharedLibrariesLPr(pkg, null);
18569        } catch (PackageManagerException e) {
18570            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18571        }
18572
18573        prepareAppDataAfterInstallLIF(pkg);
18574
18575        // writer
18576        synchronized (mPackages) {
18577            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18578
18579            // Propagate the permissions state as we do not want to drop on the floor
18580            // runtime permissions. The update permissions method below will take
18581            // care of removing obsolete permissions and grant install permissions.
18582            if (origPermissionState != null) {
18583                ps.getPermissionsState().copyFrom(origPermissionState);
18584            }
18585            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18586                    mPermissionCallback);
18587
18588            final boolean applyUserRestrictions
18589                    = (allUserHandles != null) && (origUserHandles != null);
18590            if (applyUserRestrictions) {
18591                boolean installedStateChanged = false;
18592                if (DEBUG_REMOVE) {
18593                    Slog.d(TAG, "Propagating install state across reinstall");
18594                }
18595                for (int userId : allUserHandles) {
18596                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18597                    if (DEBUG_REMOVE) {
18598                        Slog.d(TAG, "    user " + userId + " => " + installed);
18599                    }
18600                    if (installed != ps.getInstalled(userId)) {
18601                        installedStateChanged = true;
18602                    }
18603                    ps.setInstalled(installed, userId);
18604
18605                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18606                }
18607                // Regardless of writeSettings we need to ensure that this restriction
18608                // state propagation is persisted
18609                mSettings.writeAllUsersPackageRestrictionsLPr();
18610                if (installedStateChanged) {
18611                    mSettings.writeKernelMappingLPr(ps);
18612                }
18613            }
18614            // can downgrade to reader here
18615            if (writeSettings) {
18616                mSettings.writeLPr();
18617            }
18618        }
18619        return pkg;
18620    }
18621
18622    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18623            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18624            PackageRemovedInfo outInfo, boolean writeSettings,
18625            PackageParser.Package replacingPackage) {
18626        synchronized (mPackages) {
18627            if (outInfo != null) {
18628                outInfo.uid = ps.appId;
18629            }
18630
18631            if (outInfo != null && outInfo.removedChildPackages != null) {
18632                final int childCount = (ps.childPackageNames != null)
18633                        ? ps.childPackageNames.size() : 0;
18634                for (int i = 0; i < childCount; i++) {
18635                    String childPackageName = ps.childPackageNames.get(i);
18636                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18637                    if (childPs == null) {
18638                        return false;
18639                    }
18640                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18641                            childPackageName);
18642                    if (childInfo != null) {
18643                        childInfo.uid = childPs.appId;
18644                    }
18645                }
18646            }
18647        }
18648
18649        // Delete package data from internal structures and also remove data if flag is set
18650        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18651
18652        // Delete the child packages data
18653        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18654        for (int i = 0; i < childCount; i++) {
18655            PackageSetting childPs;
18656            synchronized (mPackages) {
18657                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18658            }
18659            if (childPs != null) {
18660                PackageRemovedInfo childOutInfo = (outInfo != null
18661                        && outInfo.removedChildPackages != null)
18662                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18663                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18664                        && (replacingPackage != null
18665                        && !replacingPackage.hasChildPackage(childPs.name))
18666                        ? flags & ~DELETE_KEEP_DATA : flags;
18667                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18668                        deleteFlags, writeSettings);
18669            }
18670        }
18671
18672        // Delete application code and resources only for parent packages
18673        if (ps.parentPackageName == null) {
18674            if (deleteCodeAndResources && (outInfo != null)) {
18675                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18676                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18677                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18678            }
18679        }
18680
18681        return true;
18682    }
18683
18684    @Override
18685    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18686            int userId) {
18687        mContext.enforceCallingOrSelfPermission(
18688                android.Manifest.permission.DELETE_PACKAGES, null);
18689        synchronized (mPackages) {
18690            // Cannot block uninstall of static shared libs as they are
18691            // considered a part of the using app (emulating static linking).
18692            // Also static libs are installed always on internal storage.
18693            PackageParser.Package pkg = mPackages.get(packageName);
18694            if (pkg != null && pkg.staticSharedLibName != null) {
18695                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18696                        + " providing static shared library: " + pkg.staticSharedLibName);
18697                return false;
18698            }
18699            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18700            mSettings.writePackageRestrictionsLPr(userId);
18701        }
18702        return true;
18703    }
18704
18705    @Override
18706    public boolean getBlockUninstallForUser(String packageName, int userId) {
18707        synchronized (mPackages) {
18708            final PackageSetting ps = mSettings.mPackages.get(packageName);
18709            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18710                return false;
18711            }
18712            return mSettings.getBlockUninstallLPr(userId, packageName);
18713        }
18714    }
18715
18716    @Override
18717    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18718        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18719        synchronized (mPackages) {
18720            PackageSetting ps = mSettings.mPackages.get(packageName);
18721            if (ps == null) {
18722                Log.w(TAG, "Package doesn't exist: " + packageName);
18723                return false;
18724            }
18725            if (systemUserApp) {
18726                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18727            } else {
18728                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18729            }
18730            mSettings.writeLPr();
18731        }
18732        return true;
18733    }
18734
18735    /*
18736     * This method handles package deletion in general
18737     */
18738    private boolean deletePackageLIF(String packageName, UserHandle user,
18739            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18740            PackageRemovedInfo outInfo, boolean writeSettings,
18741            PackageParser.Package replacingPackage) {
18742        if (packageName == null) {
18743            Slog.w(TAG, "Attempt to delete null packageName.");
18744            return false;
18745        }
18746
18747        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18748
18749        PackageSetting ps;
18750        synchronized (mPackages) {
18751            ps = mSettings.mPackages.get(packageName);
18752            if (ps == null) {
18753                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18754                return false;
18755            }
18756
18757            if (ps.parentPackageName != null && (!isSystemApp(ps)
18758                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18759                if (DEBUG_REMOVE) {
18760                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18761                            + ((user == null) ? UserHandle.USER_ALL : user));
18762                }
18763                final int removedUserId = (user != null) ? user.getIdentifier()
18764                        : UserHandle.USER_ALL;
18765
18766                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18767                    return false;
18768                }
18769                markPackageUninstalledForUserLPw(ps, user);
18770                scheduleWritePackageRestrictionsLocked(user);
18771                return true;
18772            }
18773        }
18774
18775        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
18776        if (ps.getPermissionsState().hasPermission(Manifest.permission.SUSPEND_APPS, userId)) {
18777            onSuspendingPackageRemoved(packageName, userId);
18778        }
18779
18780
18781        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18782                && user.getIdentifier() != UserHandle.USER_ALL)) {
18783            // The caller is asking that the package only be deleted for a single
18784            // user.  To do this, we just mark its uninstalled state and delete
18785            // its data. If this is a system app, we only allow this to happen if
18786            // they have set the special DELETE_SYSTEM_APP which requests different
18787            // semantics than normal for uninstalling system apps.
18788            markPackageUninstalledForUserLPw(ps, user);
18789
18790            if (!isSystemApp(ps)) {
18791                // Do not uninstall the APK if an app should be cached
18792                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18793                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18794                    // Other user still have this package installed, so all
18795                    // we need to do is clear this user's data and save that
18796                    // it is uninstalled.
18797                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18798                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18799                        return false;
18800                    }
18801                    scheduleWritePackageRestrictionsLocked(user);
18802                    return true;
18803                } else {
18804                    // We need to set it back to 'installed' so the uninstall
18805                    // broadcasts will be sent correctly.
18806                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18807                    ps.setInstalled(true, user.getIdentifier());
18808                    mSettings.writeKernelMappingLPr(ps);
18809                }
18810            } else {
18811                // This is a system app, so we assume that the
18812                // other users still have this package installed, so all
18813                // we need to do is clear this user's data and save that
18814                // it is uninstalled.
18815                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18816                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18817                    return false;
18818                }
18819                scheduleWritePackageRestrictionsLocked(user);
18820                return true;
18821            }
18822        }
18823
18824        // If we are deleting a composite package for all users, keep track
18825        // of result for each child.
18826        if (ps.childPackageNames != null && outInfo != null) {
18827            synchronized (mPackages) {
18828                final int childCount = ps.childPackageNames.size();
18829                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18830                for (int i = 0; i < childCount; i++) {
18831                    String childPackageName = ps.childPackageNames.get(i);
18832                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18833                    childInfo.removedPackage = childPackageName;
18834                    childInfo.installerPackageName = ps.installerPackageName;
18835                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18836                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18837                    if (childPs != null) {
18838                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18839                    }
18840                }
18841            }
18842        }
18843
18844        boolean ret = false;
18845        if (isSystemApp(ps)) {
18846            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18847            // When an updated system application is deleted we delete the existing resources
18848            // as well and fall back to existing code in system partition
18849            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18850        } else {
18851            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18852            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18853                    outInfo, writeSettings, replacingPackage);
18854        }
18855
18856        // Take a note whether we deleted the package for all users
18857        if (outInfo != null) {
18858            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18859            if (outInfo.removedChildPackages != null) {
18860                synchronized (mPackages) {
18861                    final int childCount = outInfo.removedChildPackages.size();
18862                    for (int i = 0; i < childCount; i++) {
18863                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18864                        if (childInfo != null) {
18865                            childInfo.removedForAllUsers = mPackages.get(
18866                                    childInfo.removedPackage) == null;
18867                        }
18868                    }
18869                }
18870            }
18871            // If we uninstalled an update to a system app there may be some
18872            // child packages that appeared as they are declared in the system
18873            // app but were not declared in the update.
18874            if (isSystemApp(ps)) {
18875                synchronized (mPackages) {
18876                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18877                    final int childCount = (updatedPs.childPackageNames != null)
18878                            ? updatedPs.childPackageNames.size() : 0;
18879                    for (int i = 0; i < childCount; i++) {
18880                        String childPackageName = updatedPs.childPackageNames.get(i);
18881                        if (outInfo.removedChildPackages == null
18882                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18883                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18884                            if (childPs == null) {
18885                                continue;
18886                            }
18887                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18888                            installRes.name = childPackageName;
18889                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18890                            installRes.pkg = mPackages.get(childPackageName);
18891                            installRes.uid = childPs.pkg.applicationInfo.uid;
18892                            if (outInfo.appearedChildPackages == null) {
18893                                outInfo.appearedChildPackages = new ArrayMap<>();
18894                            }
18895                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18896                        }
18897                    }
18898                }
18899            }
18900        }
18901
18902        return ret;
18903    }
18904
18905    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18906        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18907                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18908        for (int nextUserId : userIds) {
18909            if (DEBUG_REMOVE) {
18910                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18911            }
18912            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18913                    false /*installed*/,
18914                    true /*stopped*/,
18915                    true /*notLaunched*/,
18916                    false /*hidden*/,
18917                    false /*suspended*/,
18918                    null, /*suspendingPackage*/
18919                    null, /*dialogMessage*/
18920                    null, /*suspendedAppExtras*/
18921                    null, /*suspendedLauncherExtras*/
18922                    false /*instantApp*/,
18923                    false /*virtualPreload*/,
18924                    null /*lastDisableAppCaller*/,
18925                    null /*enabledComponents*/,
18926                    null /*disabledComponents*/,
18927                    ps.readUserState(nextUserId).domainVerificationStatus,
18928                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18929                    null /*harmfulAppWarning*/);
18930        }
18931        mSettings.writeKernelMappingLPr(ps);
18932    }
18933
18934    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18935            PackageRemovedInfo outInfo) {
18936        final PackageParser.Package pkg;
18937        synchronized (mPackages) {
18938            pkg = mPackages.get(ps.name);
18939        }
18940
18941        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18942                : new int[] {userId};
18943        for (int nextUserId : userIds) {
18944            if (DEBUG_REMOVE) {
18945                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18946                        + nextUserId);
18947            }
18948
18949            destroyAppDataLIF(pkg, userId,
18950                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18951            destroyAppProfilesLIF(pkg, userId);
18952            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18953            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18954            schedulePackageCleaning(ps.name, nextUserId, false);
18955            synchronized (mPackages) {
18956                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18957                    scheduleWritePackageRestrictionsLocked(nextUserId);
18958                }
18959                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18960            }
18961        }
18962
18963        if (outInfo != null) {
18964            outInfo.removedPackage = ps.name;
18965            outInfo.installerPackageName = ps.installerPackageName;
18966            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18967            outInfo.removedAppId = ps.appId;
18968            outInfo.removedUsers = userIds;
18969            outInfo.broadcastUsers = userIds;
18970        }
18971
18972        return true;
18973    }
18974
18975    private final class ClearStorageConnection implements ServiceConnection {
18976        IMediaContainerService mContainerService;
18977
18978        @Override
18979        public void onServiceConnected(ComponentName name, IBinder service) {
18980            synchronized (this) {
18981                mContainerService = IMediaContainerService.Stub
18982                        .asInterface(Binder.allowBlocking(service));
18983                notifyAll();
18984            }
18985        }
18986
18987        @Override
18988        public void onServiceDisconnected(ComponentName name) {
18989        }
18990    }
18991
18992    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18993        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18994
18995        final boolean mounted;
18996        if (Environment.isExternalStorageEmulated()) {
18997            mounted = true;
18998        } else {
18999            final String status = Environment.getExternalStorageState();
19000
19001            mounted = status.equals(Environment.MEDIA_MOUNTED)
19002                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19003        }
19004
19005        if (!mounted) {
19006            return;
19007        }
19008
19009        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19010        int[] users;
19011        if (userId == UserHandle.USER_ALL) {
19012            users = sUserManager.getUserIds();
19013        } else {
19014            users = new int[] { userId };
19015        }
19016        final ClearStorageConnection conn = new ClearStorageConnection();
19017        if (mContext.bindServiceAsUser(
19018                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19019            try {
19020                for (int curUser : users) {
19021                    long timeout = SystemClock.uptimeMillis() + 5000;
19022                    synchronized (conn) {
19023                        long now;
19024                        while (conn.mContainerService == null &&
19025                                (now = SystemClock.uptimeMillis()) < timeout) {
19026                            try {
19027                                conn.wait(timeout - now);
19028                            } catch (InterruptedException e) {
19029                            }
19030                        }
19031                    }
19032                    if (conn.mContainerService == null) {
19033                        return;
19034                    }
19035
19036                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19037                    clearDirectory(conn.mContainerService,
19038                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19039                    if (allData) {
19040                        clearDirectory(conn.mContainerService,
19041                                userEnv.buildExternalStorageAppDataDirs(packageName));
19042                        clearDirectory(conn.mContainerService,
19043                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19044                    }
19045                }
19046            } finally {
19047                mContext.unbindService(conn);
19048            }
19049        }
19050    }
19051
19052    @Override
19053    public void clearApplicationProfileData(String packageName) {
19054        enforceSystemOrRoot("Only the system can clear all profile data");
19055
19056        final PackageParser.Package pkg;
19057        synchronized (mPackages) {
19058            pkg = mPackages.get(packageName);
19059        }
19060
19061        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19062            synchronized (mInstallLock) {
19063                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19064            }
19065        }
19066    }
19067
19068    @Override
19069    public void clearApplicationUserData(final String packageName,
19070            final IPackageDataObserver observer, final int userId) {
19071        mContext.enforceCallingOrSelfPermission(
19072                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19073
19074        final int callingUid = Binder.getCallingUid();
19075        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19076                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19077
19078        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19079        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
19080        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19081            throw new SecurityException("Cannot clear data for a protected package: "
19082                    + packageName);
19083        }
19084        // Queue up an async operation since the package deletion may take a little while.
19085        mHandler.post(new Runnable() {
19086            public void run() {
19087                mHandler.removeCallbacks(this);
19088                final boolean succeeded;
19089                if (!filterApp) {
19090                    try (PackageFreezer freezer = freezePackage(packageName,
19091                            "clearApplicationUserData")) {
19092                        synchronized (mInstallLock) {
19093                            succeeded = clearApplicationUserDataLIF(packageName, userId);
19094                        }
19095                        clearExternalStorageDataSync(packageName, userId, true);
19096                        synchronized (mPackages) {
19097                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19098                                    packageName, userId);
19099                        }
19100                    }
19101                    if (succeeded) {
19102                        // invoke DeviceStorageMonitor's update method to clear any notifications
19103                        DeviceStorageMonitorInternal dsm = LocalServices
19104                                .getService(DeviceStorageMonitorInternal.class);
19105                        if (dsm != null) {
19106                            dsm.checkMemory();
19107                        }
19108                    }
19109                } else {
19110                    succeeded = false;
19111                }
19112                if (observer != null) {
19113                    try {
19114                        observer.onRemoveCompleted(packageName, succeeded);
19115                    } catch (RemoteException e) {
19116                        Log.i(TAG, "Observer no longer exists.");
19117                    }
19118                } //end if observer
19119            } //end run
19120        });
19121    }
19122
19123    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19124        if (packageName == null) {
19125            Slog.w(TAG, "Attempt to delete null packageName.");
19126            return false;
19127        }
19128
19129        // Try finding details about the requested package
19130        PackageParser.Package pkg;
19131        synchronized (mPackages) {
19132            pkg = mPackages.get(packageName);
19133            if (pkg == null) {
19134                final PackageSetting ps = mSettings.mPackages.get(packageName);
19135                if (ps != null) {
19136                    pkg = ps.pkg;
19137                }
19138            }
19139
19140            if (pkg == null) {
19141                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19142                return false;
19143            }
19144
19145            PackageSetting ps = (PackageSetting) pkg.mExtras;
19146            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19147        }
19148
19149        clearAppDataLIF(pkg, userId,
19150                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19151
19152        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19153        removeKeystoreDataIfNeeded(userId, appId);
19154
19155        UserManagerInternal umInternal = getUserManagerInternal();
19156        final int flags;
19157        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19158            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19159        } else if (umInternal.isUserRunning(userId)) {
19160            flags = StorageManager.FLAG_STORAGE_DE;
19161        } else {
19162            flags = 0;
19163        }
19164        prepareAppDataContentsLIF(pkg, userId, flags);
19165
19166        return true;
19167    }
19168
19169    /**
19170     * Reverts user permission state changes (permissions and flags) in
19171     * all packages for a given user.
19172     *
19173     * @param userId The device user for which to do a reset.
19174     */
19175    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19176        final int packageCount = mPackages.size();
19177        for (int i = 0; i < packageCount; i++) {
19178            PackageParser.Package pkg = mPackages.valueAt(i);
19179            PackageSetting ps = (PackageSetting) pkg.mExtras;
19180            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19181        }
19182    }
19183
19184    private void resetNetworkPolicies(int userId) {
19185        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19186    }
19187
19188    /**
19189     * Reverts user permission state changes (permissions and flags).
19190     *
19191     * @param ps The package for which to reset.
19192     * @param userId The device user for which to do a reset.
19193     */
19194    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19195            final PackageSetting ps, final int userId) {
19196        if (ps.pkg == null) {
19197            return;
19198        }
19199
19200        // These are flags that can change base on user actions.
19201        final int userSettableMask = FLAG_PERMISSION_USER_SET
19202                | FLAG_PERMISSION_USER_FIXED
19203                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19204                | FLAG_PERMISSION_REVIEW_REQUIRED;
19205
19206        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19207                | FLAG_PERMISSION_POLICY_FIXED;
19208
19209        boolean writeInstallPermissions = false;
19210        boolean writeRuntimePermissions = false;
19211
19212        final int permissionCount = ps.pkg.requestedPermissions.size();
19213        for (int i = 0; i < permissionCount; i++) {
19214            final String permName = ps.pkg.requestedPermissions.get(i);
19215            final BasePermission bp =
19216                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19217            if (bp == null) {
19218                continue;
19219            }
19220
19221            // If shared user we just reset the state to which only this app contributed.
19222            if (ps.sharedUser != null) {
19223                boolean used = false;
19224                final int packageCount = ps.sharedUser.packages.size();
19225                for (int j = 0; j < packageCount; j++) {
19226                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19227                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19228                            && pkg.pkg.requestedPermissions.contains(permName)) {
19229                        used = true;
19230                        break;
19231                    }
19232                }
19233                if (used) {
19234                    continue;
19235                }
19236            }
19237
19238            final PermissionsState permissionsState = ps.getPermissionsState();
19239
19240            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19241
19242            // Always clear the user settable flags.
19243            final boolean hasInstallState =
19244                    permissionsState.getInstallPermissionState(permName) != null;
19245            // If permission review is enabled and this is a legacy app, mark the
19246            // permission as requiring a review as this is the initial state.
19247            int flags = 0;
19248            if (mSettings.mPermissions.mPermissionReviewRequired
19249                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19250                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19251            }
19252            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19253                if (hasInstallState) {
19254                    writeInstallPermissions = true;
19255                } else {
19256                    writeRuntimePermissions = true;
19257                }
19258            }
19259
19260            // Below is only runtime permission handling.
19261            if (!bp.isRuntime()) {
19262                continue;
19263            }
19264
19265            // Never clobber system or policy.
19266            if ((oldFlags & policyOrSystemFlags) != 0) {
19267                continue;
19268            }
19269
19270            // If this permission was granted by default, make sure it is.
19271            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19272                if (permissionsState.grantRuntimePermission(bp, userId)
19273                        != PERMISSION_OPERATION_FAILURE) {
19274                    writeRuntimePermissions = true;
19275                }
19276            // If permission review is enabled the permissions for a legacy apps
19277            // are represented as constantly granted runtime ones, so don't revoke.
19278            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19279                // Otherwise, reset the permission.
19280                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19281                switch (revokeResult) {
19282                    case PERMISSION_OPERATION_SUCCESS:
19283                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19284                        writeRuntimePermissions = true;
19285                        final int appId = ps.appId;
19286                        mHandler.post(new Runnable() {
19287                            @Override
19288                            public void run() {
19289                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19290                            }
19291                        });
19292                    } break;
19293                }
19294            }
19295        }
19296
19297        // Synchronously write as we are taking permissions away.
19298        if (writeRuntimePermissions) {
19299            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19300        }
19301
19302        // Synchronously write as we are taking permissions away.
19303        if (writeInstallPermissions) {
19304            mSettings.writeLPr();
19305        }
19306    }
19307
19308    /**
19309     * Remove entries from the keystore daemon. Will only remove it if the
19310     * {@code appId} is valid.
19311     */
19312    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19313        if (appId < 0) {
19314            return;
19315        }
19316
19317        final KeyStore keyStore = KeyStore.getInstance();
19318        if (keyStore != null) {
19319            if (userId == UserHandle.USER_ALL) {
19320                for (final int individual : sUserManager.getUserIds()) {
19321                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19322                }
19323            } else {
19324                keyStore.clearUid(UserHandle.getUid(userId, appId));
19325            }
19326        } else {
19327            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19328        }
19329    }
19330
19331    @Override
19332    public void deleteApplicationCacheFiles(final String packageName,
19333            final IPackageDataObserver observer) {
19334        final int userId = UserHandle.getCallingUserId();
19335        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19336    }
19337
19338    @Override
19339    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19340            final IPackageDataObserver observer) {
19341        final int callingUid = Binder.getCallingUid();
19342        if (mContext.checkCallingOrSelfPermission(
19343                android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
19344                != PackageManager.PERMISSION_GRANTED) {
19345            // If the caller has the old delete cache permission, silently ignore.  Else throw.
19346            if (mContext.checkCallingOrSelfPermission(
19347                    android.Manifest.permission.DELETE_CACHE_FILES)
19348                    == PackageManager.PERMISSION_GRANTED) {
19349                Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
19350                        android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
19351                        ", silently ignoring");
19352                return;
19353            }
19354            mContext.enforceCallingOrSelfPermission(
19355                    android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
19356        }
19357        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19358                /* requireFullPermission= */ true, /* checkShell= */ false,
19359                "delete application cache files");
19360        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19361                android.Manifest.permission.ACCESS_INSTANT_APPS);
19362
19363        final PackageParser.Package pkg;
19364        synchronized (mPackages) {
19365            pkg = mPackages.get(packageName);
19366        }
19367
19368        // Queue up an async operation since the package deletion may take a little while.
19369        mHandler.post(new Runnable() {
19370            public void run() {
19371                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19372                boolean doClearData = true;
19373                if (ps != null) {
19374                    final boolean targetIsInstantApp =
19375                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19376                    doClearData = !targetIsInstantApp
19377                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19378                }
19379                if (doClearData) {
19380                    synchronized (mInstallLock) {
19381                        final int flags = StorageManager.FLAG_STORAGE_DE
19382                                | StorageManager.FLAG_STORAGE_CE;
19383                        // We're only clearing cache files, so we don't care if the
19384                        // app is unfrozen and still able to run
19385                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19386                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19387                    }
19388                    clearExternalStorageDataSync(packageName, userId, false);
19389                }
19390                if (observer != null) {
19391                    try {
19392                        observer.onRemoveCompleted(packageName, true);
19393                    } catch (RemoteException e) {
19394                        Log.i(TAG, "Observer no longer exists.");
19395                    }
19396                }
19397            }
19398        });
19399    }
19400
19401    @Override
19402    public void getPackageSizeInfo(final String packageName, int userHandle,
19403            final IPackageStatsObserver observer) {
19404        throw new UnsupportedOperationException(
19405                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19406    }
19407
19408    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19409        final PackageSetting ps;
19410        synchronized (mPackages) {
19411            ps = mSettings.mPackages.get(packageName);
19412            if (ps == null) {
19413                Slog.w(TAG, "Failed to find settings for " + packageName);
19414                return false;
19415            }
19416        }
19417
19418        final String[] packageNames = { packageName };
19419        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19420        final String[] codePaths = { ps.codePathString };
19421
19422        try {
19423            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19424                    ps.appId, ceDataInodes, codePaths, stats);
19425
19426            // For now, ignore code size of packages on system partition
19427            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19428                stats.codeSize = 0;
19429            }
19430
19431            // External clients expect these to be tracked separately
19432            stats.dataSize -= stats.cacheSize;
19433
19434        } catch (InstallerException e) {
19435            Slog.w(TAG, String.valueOf(e));
19436            return false;
19437        }
19438
19439        return true;
19440    }
19441
19442    private int getUidTargetSdkVersionLockedLPr(int uid) {
19443        Object obj = mSettings.getUserIdLPr(uid);
19444        if (obj instanceof SharedUserSetting) {
19445            final SharedUserSetting sus = (SharedUserSetting) obj;
19446            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19447            final Iterator<PackageSetting> it = sus.packages.iterator();
19448            while (it.hasNext()) {
19449                final PackageSetting ps = it.next();
19450                if (ps.pkg != null) {
19451                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19452                    if (v < vers) vers = v;
19453                }
19454            }
19455            return vers;
19456        } else if (obj instanceof PackageSetting) {
19457            final PackageSetting ps = (PackageSetting) obj;
19458            if (ps.pkg != null) {
19459                return ps.pkg.applicationInfo.targetSdkVersion;
19460            }
19461        }
19462        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19463    }
19464
19465    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19466        final PackageParser.Package p = mPackages.get(packageName);
19467        if (p != null) {
19468            return p.applicationInfo.targetSdkVersion;
19469        }
19470        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19471    }
19472
19473    @Override
19474    public void addPreferredActivity(IntentFilter filter, int match,
19475            ComponentName[] set, ComponentName activity, int userId) {
19476        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19477                "Adding preferred");
19478    }
19479
19480    private void addPreferredActivityInternal(IntentFilter filter, int match,
19481            ComponentName[] set, ComponentName activity, boolean always, int userId,
19482            String opname) {
19483        // writer
19484        int callingUid = Binder.getCallingUid();
19485        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19486                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19487        if (filter.countActions() == 0) {
19488            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19489            return;
19490        }
19491        synchronized (mPackages) {
19492            if (mContext.checkCallingOrSelfPermission(
19493                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19494                    != PackageManager.PERMISSION_GRANTED) {
19495                if (getUidTargetSdkVersionLockedLPr(callingUid)
19496                        < Build.VERSION_CODES.FROYO) {
19497                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19498                            + callingUid);
19499                    return;
19500                }
19501                mContext.enforceCallingOrSelfPermission(
19502                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19503            }
19504
19505            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19506            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19507                    + userId + ":");
19508            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19509            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19510            scheduleWritePackageRestrictionsLocked(userId);
19511            postPreferredActivityChangedBroadcast(userId);
19512        }
19513    }
19514
19515    private void postPreferredActivityChangedBroadcast(int userId) {
19516        mHandler.post(() -> {
19517            final IActivityManager am = ActivityManager.getService();
19518            if (am == null) {
19519                return;
19520            }
19521
19522            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19523            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19524            try {
19525                am.broadcastIntent(null, intent, null, null,
19526                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19527                        null, false, false, userId);
19528            } catch (RemoteException e) {
19529            }
19530        });
19531    }
19532
19533    @Override
19534    public void replacePreferredActivity(IntentFilter filter, int match,
19535            ComponentName[] set, ComponentName activity, int userId) {
19536        if (filter.countActions() != 1) {
19537            throw new IllegalArgumentException(
19538                    "replacePreferredActivity expects filter to have only 1 action.");
19539        }
19540        if (filter.countDataAuthorities() != 0
19541                || filter.countDataPaths() != 0
19542                || filter.countDataSchemes() > 1
19543                || filter.countDataTypes() != 0) {
19544            throw new IllegalArgumentException(
19545                    "replacePreferredActivity expects filter to have no data authorities, " +
19546                    "paths, or types; and at most one scheme.");
19547        }
19548
19549        final int callingUid = Binder.getCallingUid();
19550        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19551                true /* requireFullPermission */, false /* checkShell */,
19552                "replace preferred activity");
19553        synchronized (mPackages) {
19554            if (mContext.checkCallingOrSelfPermission(
19555                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19556                    != PackageManager.PERMISSION_GRANTED) {
19557                if (getUidTargetSdkVersionLockedLPr(callingUid)
19558                        < Build.VERSION_CODES.FROYO) {
19559                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19560                            + Binder.getCallingUid());
19561                    return;
19562                }
19563                mContext.enforceCallingOrSelfPermission(
19564                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19565            }
19566
19567            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19568            if (pir != null) {
19569                // Get all of the existing entries that exactly match this filter.
19570                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19571                if (existing != null && existing.size() == 1) {
19572                    PreferredActivity cur = existing.get(0);
19573                    if (DEBUG_PREFERRED) {
19574                        Slog.i(TAG, "Checking replace of preferred:");
19575                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19576                        if (!cur.mPref.mAlways) {
19577                            Slog.i(TAG, "  -- CUR; not mAlways!");
19578                        } else {
19579                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19580                            Slog.i(TAG, "  -- CUR: mSet="
19581                                    + Arrays.toString(cur.mPref.mSetComponents));
19582                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19583                            Slog.i(TAG, "  -- NEW: mMatch="
19584                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19585                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19586                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19587                        }
19588                    }
19589                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19590                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19591                            && cur.mPref.sameSet(set)) {
19592                        // Setting the preferred activity to what it happens to be already
19593                        if (DEBUG_PREFERRED) {
19594                            Slog.i(TAG, "Replacing with same preferred activity "
19595                                    + cur.mPref.mShortComponent + " for user "
19596                                    + userId + ":");
19597                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19598                        }
19599                        return;
19600                    }
19601                }
19602
19603                if (existing != null) {
19604                    if (DEBUG_PREFERRED) {
19605                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19606                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19607                    }
19608                    for (int i = 0; i < existing.size(); i++) {
19609                        PreferredActivity pa = existing.get(i);
19610                        if (DEBUG_PREFERRED) {
19611                            Slog.i(TAG, "Removing existing preferred activity "
19612                                    + pa.mPref.mComponent + ":");
19613                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19614                        }
19615                        pir.removeFilter(pa);
19616                    }
19617                }
19618            }
19619            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19620                    "Replacing preferred");
19621        }
19622    }
19623
19624    @Override
19625    public void clearPackagePreferredActivities(String packageName) {
19626        final int callingUid = Binder.getCallingUid();
19627        if (getInstantAppPackageName(callingUid) != null) {
19628            return;
19629        }
19630        // writer
19631        synchronized (mPackages) {
19632            PackageParser.Package pkg = mPackages.get(packageName);
19633            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19634                if (mContext.checkCallingOrSelfPermission(
19635                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19636                        != PackageManager.PERMISSION_GRANTED) {
19637                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19638                            < Build.VERSION_CODES.FROYO) {
19639                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19640                                + callingUid);
19641                        return;
19642                    }
19643                    mContext.enforceCallingOrSelfPermission(
19644                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19645                }
19646            }
19647            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19648            if (ps != null
19649                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19650                return;
19651            }
19652            int user = UserHandle.getCallingUserId();
19653            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19654                scheduleWritePackageRestrictionsLocked(user);
19655            }
19656        }
19657    }
19658
19659    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19660    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19661        ArrayList<PreferredActivity> removed = null;
19662        boolean changed = false;
19663        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19664            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19665            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19666            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19667                continue;
19668            }
19669            Iterator<PreferredActivity> it = pir.filterIterator();
19670            while (it.hasNext()) {
19671                PreferredActivity pa = it.next();
19672                // Mark entry for removal only if it matches the package name
19673                // and the entry is of type "always".
19674                if (packageName == null ||
19675                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19676                                && pa.mPref.mAlways)) {
19677                    if (removed == null) {
19678                        removed = new ArrayList<PreferredActivity>();
19679                    }
19680                    removed.add(pa);
19681                }
19682            }
19683            if (removed != null) {
19684                for (int j=0; j<removed.size(); j++) {
19685                    PreferredActivity pa = removed.get(j);
19686                    pir.removeFilter(pa);
19687                }
19688                changed = true;
19689            }
19690        }
19691        if (changed) {
19692            postPreferredActivityChangedBroadcast(userId);
19693        }
19694        return changed;
19695    }
19696
19697    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19698    private void clearIntentFilterVerificationsLPw(int userId) {
19699        final int packageCount = mPackages.size();
19700        for (int i = 0; i < packageCount; i++) {
19701            PackageParser.Package pkg = mPackages.valueAt(i);
19702            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19703        }
19704    }
19705
19706    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19707    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19708        if (userId == UserHandle.USER_ALL) {
19709            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19710                    sUserManager.getUserIds())) {
19711                for (int oneUserId : sUserManager.getUserIds()) {
19712                    scheduleWritePackageRestrictionsLocked(oneUserId);
19713                }
19714            }
19715        } else {
19716            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19717                scheduleWritePackageRestrictionsLocked(userId);
19718            }
19719        }
19720    }
19721
19722    /** Clears state for all users, and touches intent filter verification policy */
19723    void clearDefaultBrowserIfNeeded(String packageName) {
19724        for (int oneUserId : sUserManager.getUserIds()) {
19725            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19726        }
19727    }
19728
19729    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19730        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19731        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19732            if (packageName.equals(defaultBrowserPackageName)) {
19733                setDefaultBrowserPackageName(null, userId);
19734            }
19735        }
19736    }
19737
19738    @Override
19739    public void resetApplicationPreferences(int userId) {
19740        mContext.enforceCallingOrSelfPermission(
19741                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19742        final long identity = Binder.clearCallingIdentity();
19743        // writer
19744        try {
19745            synchronized (mPackages) {
19746                clearPackagePreferredActivitiesLPw(null, userId);
19747                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19748                // TODO: We have to reset the default SMS and Phone. This requires
19749                // significant refactoring to keep all default apps in the package
19750                // manager (cleaner but more work) or have the services provide
19751                // callbacks to the package manager to request a default app reset.
19752                applyFactoryDefaultBrowserLPw(userId);
19753                clearIntentFilterVerificationsLPw(userId);
19754                primeDomainVerificationsLPw(userId);
19755                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19756                scheduleWritePackageRestrictionsLocked(userId);
19757            }
19758            resetNetworkPolicies(userId);
19759        } finally {
19760            Binder.restoreCallingIdentity(identity);
19761        }
19762    }
19763
19764    @Override
19765    public int getPreferredActivities(List<IntentFilter> outFilters,
19766            List<ComponentName> outActivities, String packageName) {
19767        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19768            return 0;
19769        }
19770        int num = 0;
19771        final int userId = UserHandle.getCallingUserId();
19772        // reader
19773        synchronized (mPackages) {
19774            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19775            if (pir != null) {
19776                final Iterator<PreferredActivity> it = pir.filterIterator();
19777                while (it.hasNext()) {
19778                    final PreferredActivity pa = it.next();
19779                    if (packageName == null
19780                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19781                                    && pa.mPref.mAlways)) {
19782                        if (outFilters != null) {
19783                            outFilters.add(new IntentFilter(pa));
19784                        }
19785                        if (outActivities != null) {
19786                            outActivities.add(pa.mPref.mComponent);
19787                        }
19788                    }
19789                }
19790            }
19791        }
19792
19793        return num;
19794    }
19795
19796    @Override
19797    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19798            int userId) {
19799        int callingUid = Binder.getCallingUid();
19800        if (callingUid != Process.SYSTEM_UID) {
19801            throw new SecurityException(
19802                    "addPersistentPreferredActivity can only be run by the system");
19803        }
19804        if (filter.countActions() == 0) {
19805            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19806            return;
19807        }
19808        synchronized (mPackages) {
19809            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19810                    ":");
19811            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19812            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19813                    new PersistentPreferredActivity(filter, activity));
19814            scheduleWritePackageRestrictionsLocked(userId);
19815            postPreferredActivityChangedBroadcast(userId);
19816        }
19817    }
19818
19819    @Override
19820    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19821        int callingUid = Binder.getCallingUid();
19822        if (callingUid != Process.SYSTEM_UID) {
19823            throw new SecurityException(
19824                    "clearPackagePersistentPreferredActivities can only be run by the system");
19825        }
19826        ArrayList<PersistentPreferredActivity> removed = null;
19827        boolean changed = false;
19828        synchronized (mPackages) {
19829            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19830                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19831                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19832                        .valueAt(i);
19833                if (userId != thisUserId) {
19834                    continue;
19835                }
19836                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19837                while (it.hasNext()) {
19838                    PersistentPreferredActivity ppa = it.next();
19839                    // Mark entry for removal only if it matches the package name.
19840                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19841                        if (removed == null) {
19842                            removed = new ArrayList<PersistentPreferredActivity>();
19843                        }
19844                        removed.add(ppa);
19845                    }
19846                }
19847                if (removed != null) {
19848                    for (int j=0; j<removed.size(); j++) {
19849                        PersistentPreferredActivity ppa = removed.get(j);
19850                        ppir.removeFilter(ppa);
19851                    }
19852                    changed = true;
19853                }
19854            }
19855
19856            if (changed) {
19857                scheduleWritePackageRestrictionsLocked(userId);
19858                postPreferredActivityChangedBroadcast(userId);
19859            }
19860        }
19861    }
19862
19863    /**
19864     * Common machinery for picking apart a restored XML blob and passing
19865     * it to a caller-supplied functor to be applied to the running system.
19866     */
19867    private void restoreFromXml(XmlPullParser parser, int userId,
19868            String expectedStartTag, BlobXmlRestorer functor)
19869            throws IOException, XmlPullParserException {
19870        int type;
19871        while ((type = parser.next()) != XmlPullParser.START_TAG
19872                && type != XmlPullParser.END_DOCUMENT) {
19873        }
19874        if (type != XmlPullParser.START_TAG) {
19875            // oops didn't find a start tag?!
19876            if (DEBUG_BACKUP) {
19877                Slog.e(TAG, "Didn't find start tag during restore");
19878            }
19879            return;
19880        }
19881Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19882        // this is supposed to be TAG_PREFERRED_BACKUP
19883        if (!expectedStartTag.equals(parser.getName())) {
19884            if (DEBUG_BACKUP) {
19885                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19886            }
19887            return;
19888        }
19889
19890        // skip interfering stuff, then we're aligned with the backing implementation
19891        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19892Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19893        functor.apply(parser, userId);
19894    }
19895
19896    private interface BlobXmlRestorer {
19897        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19898    }
19899
19900    /**
19901     * Non-Binder method, support for the backup/restore mechanism: write the
19902     * full set of preferred activities in its canonical XML format.  Returns the
19903     * XML output as a byte array, or null if there is none.
19904     */
19905    @Override
19906    public byte[] getPreferredActivityBackup(int userId) {
19907        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19908            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19909        }
19910
19911        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19912        try {
19913            final XmlSerializer serializer = new FastXmlSerializer();
19914            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19915            serializer.startDocument(null, true);
19916            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19917
19918            synchronized (mPackages) {
19919                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19920            }
19921
19922            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19923            serializer.endDocument();
19924            serializer.flush();
19925        } catch (Exception e) {
19926            if (DEBUG_BACKUP) {
19927                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19928            }
19929            return null;
19930        }
19931
19932        return dataStream.toByteArray();
19933    }
19934
19935    @Override
19936    public void restorePreferredActivities(byte[] backup, int userId) {
19937        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19938            throw new SecurityException("Only the system may call restorePreferredActivities()");
19939        }
19940
19941        try {
19942            final XmlPullParser parser = Xml.newPullParser();
19943            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19944            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19945                    new BlobXmlRestorer() {
19946                        @Override
19947                        public void apply(XmlPullParser parser, int userId)
19948                                throws XmlPullParserException, IOException {
19949                            synchronized (mPackages) {
19950                                mSettings.readPreferredActivitiesLPw(parser, userId);
19951                            }
19952                        }
19953                    } );
19954        } catch (Exception e) {
19955            if (DEBUG_BACKUP) {
19956                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19957            }
19958        }
19959    }
19960
19961    /**
19962     * Non-Binder method, support for the backup/restore mechanism: write the
19963     * default browser (etc) settings in its canonical XML format.  Returns the default
19964     * browser XML representation as a byte array, or null if there is none.
19965     */
19966    @Override
19967    public byte[] getDefaultAppsBackup(int userId) {
19968        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19969            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19970        }
19971
19972        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19973        try {
19974            final XmlSerializer serializer = new FastXmlSerializer();
19975            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19976            serializer.startDocument(null, true);
19977            serializer.startTag(null, TAG_DEFAULT_APPS);
19978
19979            synchronized (mPackages) {
19980                mSettings.writeDefaultAppsLPr(serializer, userId);
19981            }
19982
19983            serializer.endTag(null, TAG_DEFAULT_APPS);
19984            serializer.endDocument();
19985            serializer.flush();
19986        } catch (Exception e) {
19987            if (DEBUG_BACKUP) {
19988                Slog.e(TAG, "Unable to write default apps for backup", e);
19989            }
19990            return null;
19991        }
19992
19993        return dataStream.toByteArray();
19994    }
19995
19996    @Override
19997    public void restoreDefaultApps(byte[] backup, int userId) {
19998        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19999            throw new SecurityException("Only the system may call restoreDefaultApps()");
20000        }
20001
20002        try {
20003            final XmlPullParser parser = Xml.newPullParser();
20004            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20005            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20006                    new BlobXmlRestorer() {
20007                        @Override
20008                        public void apply(XmlPullParser parser, int userId)
20009                                throws XmlPullParserException, IOException {
20010                            synchronized (mPackages) {
20011                                mSettings.readDefaultAppsLPw(parser, userId);
20012                            }
20013                        }
20014                    } );
20015        } catch (Exception e) {
20016            if (DEBUG_BACKUP) {
20017                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20018            }
20019        }
20020    }
20021
20022    @Override
20023    public byte[] getIntentFilterVerificationBackup(int userId) {
20024        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20025            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20026        }
20027
20028        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20029        try {
20030            final XmlSerializer serializer = new FastXmlSerializer();
20031            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20032            serializer.startDocument(null, true);
20033            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20034
20035            synchronized (mPackages) {
20036                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20037            }
20038
20039            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20040            serializer.endDocument();
20041            serializer.flush();
20042        } catch (Exception e) {
20043            if (DEBUG_BACKUP) {
20044                Slog.e(TAG, "Unable to write default apps for backup", e);
20045            }
20046            return null;
20047        }
20048
20049        return dataStream.toByteArray();
20050    }
20051
20052    @Override
20053    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20054        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20055            throw new SecurityException("Only the system may call restorePreferredActivities()");
20056        }
20057
20058        try {
20059            final XmlPullParser parser = Xml.newPullParser();
20060            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20061            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20062                    new BlobXmlRestorer() {
20063                        @Override
20064                        public void apply(XmlPullParser parser, int userId)
20065                                throws XmlPullParserException, IOException {
20066                            synchronized (mPackages) {
20067                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20068                                mSettings.writeLPr();
20069                            }
20070                        }
20071                    } );
20072        } catch (Exception e) {
20073            if (DEBUG_BACKUP) {
20074                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20075            }
20076        }
20077    }
20078
20079    @Override
20080    public byte[] getPermissionGrantBackup(int userId) {
20081        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20082            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20083        }
20084
20085        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20086        try {
20087            final XmlSerializer serializer = new FastXmlSerializer();
20088            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20089            serializer.startDocument(null, true);
20090            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20091
20092            synchronized (mPackages) {
20093                serializeRuntimePermissionGrantsLPr(serializer, userId);
20094            }
20095
20096            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20097            serializer.endDocument();
20098            serializer.flush();
20099        } catch (Exception e) {
20100            if (DEBUG_BACKUP) {
20101                Slog.e(TAG, "Unable to write default apps for backup", e);
20102            }
20103            return null;
20104        }
20105
20106        return dataStream.toByteArray();
20107    }
20108
20109    @Override
20110    public void restorePermissionGrants(byte[] backup, int userId) {
20111        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20112            throw new SecurityException("Only the system may call restorePermissionGrants()");
20113        }
20114
20115        try {
20116            final XmlPullParser parser = Xml.newPullParser();
20117            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20118            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20119                    new BlobXmlRestorer() {
20120                        @Override
20121                        public void apply(XmlPullParser parser, int userId)
20122                                throws XmlPullParserException, IOException {
20123                            synchronized (mPackages) {
20124                                processRestoredPermissionGrantsLPr(parser, userId);
20125                            }
20126                        }
20127                    } );
20128        } catch (Exception e) {
20129            if (DEBUG_BACKUP) {
20130                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20131            }
20132        }
20133    }
20134
20135    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20136            throws IOException {
20137        serializer.startTag(null, TAG_ALL_GRANTS);
20138
20139        final int N = mSettings.mPackages.size();
20140        for (int i = 0; i < N; i++) {
20141            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20142            boolean pkgGrantsKnown = false;
20143
20144            PermissionsState packagePerms = ps.getPermissionsState();
20145
20146            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20147                final int grantFlags = state.getFlags();
20148                // only look at grants that are not system/policy fixed
20149                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20150                    final boolean isGranted = state.isGranted();
20151                    // And only back up the user-twiddled state bits
20152                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20153                        final String packageName = mSettings.mPackages.keyAt(i);
20154                        if (!pkgGrantsKnown) {
20155                            serializer.startTag(null, TAG_GRANT);
20156                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20157                            pkgGrantsKnown = true;
20158                        }
20159
20160                        final boolean userSet =
20161                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20162                        final boolean userFixed =
20163                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20164                        final boolean revoke =
20165                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20166
20167                        serializer.startTag(null, TAG_PERMISSION);
20168                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20169                        if (isGranted) {
20170                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20171                        }
20172                        if (userSet) {
20173                            serializer.attribute(null, ATTR_USER_SET, "true");
20174                        }
20175                        if (userFixed) {
20176                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20177                        }
20178                        if (revoke) {
20179                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20180                        }
20181                        serializer.endTag(null, TAG_PERMISSION);
20182                    }
20183                }
20184            }
20185
20186            if (pkgGrantsKnown) {
20187                serializer.endTag(null, TAG_GRANT);
20188            }
20189        }
20190
20191        serializer.endTag(null, TAG_ALL_GRANTS);
20192    }
20193
20194    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20195            throws XmlPullParserException, IOException {
20196        String pkgName = null;
20197        int outerDepth = parser.getDepth();
20198        int type;
20199        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20200                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20201            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20202                continue;
20203            }
20204
20205            final String tagName = parser.getName();
20206            if (tagName.equals(TAG_GRANT)) {
20207                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20208                if (DEBUG_BACKUP) {
20209                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20210                }
20211            } else if (tagName.equals(TAG_PERMISSION)) {
20212
20213                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20214                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20215
20216                int newFlagSet = 0;
20217                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20218                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20219                }
20220                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20221                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20222                }
20223                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20224                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20225                }
20226                if (DEBUG_BACKUP) {
20227                    Slog.v(TAG, "  + Restoring grant:"
20228                            + " pkg=" + pkgName
20229                            + " perm=" + permName
20230                            + " granted=" + isGranted
20231                            + " bits=0x" + Integer.toHexString(newFlagSet));
20232                }
20233                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20234                if (ps != null) {
20235                    // Already installed so we apply the grant immediately
20236                    if (DEBUG_BACKUP) {
20237                        Slog.v(TAG, "        + already installed; applying");
20238                    }
20239                    PermissionsState perms = ps.getPermissionsState();
20240                    BasePermission bp =
20241                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20242                    if (bp != null) {
20243                        if (isGranted) {
20244                            perms.grantRuntimePermission(bp, userId);
20245                        }
20246                        if (newFlagSet != 0) {
20247                            perms.updatePermissionFlags(
20248                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20249                        }
20250                    }
20251                } else {
20252                    // Need to wait for post-restore install to apply the grant
20253                    if (DEBUG_BACKUP) {
20254                        Slog.v(TAG, "        - not yet installed; saving for later");
20255                    }
20256                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20257                            isGranted, newFlagSet, userId);
20258                }
20259            } else {
20260                PackageManagerService.reportSettingsProblem(Log.WARN,
20261                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20262                XmlUtils.skipCurrentTag(parser);
20263            }
20264        }
20265
20266        scheduleWriteSettingsLocked();
20267        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20268    }
20269
20270    @Override
20271    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20272            int sourceUserId, int targetUserId, int flags) {
20273        mContext.enforceCallingOrSelfPermission(
20274                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20275        int callingUid = Binder.getCallingUid();
20276        enforceOwnerRights(ownerPackage, callingUid);
20277        PackageManagerServiceUtils.enforceShellRestriction(
20278                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20279        if (intentFilter.countActions() == 0) {
20280            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20281            return;
20282        }
20283        synchronized (mPackages) {
20284            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20285                    ownerPackage, targetUserId, flags);
20286            CrossProfileIntentResolver resolver =
20287                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20288            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20289            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20290            if (existing != null) {
20291                int size = existing.size();
20292                for (int i = 0; i < size; i++) {
20293                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20294                        return;
20295                    }
20296                }
20297            }
20298            resolver.addFilter(newFilter);
20299            scheduleWritePackageRestrictionsLocked(sourceUserId);
20300        }
20301    }
20302
20303    @Override
20304    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20305        mContext.enforceCallingOrSelfPermission(
20306                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20307        final int callingUid = Binder.getCallingUid();
20308        enforceOwnerRights(ownerPackage, callingUid);
20309        PackageManagerServiceUtils.enforceShellRestriction(
20310                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20311        synchronized (mPackages) {
20312            CrossProfileIntentResolver resolver =
20313                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20314            ArraySet<CrossProfileIntentFilter> set =
20315                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20316            for (CrossProfileIntentFilter filter : set) {
20317                if (filter.getOwnerPackage().equals(ownerPackage)) {
20318                    resolver.removeFilter(filter);
20319                }
20320            }
20321            scheduleWritePackageRestrictionsLocked(sourceUserId);
20322        }
20323    }
20324
20325    // Enforcing that callingUid is owning pkg on userId
20326    private void enforceOwnerRights(String pkg, int callingUid) {
20327        // The system owns everything.
20328        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20329            return;
20330        }
20331        final int callingUserId = UserHandle.getUserId(callingUid);
20332        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20333        if (pi == null) {
20334            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20335                    + callingUserId);
20336        }
20337        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20338            throw new SecurityException("Calling uid " + callingUid
20339                    + " does not own package " + pkg);
20340        }
20341    }
20342
20343    @Override
20344    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20345        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20346            return null;
20347        }
20348        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20349    }
20350
20351    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20352        UserManagerService ums = UserManagerService.getInstance();
20353        if (ums != null) {
20354            final UserInfo parent = ums.getProfileParent(userId);
20355            final int launcherUid = (parent != null) ? parent.id : userId;
20356            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20357            if (launcherComponent != null) {
20358                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20359                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20360                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20361                        .setPackage(launcherComponent.getPackageName());
20362                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20363            }
20364        }
20365    }
20366
20367    /**
20368     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20369     * then reports the most likely home activity or null if there are more than one.
20370     */
20371    private ComponentName getDefaultHomeActivity(int userId) {
20372        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20373        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20374        if (cn != null) {
20375            return cn;
20376        }
20377
20378        // Find the launcher with the highest priority and return that component if there are no
20379        // other home activity with the same priority.
20380        int lastPriority = Integer.MIN_VALUE;
20381        ComponentName lastComponent = null;
20382        final int size = allHomeCandidates.size();
20383        for (int i = 0; i < size; i++) {
20384            final ResolveInfo ri = allHomeCandidates.get(i);
20385            if (ri.priority > lastPriority) {
20386                lastComponent = ri.activityInfo.getComponentName();
20387                lastPriority = ri.priority;
20388            } else if (ri.priority == lastPriority) {
20389                // Two components found with same priority.
20390                lastComponent = null;
20391            }
20392        }
20393        return lastComponent;
20394    }
20395
20396    private Intent getHomeIntent() {
20397        Intent intent = new Intent(Intent.ACTION_MAIN);
20398        intent.addCategory(Intent.CATEGORY_HOME);
20399        intent.addCategory(Intent.CATEGORY_DEFAULT);
20400        return intent;
20401    }
20402
20403    private IntentFilter getHomeFilter() {
20404        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20405        filter.addCategory(Intent.CATEGORY_HOME);
20406        filter.addCategory(Intent.CATEGORY_DEFAULT);
20407        return filter;
20408    }
20409
20410    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20411            int userId) {
20412        Intent intent  = getHomeIntent();
20413        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20414                PackageManager.GET_META_DATA, userId);
20415        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20416                true, false, false, userId);
20417
20418        allHomeCandidates.clear();
20419        if (list != null) {
20420            for (ResolveInfo ri : list) {
20421                allHomeCandidates.add(ri);
20422            }
20423        }
20424        return (preferred == null || preferred.activityInfo == null)
20425                ? null
20426                : new ComponentName(preferred.activityInfo.packageName,
20427                        preferred.activityInfo.name);
20428    }
20429
20430    @Override
20431    public void setHomeActivity(ComponentName comp, int userId) {
20432        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20433            return;
20434        }
20435        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20436        getHomeActivitiesAsUser(homeActivities, userId);
20437
20438        boolean found = false;
20439
20440        final int size = homeActivities.size();
20441        final ComponentName[] set = new ComponentName[size];
20442        for (int i = 0; i < size; i++) {
20443            final ResolveInfo candidate = homeActivities.get(i);
20444            final ActivityInfo info = candidate.activityInfo;
20445            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20446            set[i] = activityName;
20447            if (!found && activityName.equals(comp)) {
20448                found = true;
20449            }
20450        }
20451        if (!found) {
20452            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20453                    + userId);
20454        }
20455        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20456                set, comp, userId);
20457    }
20458
20459    private @Nullable String getSetupWizardPackageName() {
20460        final Intent intent = new Intent(Intent.ACTION_MAIN);
20461        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20462
20463        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20464                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20465                        | MATCH_DISABLED_COMPONENTS,
20466                UserHandle.myUserId());
20467        if (matches.size() == 1) {
20468            return matches.get(0).getComponentInfo().packageName;
20469        } else {
20470            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20471                    + ": matches=" + matches);
20472            return null;
20473        }
20474    }
20475
20476    private @Nullable String getStorageManagerPackageName() {
20477        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20478
20479        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20480                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20481                        | MATCH_DISABLED_COMPONENTS,
20482                UserHandle.myUserId());
20483        if (matches.size() == 1) {
20484            return matches.get(0).getComponentInfo().packageName;
20485        } else {
20486            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20487                    + matches.size() + ": matches=" + matches);
20488            return null;
20489        }
20490    }
20491
20492    @Override
20493    public String getSystemTextClassifierPackageName() {
20494        return mContext.getString(R.string.config_defaultTextClassifierPackage);
20495    }
20496
20497    @Override
20498    public void setApplicationEnabledSetting(String appPackageName,
20499            int newState, int flags, int userId, String callingPackage) {
20500        if (!sUserManager.exists(userId)) return;
20501        if (callingPackage == null) {
20502            callingPackage = Integer.toString(Binder.getCallingUid());
20503        }
20504        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20505    }
20506
20507    @Override
20508    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20509        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20510        synchronized (mPackages) {
20511            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20512            if (pkgSetting != null) {
20513                pkgSetting.setUpdateAvailable(updateAvailable);
20514            }
20515        }
20516    }
20517
20518    @Override
20519    public void setComponentEnabledSetting(ComponentName componentName,
20520            int newState, int flags, int userId) {
20521        if (!sUserManager.exists(userId)) return;
20522        setEnabledSetting(componentName.getPackageName(),
20523                componentName.getClassName(), newState, flags, userId, null);
20524    }
20525
20526    private void setEnabledSetting(final String packageName, String className, int newState,
20527            final int flags, int userId, String callingPackage) {
20528        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20529              || newState == COMPONENT_ENABLED_STATE_ENABLED
20530              || newState == COMPONENT_ENABLED_STATE_DISABLED
20531              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20532              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20533            throw new IllegalArgumentException("Invalid new component state: "
20534                    + newState);
20535        }
20536        PackageSetting pkgSetting;
20537        final int callingUid = Binder.getCallingUid();
20538        final int permission;
20539        if (callingUid == Process.SYSTEM_UID) {
20540            permission = PackageManager.PERMISSION_GRANTED;
20541        } else {
20542            permission = mContext.checkCallingOrSelfPermission(
20543                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20544        }
20545        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20546                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20547        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20548        boolean sendNow = false;
20549        boolean isApp = (className == null);
20550        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20551        String componentName = isApp ? packageName : className;
20552        int packageUid = -1;
20553        ArrayList<String> components;
20554
20555        // reader
20556        synchronized (mPackages) {
20557            pkgSetting = mSettings.mPackages.get(packageName);
20558            if (pkgSetting == null) {
20559                if (!isCallerInstantApp) {
20560                    if (className == null) {
20561                        throw new IllegalArgumentException("Unknown package: " + packageName);
20562                    }
20563                    throw new IllegalArgumentException(
20564                            "Unknown component: " + packageName + "/" + className);
20565                } else {
20566                    // throw SecurityException to prevent leaking package information
20567                    throw new SecurityException(
20568                            "Attempt to change component state; "
20569                            + "pid=" + Binder.getCallingPid()
20570                            + ", uid=" + callingUid
20571                            + (className == null
20572                                    ? ", package=" + packageName
20573                                    : ", component=" + packageName + "/" + className));
20574                }
20575            }
20576        }
20577
20578        // Limit who can change which apps
20579        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20580            // Don't allow apps that don't have permission to modify other apps
20581            if (!allowedByPermission
20582                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20583                throw new SecurityException(
20584                        "Attempt to change component state; "
20585                        + "pid=" + Binder.getCallingPid()
20586                        + ", uid=" + callingUid
20587                        + (className == null
20588                                ? ", package=" + packageName
20589                                : ", component=" + packageName + "/" + className));
20590            }
20591            // Don't allow changing protected packages.
20592            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20593                throw new SecurityException("Cannot disable a protected package: " + packageName);
20594            }
20595        }
20596
20597        synchronized (mPackages) {
20598            if (callingUid == Process.SHELL_UID
20599                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20600                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20601                // unless it is a test package.
20602                int oldState = pkgSetting.getEnabled(userId);
20603                if (className == null
20604                        &&
20605                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20606                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20607                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20608                        &&
20609                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20610                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20611                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20612                    // ok
20613                } else {
20614                    throw new SecurityException(
20615                            "Shell cannot change component state for " + packageName + "/"
20616                                    + className + " to " + newState);
20617                }
20618            }
20619        }
20620        if (className == null) {
20621            // We're dealing with an application/package level state change
20622            synchronized (mPackages) {
20623                if (pkgSetting.getEnabled(userId) == newState) {
20624                    // Nothing to do
20625                    return;
20626                }
20627            }
20628            // If we're enabling a system stub, there's a little more work to do.
20629            // Prior to enabling the package, we need to decompress the APK(s) to the
20630            // data partition and then replace the version on the system partition.
20631            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20632            final boolean isSystemStub = deletedPkg.isStub
20633                    && deletedPkg.isSystem();
20634            if (isSystemStub
20635                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20636                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20637                final File codePath = decompressPackage(deletedPkg);
20638                if (codePath == null) {
20639                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20640                    return;
20641                }
20642                // TODO remove direct parsing of the package object during internal cleanup
20643                // of scan package
20644                // We need to call parse directly here for no other reason than we need
20645                // the new package in order to disable the old one [we use the information
20646                // for some internal optimization to optionally create a new package setting
20647                // object on replace]. However, we can't get the package from the scan
20648                // because the scan modifies live structures and we need to remove the
20649                // old [system] package from the system before a scan can be attempted.
20650                // Once scan is indempotent we can remove this parse and use the package
20651                // object we scanned, prior to adding it to package settings.
20652                final PackageParser pp = new PackageParser();
20653                pp.setSeparateProcesses(mSeparateProcesses);
20654                pp.setDisplayMetrics(mMetrics);
20655                pp.setCallback(mPackageParserCallback);
20656                final PackageParser.Package tmpPkg;
20657                try {
20658                    final @ParseFlags int parseFlags = mDefParseFlags
20659                            | PackageParser.PARSE_MUST_BE_APK
20660                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20661                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20662                } catch (PackageParserException e) {
20663                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20664                    return;
20665                }
20666                synchronized (mInstallLock) {
20667                    // Disable the stub and remove any package entries
20668                    removePackageLI(deletedPkg, true);
20669                    synchronized (mPackages) {
20670                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20671                    }
20672                    final PackageParser.Package pkg;
20673                    try (PackageFreezer freezer =
20674                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20675                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20676                                | PackageParser.PARSE_ENFORCE_CODE;
20677                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20678                                0 /*currentTime*/, null /*user*/);
20679                        prepareAppDataAfterInstallLIF(pkg);
20680                        synchronized (mPackages) {
20681                            try {
20682                                updateSharedLibrariesLPr(pkg, null);
20683                            } catch (PackageManagerException e) {
20684                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20685                            }
20686                            mPermissionManager.updatePermissions(
20687                                    pkg.packageName, pkg, true, mPackages.values(),
20688                                    mPermissionCallback);
20689                            mSettings.writeLPr();
20690                        }
20691                    } catch (PackageManagerException e) {
20692                        // Whoops! Something went wrong; try to roll back to the stub
20693                        Slog.w(TAG, "Failed to install compressed system package:"
20694                                + pkgSetting.name, e);
20695                        // Remove the failed install
20696                        removeCodePathLI(codePath);
20697
20698                        // Install the system package
20699                        try (PackageFreezer freezer =
20700                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20701                            synchronized (mPackages) {
20702                                // NOTE: The system package always needs to be enabled; even
20703                                // if it's for a compressed stub. If we don't, installing the
20704                                // system package fails during scan [scanning checks the disabled
20705                                // packages]. We will reverse this later, after we've "installed"
20706                                // the stub.
20707                                // This leaves us in a fragile state; the stub should never be
20708                                // enabled, so, cross your fingers and hope nothing goes wrong
20709                                // until we can disable the package later.
20710                                enableSystemPackageLPw(deletedPkg);
20711                            }
20712                            installPackageFromSystemLIF(deletedPkg.codePath,
20713                                    false /*isPrivileged*/, null /*allUserHandles*/,
20714                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20715                                    true /*writeSettings*/);
20716                        } catch (PackageManagerException pme) {
20717                            Slog.w(TAG, "Failed to restore system package:"
20718                                    + deletedPkg.packageName, pme);
20719                        } finally {
20720                            synchronized (mPackages) {
20721                                mSettings.disableSystemPackageLPw(
20722                                        deletedPkg.packageName, true /*replaced*/);
20723                                mSettings.writeLPr();
20724                            }
20725                        }
20726                        return;
20727                    }
20728                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20729                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20730                    mDexManager.notifyPackageUpdated(pkg.packageName,
20731                            pkg.baseCodePath, pkg.splitCodePaths);
20732                }
20733            }
20734            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20735                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20736                // Don't care about who enables an app.
20737                callingPackage = null;
20738            }
20739            synchronized (mPackages) {
20740                pkgSetting.setEnabled(newState, userId, callingPackage);
20741            }
20742        } else {
20743            synchronized (mPackages) {
20744                // We're dealing with a component level state change
20745                // First, verify that this is a valid class name.
20746                PackageParser.Package pkg = pkgSetting.pkg;
20747                if (pkg == null || !pkg.hasComponentClassName(className)) {
20748                    if (pkg != null &&
20749                            pkg.applicationInfo.targetSdkVersion >=
20750                                    Build.VERSION_CODES.JELLY_BEAN) {
20751                        throw new IllegalArgumentException("Component class " + className
20752                                + " does not exist in " + packageName);
20753                    } else {
20754                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20755                                + className + " does not exist in " + packageName);
20756                    }
20757                }
20758                switch (newState) {
20759                    case COMPONENT_ENABLED_STATE_ENABLED:
20760                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20761                            return;
20762                        }
20763                        break;
20764                    case COMPONENT_ENABLED_STATE_DISABLED:
20765                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20766                            return;
20767                        }
20768                        break;
20769                    case COMPONENT_ENABLED_STATE_DEFAULT:
20770                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20771                            return;
20772                        }
20773                        break;
20774                    default:
20775                        Slog.e(TAG, "Invalid new component state: " + newState);
20776                        return;
20777                }
20778            }
20779        }
20780        synchronized (mPackages) {
20781            scheduleWritePackageRestrictionsLocked(userId);
20782            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20783            final long callingId = Binder.clearCallingIdentity();
20784            try {
20785                updateInstantAppInstallerLocked(packageName);
20786            } finally {
20787                Binder.restoreCallingIdentity(callingId);
20788            }
20789            components = mPendingBroadcasts.get(userId, packageName);
20790            final boolean newPackage = components == null;
20791            if (newPackage) {
20792                components = new ArrayList<String>();
20793            }
20794            if (!components.contains(componentName)) {
20795                components.add(componentName);
20796            }
20797            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20798                sendNow = true;
20799                // Purge entry from pending broadcast list if another one exists already
20800                // since we are sending one right away.
20801                mPendingBroadcasts.remove(userId, packageName);
20802            } else {
20803                if (newPackage) {
20804                    mPendingBroadcasts.put(userId, packageName, components);
20805                }
20806                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20807                    // Schedule a message
20808                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20809                }
20810            }
20811        }
20812
20813        long callingId = Binder.clearCallingIdentity();
20814        try {
20815            if (sendNow) {
20816                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20817                sendPackageChangedBroadcast(packageName,
20818                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20819            }
20820        } finally {
20821            Binder.restoreCallingIdentity(callingId);
20822        }
20823    }
20824
20825    @Override
20826    public void flushPackageRestrictionsAsUser(int userId) {
20827        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20828            return;
20829        }
20830        if (!sUserManager.exists(userId)) {
20831            return;
20832        }
20833        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20834                false /* checkShell */, "flushPackageRestrictions");
20835        synchronized (mPackages) {
20836            mSettings.writePackageRestrictionsLPr(userId);
20837            mDirtyUsers.remove(userId);
20838            if (mDirtyUsers.isEmpty()) {
20839                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20840            }
20841        }
20842    }
20843
20844    private void sendPackageChangedBroadcast(String packageName,
20845            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20846        if (DEBUG_INSTALL)
20847            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20848                    + componentNames);
20849        Bundle extras = new Bundle(4);
20850        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20851        String nameList[] = new String[componentNames.size()];
20852        componentNames.toArray(nameList);
20853        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20854        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20855        extras.putInt(Intent.EXTRA_UID, packageUid);
20856        // If this is not reporting a change of the overall package, then only send it
20857        // to registered receivers.  We don't want to launch a swath of apps for every
20858        // little component state change.
20859        final int flags = !componentNames.contains(packageName)
20860                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20861        final int userId = UserHandle.getUserId(packageUid);
20862        final boolean isInstantApp = isInstantApp(packageName, userId);
20863        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20864        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20865        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20866                userIds, instantUserIds);
20867    }
20868
20869    @Override
20870    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20871        if (!sUserManager.exists(userId)) return;
20872        final int callingUid = Binder.getCallingUid();
20873        if (getInstantAppPackageName(callingUid) != null) {
20874            return;
20875        }
20876        final int permission = mContext.checkCallingOrSelfPermission(
20877                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20878        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20879        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20880                true /* requireFullPermission */, true /* checkShell */, "stop package");
20881        // writer
20882        synchronized (mPackages) {
20883            final PackageSetting ps = mSettings.mPackages.get(packageName);
20884            if (!filterAppAccessLPr(ps, callingUid, userId)
20885                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20886                            allowedByPermission, callingUid, userId)) {
20887                scheduleWritePackageRestrictionsLocked(userId);
20888            }
20889        }
20890    }
20891
20892    @Override
20893    public String getInstallerPackageName(String packageName) {
20894        final int callingUid = Binder.getCallingUid();
20895        synchronized (mPackages) {
20896            final PackageSetting ps = mSettings.mPackages.get(packageName);
20897            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20898                return null;
20899            }
20900            return mSettings.getInstallerPackageNameLPr(packageName);
20901        }
20902    }
20903
20904    public boolean isOrphaned(String packageName) {
20905        // reader
20906        synchronized (mPackages) {
20907            return mSettings.isOrphaned(packageName);
20908        }
20909    }
20910
20911    @Override
20912    public int getApplicationEnabledSetting(String packageName, int userId) {
20913        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20914        int callingUid = Binder.getCallingUid();
20915        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20916                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20917        // reader
20918        synchronized (mPackages) {
20919            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20920                return COMPONENT_ENABLED_STATE_DISABLED;
20921            }
20922            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20923        }
20924    }
20925
20926    @Override
20927    public int getComponentEnabledSetting(ComponentName component, int userId) {
20928        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20929        int callingUid = Binder.getCallingUid();
20930        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20931                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20932        synchronized (mPackages) {
20933            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20934                    component, TYPE_UNKNOWN, userId)) {
20935                return COMPONENT_ENABLED_STATE_DISABLED;
20936            }
20937            return mSettings.getComponentEnabledSettingLPr(component, userId);
20938        }
20939    }
20940
20941    @Override
20942    public void enterSafeMode() {
20943        enforceSystemOrRoot("Only the system can request entering safe mode");
20944
20945        if (!mSystemReady) {
20946            mSafeMode = true;
20947        }
20948    }
20949
20950    @Override
20951    public void systemReady() {
20952        enforceSystemOrRoot("Only the system can claim the system is ready");
20953
20954        mSystemReady = true;
20955        final ContentResolver resolver = mContext.getContentResolver();
20956        ContentObserver co = new ContentObserver(mHandler) {
20957            @Override
20958            public void onChange(boolean selfChange) {
20959                mWebInstantAppsDisabled =
20960                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20961                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20962            }
20963        };
20964        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20965                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20966                false, co, UserHandle.USER_SYSTEM);
20967        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
20968                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20969        co.onChange(true);
20970
20971        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20972        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20973        // it is done.
20974        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20975            @Override
20976            public void onChange(boolean selfChange) {
20977                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20978                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20979                        oobEnabled == 1 ? "true" : "false");
20980            }
20981        };
20982        mContext.getContentResolver().registerContentObserver(
20983                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20984                UserHandle.USER_SYSTEM);
20985        // At boot, restore the value from the setting, which persists across reboot.
20986        privAppOobObserver.onChange(true);
20987
20988        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20989        // disabled after already being started.
20990        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20991                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20992
20993        // Read the compatibilty setting when the system is ready.
20994        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20995                mContext.getContentResolver(),
20996                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20997        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20998        if (DEBUG_SETTINGS) {
20999            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21000        }
21001
21002        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21003
21004        synchronized (mPackages) {
21005            // Verify that all of the preferred activity components actually
21006            // exist.  It is possible for applications to be updated and at
21007            // that point remove a previously declared activity component that
21008            // had been set as a preferred activity.  We try to clean this up
21009            // the next time we encounter that preferred activity, but it is
21010            // possible for the user flow to never be able to return to that
21011            // situation so here we do a sanity check to make sure we haven't
21012            // left any junk around.
21013            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21014            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21015                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21016                removed.clear();
21017                for (PreferredActivity pa : pir.filterSet()) {
21018                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21019                        removed.add(pa);
21020                    }
21021                }
21022                if (removed.size() > 0) {
21023                    for (int r=0; r<removed.size(); r++) {
21024                        PreferredActivity pa = removed.get(r);
21025                        Slog.w(TAG, "Removing dangling preferred activity: "
21026                                + pa.mPref.mComponent);
21027                        pir.removeFilter(pa);
21028                    }
21029                    mSettings.writePackageRestrictionsLPr(
21030                            mSettings.mPreferredActivities.keyAt(i));
21031                }
21032            }
21033
21034            for (int userId : UserManagerService.getInstance().getUserIds()) {
21035                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21036                    grantPermissionsUserIds = ArrayUtils.appendInt(
21037                            grantPermissionsUserIds, userId);
21038                }
21039            }
21040        }
21041        sUserManager.systemReady();
21042        // If we upgraded grant all default permissions before kicking off.
21043        for (int userId : grantPermissionsUserIds) {
21044            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21045        }
21046
21047        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21048            // If we did not grant default permissions, we preload from this the
21049            // default permission exceptions lazily to ensure we don't hit the
21050            // disk on a new user creation.
21051            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21052        }
21053
21054        // Now that we've scanned all packages, and granted any default
21055        // permissions, ensure permissions are updated. Beware of dragons if you
21056        // try optimizing this.
21057        synchronized (mPackages) {
21058            mPermissionManager.updateAllPermissions(
21059                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
21060                    mPermissionCallback);
21061        }
21062
21063        // Kick off any messages waiting for system ready
21064        if (mPostSystemReadyMessages != null) {
21065            for (Message msg : mPostSystemReadyMessages) {
21066                msg.sendToTarget();
21067            }
21068            mPostSystemReadyMessages = null;
21069        }
21070
21071        // Watch for external volumes that come and go over time
21072        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21073        storage.registerListener(mStorageListener);
21074
21075        mInstallerService.systemReady();
21076        mPackageDexOptimizer.systemReady();
21077
21078        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21079                StorageManagerInternal.class);
21080        StorageManagerInternal.addExternalStoragePolicy(
21081                new StorageManagerInternal.ExternalStorageMountPolicy() {
21082            @Override
21083            public int getMountMode(int uid, String packageName) {
21084                if (Process.isIsolated(uid)) {
21085                    return Zygote.MOUNT_EXTERNAL_NONE;
21086                }
21087                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21088                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21089                }
21090                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21091                    return Zygote.MOUNT_EXTERNAL_READ;
21092                }
21093                return Zygote.MOUNT_EXTERNAL_WRITE;
21094            }
21095
21096            @Override
21097            public boolean hasExternalStorage(int uid, String packageName) {
21098                return true;
21099            }
21100        });
21101
21102        // Now that we're mostly running, clean up stale users and apps
21103        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21104        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21105
21106        mPermissionManager.systemReady();
21107
21108        if (mInstantAppResolverConnection != null) {
21109            mContext.registerReceiver(new BroadcastReceiver() {
21110                @Override
21111                public void onReceive(Context context, Intent intent) {
21112                    mInstantAppResolverConnection.optimisticBind();
21113                    mContext.unregisterReceiver(this);
21114                }
21115            }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
21116        }
21117    }
21118
21119    public void waitForAppDataPrepared() {
21120        if (mPrepareAppDataFuture == null) {
21121            return;
21122        }
21123        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21124        mPrepareAppDataFuture = null;
21125    }
21126
21127    @Override
21128    public boolean isSafeMode() {
21129        // allow instant applications
21130        return mSafeMode;
21131    }
21132
21133    @Override
21134    public boolean hasSystemUidErrors() {
21135        // allow instant applications
21136        return mHasSystemUidErrors;
21137    }
21138
21139    static String arrayToString(int[] array) {
21140        StringBuffer buf = new StringBuffer(128);
21141        buf.append('[');
21142        if (array != null) {
21143            for (int i=0; i<array.length; i++) {
21144                if (i > 0) buf.append(", ");
21145                buf.append(array[i]);
21146            }
21147        }
21148        buf.append(']');
21149        return buf.toString();
21150    }
21151
21152    @Override
21153    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21154            FileDescriptor err, String[] args, ShellCallback callback,
21155            ResultReceiver resultReceiver) {
21156        (new PackageManagerShellCommand(this)).exec(
21157                this, in, out, err, args, callback, resultReceiver);
21158    }
21159
21160    @Override
21161    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21162        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21163
21164        DumpState dumpState = new DumpState();
21165        boolean fullPreferred = false;
21166        boolean checkin = false;
21167
21168        String packageName = null;
21169        ArraySet<String> permissionNames = null;
21170
21171        int opti = 0;
21172        while (opti < args.length) {
21173            String opt = args[opti];
21174            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21175                break;
21176            }
21177            opti++;
21178
21179            if ("-a".equals(opt)) {
21180                // Right now we only know how to print all.
21181            } else if ("-h".equals(opt)) {
21182                pw.println("Package manager dump options:");
21183                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21184                pw.println("    --checkin: dump for a checkin");
21185                pw.println("    -f: print details of intent filters");
21186                pw.println("    -h: print this help");
21187                pw.println("  cmd may be one of:");
21188                pw.println("    l[ibraries]: list known shared libraries");
21189                pw.println("    f[eatures]: list device features");
21190                pw.println("    k[eysets]: print known keysets");
21191                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21192                pw.println("    perm[issions]: dump permissions");
21193                pw.println("    permission [name ...]: dump declaration and use of given permission");
21194                pw.println("    pref[erred]: print preferred package settings");
21195                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21196                pw.println("    prov[iders]: dump content providers");
21197                pw.println("    p[ackages]: dump installed packages");
21198                pw.println("    s[hared-users]: dump shared user IDs");
21199                pw.println("    m[essages]: print collected runtime messages");
21200                pw.println("    v[erifiers]: print package verifier info");
21201                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21202                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21203                pw.println("    version: print database version info");
21204                pw.println("    write: write current settings now");
21205                pw.println("    installs: details about install sessions");
21206                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21207                pw.println("    dexopt: dump dexopt state");
21208                pw.println("    compiler-stats: dump compiler statistics");
21209                pw.println("    service-permissions: dump permissions required by services");
21210                pw.println("    <package.name>: info about given package");
21211                return;
21212            } else if ("--checkin".equals(opt)) {
21213                checkin = true;
21214            } else if ("-f".equals(opt)) {
21215                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21216            } else if ("--proto".equals(opt)) {
21217                dumpProto(fd);
21218                return;
21219            } else {
21220                pw.println("Unknown argument: " + opt + "; use -h for help");
21221            }
21222        }
21223
21224        // Is the caller requesting to dump a particular piece of data?
21225        if (opti < args.length) {
21226            String cmd = args[opti];
21227            opti++;
21228            // Is this a package name?
21229            if ("android".equals(cmd) || cmd.contains(".")) {
21230                packageName = cmd;
21231                // When dumping a single package, we always dump all of its
21232                // filter information since the amount of data will be reasonable.
21233                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21234            } else if ("check-permission".equals(cmd)) {
21235                if (opti >= args.length) {
21236                    pw.println("Error: check-permission missing permission argument");
21237                    return;
21238                }
21239                String perm = args[opti];
21240                opti++;
21241                if (opti >= args.length) {
21242                    pw.println("Error: check-permission missing package argument");
21243                    return;
21244                }
21245
21246                String pkg = args[opti];
21247                opti++;
21248                int user = UserHandle.getUserId(Binder.getCallingUid());
21249                if (opti < args.length) {
21250                    try {
21251                        user = Integer.parseInt(args[opti]);
21252                    } catch (NumberFormatException e) {
21253                        pw.println("Error: check-permission user argument is not a number: "
21254                                + args[opti]);
21255                        return;
21256                    }
21257                }
21258
21259                // Normalize package name to handle renamed packages and static libs
21260                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21261
21262                pw.println(checkPermission(perm, pkg, user));
21263                return;
21264            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21265                dumpState.setDump(DumpState.DUMP_LIBS);
21266            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21267                dumpState.setDump(DumpState.DUMP_FEATURES);
21268            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21269                if (opti >= args.length) {
21270                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21271                            | DumpState.DUMP_SERVICE_RESOLVERS
21272                            | DumpState.DUMP_RECEIVER_RESOLVERS
21273                            | DumpState.DUMP_CONTENT_RESOLVERS);
21274                } else {
21275                    while (opti < args.length) {
21276                        String name = args[opti];
21277                        if ("a".equals(name) || "activity".equals(name)) {
21278                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21279                        } else if ("s".equals(name) || "service".equals(name)) {
21280                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21281                        } else if ("r".equals(name) || "receiver".equals(name)) {
21282                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21283                        } else if ("c".equals(name) || "content".equals(name)) {
21284                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21285                        } else {
21286                            pw.println("Error: unknown resolver table type: " + name);
21287                            return;
21288                        }
21289                        opti++;
21290                    }
21291                }
21292            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21293                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21294            } else if ("permission".equals(cmd)) {
21295                if (opti >= args.length) {
21296                    pw.println("Error: permission requires permission name");
21297                    return;
21298                }
21299                permissionNames = new ArraySet<>();
21300                while (opti < args.length) {
21301                    permissionNames.add(args[opti]);
21302                    opti++;
21303                }
21304                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21305                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21306            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21307                dumpState.setDump(DumpState.DUMP_PREFERRED);
21308            } else if ("preferred-xml".equals(cmd)) {
21309                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21310                if (opti < args.length && "--full".equals(args[opti])) {
21311                    fullPreferred = true;
21312                    opti++;
21313                }
21314            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21315                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21316            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21317                dumpState.setDump(DumpState.DUMP_PACKAGES);
21318            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21319                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21320            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21321                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21322            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21323                dumpState.setDump(DumpState.DUMP_MESSAGES);
21324            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21325                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21326            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21327                    || "intent-filter-verifiers".equals(cmd)) {
21328                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21329            } else if ("version".equals(cmd)) {
21330                dumpState.setDump(DumpState.DUMP_VERSION);
21331            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21332                dumpState.setDump(DumpState.DUMP_KEYSETS);
21333            } else if ("installs".equals(cmd)) {
21334                dumpState.setDump(DumpState.DUMP_INSTALLS);
21335            } else if ("frozen".equals(cmd)) {
21336                dumpState.setDump(DumpState.DUMP_FROZEN);
21337            } else if ("volumes".equals(cmd)) {
21338                dumpState.setDump(DumpState.DUMP_VOLUMES);
21339            } else if ("dexopt".equals(cmd)) {
21340                dumpState.setDump(DumpState.DUMP_DEXOPT);
21341            } else if ("compiler-stats".equals(cmd)) {
21342                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21343            } else if ("changes".equals(cmd)) {
21344                dumpState.setDump(DumpState.DUMP_CHANGES);
21345            } else if ("service-permissions".equals(cmd)) {
21346                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21347            } else if ("write".equals(cmd)) {
21348                synchronized (mPackages) {
21349                    mSettings.writeLPr();
21350                    pw.println("Settings written.");
21351                    return;
21352                }
21353            }
21354        }
21355
21356        if (checkin) {
21357            pw.println("vers,1");
21358        }
21359
21360        // reader
21361        synchronized (mPackages) {
21362            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21363                if (!checkin) {
21364                    if (dumpState.onTitlePrinted())
21365                        pw.println();
21366                    pw.println("Database versions:");
21367                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21368                }
21369            }
21370
21371            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21372                if (!checkin) {
21373                    if (dumpState.onTitlePrinted())
21374                        pw.println();
21375                    pw.println("Verifiers:");
21376                    pw.print("  Required: ");
21377                    pw.print(mRequiredVerifierPackage);
21378                    pw.print(" (uid=");
21379                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21380                            UserHandle.USER_SYSTEM));
21381                    pw.println(")");
21382                } else if (mRequiredVerifierPackage != null) {
21383                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21384                    pw.print(",");
21385                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21386                            UserHandle.USER_SYSTEM));
21387                }
21388            }
21389
21390            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21391                    packageName == null) {
21392                if (mIntentFilterVerifierComponent != null) {
21393                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21394                    if (!checkin) {
21395                        if (dumpState.onTitlePrinted())
21396                            pw.println();
21397                        pw.println("Intent Filter Verifier:");
21398                        pw.print("  Using: ");
21399                        pw.print(verifierPackageName);
21400                        pw.print(" (uid=");
21401                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21402                                UserHandle.USER_SYSTEM));
21403                        pw.println(")");
21404                    } else if (verifierPackageName != null) {
21405                        pw.print("ifv,"); pw.print(verifierPackageName);
21406                        pw.print(",");
21407                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21408                                UserHandle.USER_SYSTEM));
21409                    }
21410                } else {
21411                    pw.println();
21412                    pw.println("No Intent Filter Verifier available!");
21413                }
21414            }
21415
21416            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21417                boolean printedHeader = false;
21418                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21419                while (it.hasNext()) {
21420                    String libName = it.next();
21421                    LongSparseArray<SharedLibraryEntry> versionedLib
21422                            = mSharedLibraries.get(libName);
21423                    if (versionedLib == null) {
21424                        continue;
21425                    }
21426                    final int versionCount = versionedLib.size();
21427                    for (int i = 0; i < versionCount; i++) {
21428                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21429                        if (!checkin) {
21430                            if (!printedHeader) {
21431                                if (dumpState.onTitlePrinted())
21432                                    pw.println();
21433                                pw.println("Libraries:");
21434                                printedHeader = true;
21435                            }
21436                            pw.print("  ");
21437                        } else {
21438                            pw.print("lib,");
21439                        }
21440                        pw.print(libEntry.info.getName());
21441                        if (libEntry.info.isStatic()) {
21442                            pw.print(" version=" + libEntry.info.getLongVersion());
21443                        }
21444                        if (!checkin) {
21445                            pw.print(" -> ");
21446                        }
21447                        if (libEntry.path != null) {
21448                            pw.print(" (jar) ");
21449                            pw.print(libEntry.path);
21450                        } else {
21451                            pw.print(" (apk) ");
21452                            pw.print(libEntry.apk);
21453                        }
21454                        pw.println();
21455                    }
21456                }
21457            }
21458
21459            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21460                if (dumpState.onTitlePrinted())
21461                    pw.println();
21462                if (!checkin) {
21463                    pw.println("Features:");
21464                }
21465
21466                synchronized (mAvailableFeatures) {
21467                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21468                        if (checkin) {
21469                            pw.print("feat,");
21470                            pw.print(feat.name);
21471                            pw.print(",");
21472                            pw.println(feat.version);
21473                        } else {
21474                            pw.print("  ");
21475                            pw.print(feat.name);
21476                            if (feat.version > 0) {
21477                                pw.print(" version=");
21478                                pw.print(feat.version);
21479                            }
21480                            pw.println();
21481                        }
21482                    }
21483                }
21484            }
21485
21486            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21487                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21488                        : "Activity Resolver Table:", "  ", packageName,
21489                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21490                    dumpState.setTitlePrinted(true);
21491                }
21492            }
21493            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21494                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21495                        : "Receiver Resolver Table:", "  ", packageName,
21496                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21497                    dumpState.setTitlePrinted(true);
21498                }
21499            }
21500            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21501                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21502                        : "Service Resolver Table:", "  ", packageName,
21503                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21504                    dumpState.setTitlePrinted(true);
21505                }
21506            }
21507            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21508                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21509                        : "Provider Resolver Table:", "  ", packageName,
21510                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21511                    dumpState.setTitlePrinted(true);
21512                }
21513            }
21514
21515            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21516                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21517                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21518                    int user = mSettings.mPreferredActivities.keyAt(i);
21519                    if (pir.dump(pw,
21520                            dumpState.getTitlePrinted()
21521                                ? "\nPreferred Activities User " + user + ":"
21522                                : "Preferred Activities User " + user + ":", "  ",
21523                            packageName, true, false)) {
21524                        dumpState.setTitlePrinted(true);
21525                    }
21526                }
21527            }
21528
21529            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21530                pw.flush();
21531                FileOutputStream fout = new FileOutputStream(fd);
21532                BufferedOutputStream str = new BufferedOutputStream(fout);
21533                XmlSerializer serializer = new FastXmlSerializer();
21534                try {
21535                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21536                    serializer.startDocument(null, true);
21537                    serializer.setFeature(
21538                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21539                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21540                    serializer.endDocument();
21541                    serializer.flush();
21542                } catch (IllegalArgumentException e) {
21543                    pw.println("Failed writing: " + e);
21544                } catch (IllegalStateException e) {
21545                    pw.println("Failed writing: " + e);
21546                } catch (IOException e) {
21547                    pw.println("Failed writing: " + e);
21548                }
21549            }
21550
21551            if (!checkin
21552                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21553                    && packageName == null) {
21554                pw.println();
21555                int count = mSettings.mPackages.size();
21556                if (count == 0) {
21557                    pw.println("No applications!");
21558                    pw.println();
21559                } else {
21560                    final String prefix = "  ";
21561                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21562                    if (allPackageSettings.size() == 0) {
21563                        pw.println("No domain preferred apps!");
21564                        pw.println();
21565                    } else {
21566                        pw.println("App verification status:");
21567                        pw.println();
21568                        count = 0;
21569                        for (PackageSetting ps : allPackageSettings) {
21570                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21571                            if (ivi == null || ivi.getPackageName() == null) continue;
21572                            pw.println(prefix + "Package: " + ivi.getPackageName());
21573                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21574                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21575                            pw.println();
21576                            count++;
21577                        }
21578                        if (count == 0) {
21579                            pw.println(prefix + "No app verification established.");
21580                            pw.println();
21581                        }
21582                        for (int userId : sUserManager.getUserIds()) {
21583                            pw.println("App linkages for user " + userId + ":");
21584                            pw.println();
21585                            count = 0;
21586                            for (PackageSetting ps : allPackageSettings) {
21587                                final long status = ps.getDomainVerificationStatusForUser(userId);
21588                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21589                                        && !DEBUG_DOMAIN_VERIFICATION) {
21590                                    continue;
21591                                }
21592                                pw.println(prefix + "Package: " + ps.name);
21593                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21594                                String statusStr = IntentFilterVerificationInfo.
21595                                        getStatusStringFromValue(status);
21596                                pw.println(prefix + "Status:  " + statusStr);
21597                                pw.println();
21598                                count++;
21599                            }
21600                            if (count == 0) {
21601                                pw.println(prefix + "No configured app linkages.");
21602                                pw.println();
21603                            }
21604                        }
21605                    }
21606                }
21607            }
21608
21609            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21610                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21611            }
21612
21613            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21614                boolean printedSomething = false;
21615                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21616                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21617                        continue;
21618                    }
21619                    if (!printedSomething) {
21620                        if (dumpState.onTitlePrinted())
21621                            pw.println();
21622                        pw.println("Registered ContentProviders:");
21623                        printedSomething = true;
21624                    }
21625                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21626                    pw.print("    "); pw.println(p.toString());
21627                }
21628                printedSomething = false;
21629                for (Map.Entry<String, PackageParser.Provider> entry :
21630                        mProvidersByAuthority.entrySet()) {
21631                    PackageParser.Provider p = entry.getValue();
21632                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21633                        continue;
21634                    }
21635                    if (!printedSomething) {
21636                        if (dumpState.onTitlePrinted())
21637                            pw.println();
21638                        pw.println("ContentProvider Authorities:");
21639                        printedSomething = true;
21640                    }
21641                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21642                    pw.print("    "); pw.println(p.toString());
21643                    if (p.info != null && p.info.applicationInfo != null) {
21644                        final String appInfo = p.info.applicationInfo.toString();
21645                        pw.print("      applicationInfo="); pw.println(appInfo);
21646                    }
21647                }
21648            }
21649
21650            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21651                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21652            }
21653
21654            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21655                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21656            }
21657
21658            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21659                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21660            }
21661
21662            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21663                if (dumpState.onTitlePrinted()) pw.println();
21664                pw.println("Package Changes:");
21665                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21666                final int K = mChangedPackages.size();
21667                for (int i = 0; i < K; i++) {
21668                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21669                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21670                    final int N = changes.size();
21671                    if (N == 0) {
21672                        pw.print("    "); pw.println("No packages changed");
21673                    } else {
21674                        for (int j = 0; j < N; j++) {
21675                            final String pkgName = changes.valueAt(j);
21676                            final int sequenceNumber = changes.keyAt(j);
21677                            pw.print("    ");
21678                            pw.print("seq=");
21679                            pw.print(sequenceNumber);
21680                            pw.print(", package=");
21681                            pw.println(pkgName);
21682                        }
21683                    }
21684                }
21685            }
21686
21687            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21688                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21689            }
21690
21691            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21692                // XXX should handle packageName != null by dumping only install data that
21693                // the given package is involved with.
21694                if (dumpState.onTitlePrinted()) pw.println();
21695
21696                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21697                ipw.println();
21698                ipw.println("Frozen packages:");
21699                ipw.increaseIndent();
21700                if (mFrozenPackages.size() == 0) {
21701                    ipw.println("(none)");
21702                } else {
21703                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21704                        ipw.println(mFrozenPackages.valueAt(i));
21705                    }
21706                }
21707                ipw.decreaseIndent();
21708            }
21709
21710            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21711                if (dumpState.onTitlePrinted()) pw.println();
21712
21713                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21714                ipw.println();
21715                ipw.println("Loaded volumes:");
21716                ipw.increaseIndent();
21717                if (mLoadedVolumes.size() == 0) {
21718                    ipw.println("(none)");
21719                } else {
21720                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21721                        ipw.println(mLoadedVolumes.valueAt(i));
21722                    }
21723                }
21724                ipw.decreaseIndent();
21725            }
21726
21727            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21728                    && packageName == null) {
21729                if (dumpState.onTitlePrinted()) pw.println();
21730                pw.println("Service permissions:");
21731
21732                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21733                while (filterIterator.hasNext()) {
21734                    final ServiceIntentInfo info = filterIterator.next();
21735                    final ServiceInfo serviceInfo = info.service.info;
21736                    final String permission = serviceInfo.permission;
21737                    if (permission != null) {
21738                        pw.print("    ");
21739                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21740                        pw.print(": ");
21741                        pw.println(permission);
21742                    }
21743                }
21744            }
21745
21746            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21747                if (dumpState.onTitlePrinted()) pw.println();
21748                dumpDexoptStateLPr(pw, packageName);
21749            }
21750
21751            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21752                if (dumpState.onTitlePrinted()) pw.println();
21753                dumpCompilerStatsLPr(pw, packageName);
21754            }
21755
21756            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21757                if (dumpState.onTitlePrinted()) pw.println();
21758                mSettings.dumpReadMessagesLPr(pw, dumpState);
21759
21760                pw.println();
21761                pw.println("Package warning messages:");
21762                dumpCriticalInfo(pw, null);
21763            }
21764
21765            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21766                dumpCriticalInfo(pw, "msg,");
21767            }
21768        }
21769
21770        // PackageInstaller should be called outside of mPackages lock
21771        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21772            // XXX should handle packageName != null by dumping only install data that
21773            // the given package is involved with.
21774            if (dumpState.onTitlePrinted()) pw.println();
21775            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21776        }
21777    }
21778
21779    private void dumpProto(FileDescriptor fd) {
21780        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21781
21782        synchronized (mPackages) {
21783            final long requiredVerifierPackageToken =
21784                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21785            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21786            proto.write(
21787                    PackageServiceDumpProto.PackageShortProto.UID,
21788                    getPackageUid(
21789                            mRequiredVerifierPackage,
21790                            MATCH_DEBUG_TRIAGED_MISSING,
21791                            UserHandle.USER_SYSTEM));
21792            proto.end(requiredVerifierPackageToken);
21793
21794            if (mIntentFilterVerifierComponent != null) {
21795                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21796                final long verifierPackageToken =
21797                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21798                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21799                proto.write(
21800                        PackageServiceDumpProto.PackageShortProto.UID,
21801                        getPackageUid(
21802                                verifierPackageName,
21803                                MATCH_DEBUG_TRIAGED_MISSING,
21804                                UserHandle.USER_SYSTEM));
21805                proto.end(verifierPackageToken);
21806            }
21807
21808            dumpSharedLibrariesProto(proto);
21809            dumpFeaturesProto(proto);
21810            mSettings.dumpPackagesProto(proto);
21811            mSettings.dumpSharedUsersProto(proto);
21812            dumpCriticalInfo(proto);
21813        }
21814        proto.flush();
21815    }
21816
21817    private void dumpFeaturesProto(ProtoOutputStream proto) {
21818        synchronized (mAvailableFeatures) {
21819            final int count = mAvailableFeatures.size();
21820            for (int i = 0; i < count; i++) {
21821                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21822            }
21823        }
21824    }
21825
21826    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21827        final int count = mSharedLibraries.size();
21828        for (int i = 0; i < count; i++) {
21829            final String libName = mSharedLibraries.keyAt(i);
21830            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21831            if (versionedLib == null) {
21832                continue;
21833            }
21834            final int versionCount = versionedLib.size();
21835            for (int j = 0; j < versionCount; j++) {
21836                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21837                final long sharedLibraryToken =
21838                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21839                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21840                final boolean isJar = (libEntry.path != null);
21841                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21842                if (isJar) {
21843                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21844                } else {
21845                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21846                }
21847                proto.end(sharedLibraryToken);
21848            }
21849        }
21850    }
21851
21852    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21853        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21854        ipw.println();
21855        ipw.println("Dexopt state:");
21856        ipw.increaseIndent();
21857        Collection<PackageParser.Package> packages = null;
21858        if (packageName != null) {
21859            PackageParser.Package targetPackage = mPackages.get(packageName);
21860            if (targetPackage != null) {
21861                packages = Collections.singletonList(targetPackage);
21862            } else {
21863                ipw.println("Unable to find package: " + packageName);
21864                return;
21865            }
21866        } else {
21867            packages = mPackages.values();
21868        }
21869
21870        for (PackageParser.Package pkg : packages) {
21871            ipw.println("[" + pkg.packageName + "]");
21872            ipw.increaseIndent();
21873            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21874                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21875            ipw.decreaseIndent();
21876        }
21877    }
21878
21879    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21880        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21881        ipw.println();
21882        ipw.println("Compiler stats:");
21883        ipw.increaseIndent();
21884        Collection<PackageParser.Package> packages = null;
21885        if (packageName != null) {
21886            PackageParser.Package targetPackage = mPackages.get(packageName);
21887            if (targetPackage != null) {
21888                packages = Collections.singletonList(targetPackage);
21889            } else {
21890                ipw.println("Unable to find package: " + packageName);
21891                return;
21892            }
21893        } else {
21894            packages = mPackages.values();
21895        }
21896
21897        for (PackageParser.Package pkg : packages) {
21898            ipw.println("[" + pkg.packageName + "]");
21899            ipw.increaseIndent();
21900
21901            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21902            if (stats == null) {
21903                ipw.println("(No recorded stats)");
21904            } else {
21905                stats.dump(ipw);
21906            }
21907            ipw.decreaseIndent();
21908        }
21909    }
21910
21911    private String dumpDomainString(String packageName) {
21912        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21913                .getList();
21914        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21915
21916        ArraySet<String> result = new ArraySet<>();
21917        if (iviList.size() > 0) {
21918            for (IntentFilterVerificationInfo ivi : iviList) {
21919                for (String host : ivi.getDomains()) {
21920                    result.add(host);
21921                }
21922            }
21923        }
21924        if (filters != null && filters.size() > 0) {
21925            for (IntentFilter filter : filters) {
21926                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21927                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21928                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21929                    result.addAll(filter.getHostsList());
21930                }
21931            }
21932        }
21933
21934        StringBuilder sb = new StringBuilder(result.size() * 16);
21935        for (String domain : result) {
21936            if (sb.length() > 0) sb.append(" ");
21937            sb.append(domain);
21938        }
21939        return sb.toString();
21940    }
21941
21942    // ------- apps on sdcard specific code -------
21943    static final boolean DEBUG_SD_INSTALL = false;
21944
21945    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21946
21947    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21948
21949    private boolean mMediaMounted = false;
21950
21951    static String getEncryptKey() {
21952        try {
21953            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21954                    SD_ENCRYPTION_KEYSTORE_NAME);
21955            if (sdEncKey == null) {
21956                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21957                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21958                if (sdEncKey == null) {
21959                    Slog.e(TAG, "Failed to create encryption keys");
21960                    return null;
21961                }
21962            }
21963            return sdEncKey;
21964        } catch (NoSuchAlgorithmException nsae) {
21965            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21966            return null;
21967        } catch (IOException ioe) {
21968            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21969            return null;
21970        }
21971    }
21972
21973    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21974            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21975        final int size = infos.size();
21976        final String[] packageNames = new String[size];
21977        final int[] packageUids = new int[size];
21978        for (int i = 0; i < size; i++) {
21979            final ApplicationInfo info = infos.get(i);
21980            packageNames[i] = info.packageName;
21981            packageUids[i] = info.uid;
21982        }
21983        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21984                finishedReceiver);
21985    }
21986
21987    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21988            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21989        sendResourcesChangedBroadcast(mediaStatus, replacing,
21990                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21991    }
21992
21993    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21994            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21995        int size = pkgList.length;
21996        if (size > 0) {
21997            // Send broadcasts here
21998            Bundle extras = new Bundle();
21999            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22000            if (uidArr != null) {
22001                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22002            }
22003            if (replacing) {
22004                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22005            }
22006            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22007                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22008            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
22009        }
22010    }
22011
22012    private void loadPrivatePackages(final VolumeInfo vol) {
22013        mHandler.post(new Runnable() {
22014            @Override
22015            public void run() {
22016                loadPrivatePackagesInner(vol);
22017            }
22018        });
22019    }
22020
22021    private void loadPrivatePackagesInner(VolumeInfo vol) {
22022        final String volumeUuid = vol.fsUuid;
22023        if (TextUtils.isEmpty(volumeUuid)) {
22024            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22025            return;
22026        }
22027
22028        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22029        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22030        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22031
22032        final VersionInfo ver;
22033        final List<PackageSetting> packages;
22034        synchronized (mPackages) {
22035            ver = mSettings.findOrCreateVersion(volumeUuid);
22036            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22037        }
22038
22039        for (PackageSetting ps : packages) {
22040            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22041            synchronized (mInstallLock) {
22042                final PackageParser.Package pkg;
22043                try {
22044                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22045                    loaded.add(pkg.applicationInfo);
22046
22047                } catch (PackageManagerException e) {
22048                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22049                }
22050
22051                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22052                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22053                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22054                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22055                }
22056            }
22057        }
22058
22059        // Reconcile app data for all started/unlocked users
22060        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22061        final UserManager um = mContext.getSystemService(UserManager.class);
22062        UserManagerInternal umInternal = getUserManagerInternal();
22063        for (UserInfo user : um.getUsers()) {
22064            final int flags;
22065            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22066                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22067            } else if (umInternal.isUserRunning(user.id)) {
22068                flags = StorageManager.FLAG_STORAGE_DE;
22069            } else {
22070                continue;
22071            }
22072
22073            try {
22074                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22075                synchronized (mInstallLock) {
22076                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22077                }
22078            } catch (IllegalStateException e) {
22079                // Device was probably ejected, and we'll process that event momentarily
22080                Slog.w(TAG, "Failed to prepare storage: " + e);
22081            }
22082        }
22083
22084        synchronized (mPackages) {
22085            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
22086            if (sdkUpdated) {
22087                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22088                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22089            }
22090            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
22091                    mPermissionCallback);
22092
22093            // Yay, everything is now upgraded
22094            ver.forceCurrent();
22095
22096            mSettings.writeLPr();
22097        }
22098
22099        for (PackageFreezer freezer : freezers) {
22100            freezer.close();
22101        }
22102
22103        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22104        sendResourcesChangedBroadcast(true, false, loaded, null);
22105        mLoadedVolumes.add(vol.getId());
22106    }
22107
22108    private void unloadPrivatePackages(final VolumeInfo vol) {
22109        mHandler.post(new Runnable() {
22110            @Override
22111            public void run() {
22112                unloadPrivatePackagesInner(vol);
22113            }
22114        });
22115    }
22116
22117    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22118        final String volumeUuid = vol.fsUuid;
22119        if (TextUtils.isEmpty(volumeUuid)) {
22120            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22121            return;
22122        }
22123
22124        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22125        synchronized (mInstallLock) {
22126        synchronized (mPackages) {
22127            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22128            for (PackageSetting ps : packages) {
22129                if (ps.pkg == null) continue;
22130
22131                final ApplicationInfo info = ps.pkg.applicationInfo;
22132                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22133                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22134
22135                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22136                        "unloadPrivatePackagesInner")) {
22137                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22138                            false, null)) {
22139                        unloaded.add(info);
22140                    } else {
22141                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22142                    }
22143                }
22144
22145                // Try very hard to release any references to this package
22146                // so we don't risk the system server being killed due to
22147                // open FDs
22148                AttributeCache.instance().removePackage(ps.name);
22149            }
22150
22151            mSettings.writeLPr();
22152        }
22153        }
22154
22155        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22156        sendResourcesChangedBroadcast(false, false, unloaded, null);
22157        mLoadedVolumes.remove(vol.getId());
22158
22159        // Try very hard to release any references to this path so we don't risk
22160        // the system server being killed due to open FDs
22161        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22162
22163        for (int i = 0; i < 3; i++) {
22164            System.gc();
22165            System.runFinalization();
22166        }
22167    }
22168
22169    private void assertPackageKnown(String volumeUuid, String packageName)
22170            throws PackageManagerException {
22171        synchronized (mPackages) {
22172            // Normalize package name to handle renamed packages
22173            packageName = normalizePackageNameLPr(packageName);
22174
22175            final PackageSetting ps = mSettings.mPackages.get(packageName);
22176            if (ps == null) {
22177                throw new PackageManagerException("Package " + packageName + " is unknown");
22178            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22179                throw new PackageManagerException(
22180                        "Package " + packageName + " found on unknown volume " + volumeUuid
22181                                + "; expected volume " + ps.volumeUuid);
22182            }
22183        }
22184    }
22185
22186    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22187            throws PackageManagerException {
22188        synchronized (mPackages) {
22189            // Normalize package name to handle renamed packages
22190            packageName = normalizePackageNameLPr(packageName);
22191
22192            final PackageSetting ps = mSettings.mPackages.get(packageName);
22193            if (ps == null) {
22194                throw new PackageManagerException("Package " + packageName + " is unknown");
22195            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22196                throw new PackageManagerException(
22197                        "Package " + packageName + " found on unknown volume " + volumeUuid
22198                                + "; expected volume " + ps.volumeUuid);
22199            } else if (!ps.getInstalled(userId)) {
22200                throw new PackageManagerException(
22201                        "Package " + packageName + " not installed for user " + userId);
22202            }
22203        }
22204    }
22205
22206    private List<String> collectAbsoluteCodePaths() {
22207        synchronized (mPackages) {
22208            List<String> codePaths = new ArrayList<>();
22209            final int packageCount = mSettings.mPackages.size();
22210            for (int i = 0; i < packageCount; i++) {
22211                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22212                codePaths.add(ps.codePath.getAbsolutePath());
22213            }
22214            return codePaths;
22215        }
22216    }
22217
22218    /**
22219     * Examine all apps present on given mounted volume, and destroy apps that
22220     * aren't expected, either due to uninstallation or reinstallation on
22221     * another volume.
22222     */
22223    private void reconcileApps(String volumeUuid) {
22224        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22225        List<File> filesToDelete = null;
22226
22227        final File[] files = FileUtils.listFilesOrEmpty(
22228                Environment.getDataAppDirectory(volumeUuid));
22229        for (File file : files) {
22230            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22231                    && !PackageInstallerService.isStageName(file.getName());
22232            if (!isPackage) {
22233                // Ignore entries which are not packages
22234                continue;
22235            }
22236
22237            String absolutePath = file.getAbsolutePath();
22238
22239            boolean pathValid = false;
22240            final int absoluteCodePathCount = absoluteCodePaths.size();
22241            for (int i = 0; i < absoluteCodePathCount; i++) {
22242                String absoluteCodePath = absoluteCodePaths.get(i);
22243                if (absolutePath.startsWith(absoluteCodePath)) {
22244                    pathValid = true;
22245                    break;
22246                }
22247            }
22248
22249            if (!pathValid) {
22250                if (filesToDelete == null) {
22251                    filesToDelete = new ArrayList<>();
22252                }
22253                filesToDelete.add(file);
22254            }
22255        }
22256
22257        if (filesToDelete != null) {
22258            final int fileToDeleteCount = filesToDelete.size();
22259            for (int i = 0; i < fileToDeleteCount; i++) {
22260                File fileToDelete = filesToDelete.get(i);
22261                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22262                synchronized (mInstallLock) {
22263                    removeCodePathLI(fileToDelete);
22264                }
22265            }
22266        }
22267    }
22268
22269    /**
22270     * Reconcile all app data for the given user.
22271     * <p>
22272     * Verifies that directories exist and that ownership and labeling is
22273     * correct for all installed apps on all mounted volumes.
22274     */
22275    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22276        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22277        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22278            final String volumeUuid = vol.getFsUuid();
22279            synchronized (mInstallLock) {
22280                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22281            }
22282        }
22283    }
22284
22285    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22286            boolean migrateAppData) {
22287        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22288    }
22289
22290    /**
22291     * Reconcile all app data on given mounted volume.
22292     * <p>
22293     * Destroys app data that isn't expected, either due to uninstallation or
22294     * reinstallation on another volume.
22295     * <p>
22296     * Verifies that directories exist and that ownership and labeling is
22297     * correct for all installed apps.
22298     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22299     */
22300    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22301            boolean migrateAppData, boolean onlyCoreApps) {
22302        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22303                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22304        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22305
22306        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22307        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22308
22309        // First look for stale data that doesn't belong, and check if things
22310        // have changed since we did our last restorecon
22311        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22312            if (StorageManager.isFileEncryptedNativeOrEmulated()
22313                    && !StorageManager.isUserKeyUnlocked(userId)) {
22314                throw new RuntimeException(
22315                        "Yikes, someone asked us to reconcile CE storage while " + userId
22316                                + " was still locked; this would have caused massive data loss!");
22317            }
22318
22319            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22320            for (File file : files) {
22321                final String packageName = file.getName();
22322                try {
22323                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22324                } catch (PackageManagerException e) {
22325                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22326                    try {
22327                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22328                                StorageManager.FLAG_STORAGE_CE, 0);
22329                    } catch (InstallerException e2) {
22330                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22331                    }
22332                }
22333            }
22334        }
22335        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22336            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22337            for (File file : files) {
22338                final String packageName = file.getName();
22339                try {
22340                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22341                } catch (PackageManagerException e) {
22342                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22343                    try {
22344                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22345                                StorageManager.FLAG_STORAGE_DE, 0);
22346                    } catch (InstallerException e2) {
22347                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22348                    }
22349                }
22350            }
22351        }
22352
22353        // Ensure that data directories are ready to roll for all packages
22354        // installed for this volume and user
22355        final List<PackageSetting> packages;
22356        synchronized (mPackages) {
22357            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22358        }
22359        int preparedCount = 0;
22360        for (PackageSetting ps : packages) {
22361            final String packageName = ps.name;
22362            if (ps.pkg == null) {
22363                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22364                // TODO: might be due to legacy ASEC apps; we should circle back
22365                // and reconcile again once they're scanned
22366                continue;
22367            }
22368            // Skip non-core apps if requested
22369            if (onlyCoreApps && !ps.pkg.coreApp) {
22370                result.add(packageName);
22371                continue;
22372            }
22373
22374            if (ps.getInstalled(userId)) {
22375                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22376                preparedCount++;
22377            }
22378        }
22379
22380        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22381        return result;
22382    }
22383
22384    /**
22385     * Prepare app data for the given app just after it was installed or
22386     * upgraded. This method carefully only touches users that it's installed
22387     * for, and it forces a restorecon to handle any seinfo changes.
22388     * <p>
22389     * Verifies that directories exist and that ownership and labeling is
22390     * correct for all installed apps. If there is an ownership mismatch, it
22391     * will try recovering system apps by wiping data; third-party app data is
22392     * left intact.
22393     * <p>
22394     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22395     */
22396    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22397        final PackageSetting ps;
22398        synchronized (mPackages) {
22399            ps = mSettings.mPackages.get(pkg.packageName);
22400            mSettings.writeKernelMappingLPr(ps);
22401        }
22402
22403        final UserManager um = mContext.getSystemService(UserManager.class);
22404        UserManagerInternal umInternal = getUserManagerInternal();
22405        for (UserInfo user : um.getUsers()) {
22406            final int flags;
22407            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22408                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22409            } else if (umInternal.isUserRunning(user.id)) {
22410                flags = StorageManager.FLAG_STORAGE_DE;
22411            } else {
22412                continue;
22413            }
22414
22415            if (ps.getInstalled(user.id)) {
22416                // TODO: when user data is locked, mark that we're still dirty
22417                prepareAppDataLIF(pkg, user.id, flags);
22418            }
22419        }
22420    }
22421
22422    /**
22423     * Prepare app data for the given app.
22424     * <p>
22425     * Verifies that directories exist and that ownership and labeling is
22426     * correct for all installed apps. If there is an ownership mismatch, this
22427     * will try recovering system apps by wiping data; third-party app data is
22428     * left intact.
22429     */
22430    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22431        if (pkg == null) {
22432            Slog.wtf(TAG, "Package was null!", new Throwable());
22433            return;
22434        }
22435        prepareAppDataLeafLIF(pkg, userId, flags);
22436        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22437        for (int i = 0; i < childCount; i++) {
22438            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22439        }
22440    }
22441
22442    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22443            boolean maybeMigrateAppData) {
22444        prepareAppDataLIF(pkg, userId, flags);
22445
22446        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22447            // We may have just shuffled around app data directories, so
22448            // prepare them one more time
22449            prepareAppDataLIF(pkg, userId, flags);
22450        }
22451    }
22452
22453    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22454        if (DEBUG_APP_DATA) {
22455            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22456                    + Integer.toHexString(flags));
22457        }
22458
22459        final PackageSetting ps;
22460        synchronized (mPackages) {
22461            ps = mSettings.mPackages.get(pkg.packageName);
22462        }
22463        final String volumeUuid = pkg.volumeUuid;
22464        final String packageName = pkg.packageName;
22465        final ApplicationInfo app = (ps == null)
22466                ? pkg.applicationInfo
22467                : PackageParser.generateApplicationInfo(pkg, 0, ps.readUserState(userId), userId);
22468
22469        final int appId = UserHandle.getAppId(app.uid);
22470
22471        Preconditions.checkNotNull(app.seInfo);
22472
22473        final String seInfo = app.seInfo + (app.seInfoUser != null ? app.seInfoUser : "");
22474        long ceDataInode = -1;
22475        try {
22476            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22477                    appId, seInfo, app.targetSdkVersion);
22478        } catch (InstallerException e) {
22479            if (app.isSystemApp()) {
22480                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22481                        + ", but trying to recover: " + e);
22482                destroyAppDataLeafLIF(pkg, userId, flags);
22483                try {
22484                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22485                            appId, seInfo, app.targetSdkVersion);
22486                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22487                } catch (InstallerException e2) {
22488                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22489                }
22490            } else {
22491                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22492            }
22493        }
22494        // Prepare the application profiles only for upgrades and first boot (so that we don't
22495        // repeat the same operation at each boot).
22496        // We only have to cover the upgrade and first boot here because for app installs we
22497        // prepare the profiles before invoking dexopt (in installPackageLI).
22498        //
22499        // We also have to cover non system users because we do not call the usual install package
22500        // methods for them.
22501        if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) {
22502            mArtManagerService.prepareAppProfiles(pkg, userId);
22503        }
22504
22505        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22506            // TODO: mark this structure as dirty so we persist it!
22507            synchronized (mPackages) {
22508                if (ps != null) {
22509                    ps.setCeDataInode(ceDataInode, userId);
22510                }
22511            }
22512        }
22513
22514        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22515    }
22516
22517    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22518        if (pkg == null) {
22519            Slog.wtf(TAG, "Package was null!", new Throwable());
22520            return;
22521        }
22522        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22523        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22524        for (int i = 0; i < childCount; i++) {
22525            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22526        }
22527    }
22528
22529    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22530        final String volumeUuid = pkg.volumeUuid;
22531        final String packageName = pkg.packageName;
22532        final ApplicationInfo app = pkg.applicationInfo;
22533
22534        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22535            // Create a native library symlink only if we have native libraries
22536            // and if the native libraries are 32 bit libraries. We do not provide
22537            // this symlink for 64 bit libraries.
22538            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22539                final String nativeLibPath = app.nativeLibraryDir;
22540                try {
22541                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22542                            nativeLibPath, userId);
22543                } catch (InstallerException e) {
22544                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22545                }
22546            }
22547        }
22548    }
22549
22550    /**
22551     * For system apps on non-FBE devices, this method migrates any existing
22552     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22553     * requested by the app.
22554     */
22555    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22556        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22557                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22558            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22559                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22560            try {
22561                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22562                        storageTarget);
22563            } catch (InstallerException e) {
22564                logCriticalInfo(Log.WARN,
22565                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22566            }
22567            return true;
22568        } else {
22569            return false;
22570        }
22571    }
22572
22573    public PackageFreezer freezePackage(String packageName, String killReason) {
22574        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22575    }
22576
22577    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22578        return new PackageFreezer(packageName, userId, killReason);
22579    }
22580
22581    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22582            String killReason) {
22583        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22584    }
22585
22586    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22587            String killReason) {
22588        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22589            return new PackageFreezer();
22590        } else {
22591            return freezePackage(packageName, userId, killReason);
22592        }
22593    }
22594
22595    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22596            String killReason) {
22597        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22598    }
22599
22600    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22601            String killReason) {
22602        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22603            return new PackageFreezer();
22604        } else {
22605            return freezePackage(packageName, userId, killReason);
22606        }
22607    }
22608
22609    /**
22610     * Class that freezes and kills the given package upon creation, and
22611     * unfreezes it upon closing. This is typically used when doing surgery on
22612     * app code/data to prevent the app from running while you're working.
22613     */
22614    private class PackageFreezer implements AutoCloseable {
22615        private final String mPackageName;
22616        private final PackageFreezer[] mChildren;
22617
22618        private final boolean mWeFroze;
22619
22620        private final AtomicBoolean mClosed = new AtomicBoolean();
22621        private final CloseGuard mCloseGuard = CloseGuard.get();
22622
22623        /**
22624         * Create and return a stub freezer that doesn't actually do anything,
22625         * typically used when someone requested
22626         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22627         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22628         */
22629        public PackageFreezer() {
22630            mPackageName = null;
22631            mChildren = null;
22632            mWeFroze = false;
22633            mCloseGuard.open("close");
22634        }
22635
22636        public PackageFreezer(String packageName, int userId, String killReason) {
22637            synchronized (mPackages) {
22638                mPackageName = packageName;
22639                mWeFroze = mFrozenPackages.add(mPackageName);
22640
22641                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22642                if (ps != null) {
22643                    killApplication(ps.name, ps.appId, userId, killReason);
22644                }
22645
22646                final PackageParser.Package p = mPackages.get(packageName);
22647                if (p != null && p.childPackages != null) {
22648                    final int N = p.childPackages.size();
22649                    mChildren = new PackageFreezer[N];
22650                    for (int i = 0; i < N; i++) {
22651                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22652                                userId, killReason);
22653                    }
22654                } else {
22655                    mChildren = null;
22656                }
22657            }
22658            mCloseGuard.open("close");
22659        }
22660
22661        @Override
22662        protected void finalize() throws Throwable {
22663            try {
22664                if (mCloseGuard != null) {
22665                    mCloseGuard.warnIfOpen();
22666                }
22667
22668                close();
22669            } finally {
22670                super.finalize();
22671            }
22672        }
22673
22674        @Override
22675        public void close() {
22676            mCloseGuard.close();
22677            if (mClosed.compareAndSet(false, true)) {
22678                synchronized (mPackages) {
22679                    if (mWeFroze) {
22680                        mFrozenPackages.remove(mPackageName);
22681                    }
22682
22683                    if (mChildren != null) {
22684                        for (PackageFreezer freezer : mChildren) {
22685                            freezer.close();
22686                        }
22687                    }
22688                }
22689            }
22690        }
22691    }
22692
22693    /**
22694     * Verify that given package is currently frozen.
22695     */
22696    private void checkPackageFrozen(String packageName) {
22697        synchronized (mPackages) {
22698            if (!mFrozenPackages.contains(packageName)) {
22699                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22700            }
22701        }
22702    }
22703
22704    @Override
22705    public int movePackage(final String packageName, final String volumeUuid) {
22706        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22707
22708        final int callingUid = Binder.getCallingUid();
22709        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22710        final int moveId = mNextMoveId.getAndIncrement();
22711        mHandler.post(new Runnable() {
22712            @Override
22713            public void run() {
22714                try {
22715                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22716                } catch (PackageManagerException e) {
22717                    Slog.w(TAG, "Failed to move " + packageName, e);
22718                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22719                }
22720            }
22721        });
22722        return moveId;
22723    }
22724
22725    private void movePackageInternal(final String packageName, final String volumeUuid,
22726            final int moveId, final int callingUid, UserHandle user)
22727                    throws PackageManagerException {
22728        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22729        final PackageManager pm = mContext.getPackageManager();
22730
22731        final boolean currentAsec;
22732        final String currentVolumeUuid;
22733        final File codeFile;
22734        final String installerPackageName;
22735        final String packageAbiOverride;
22736        final int appId;
22737        final String seinfo;
22738        final String label;
22739        final int targetSdkVersion;
22740        final PackageFreezer freezer;
22741        final int[] installedUserIds;
22742
22743        // reader
22744        synchronized (mPackages) {
22745            final PackageParser.Package pkg = mPackages.get(packageName);
22746            final PackageSetting ps = mSettings.mPackages.get(packageName);
22747            if (pkg == null
22748                    || ps == null
22749                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22750                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22751            }
22752            if (pkg.applicationInfo.isSystemApp()) {
22753                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22754                        "Cannot move system application");
22755            }
22756
22757            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22758            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22759                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22760            if (isInternalStorage && !allow3rdPartyOnInternal) {
22761                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22762                        "3rd party apps are not allowed on internal storage");
22763            }
22764
22765            if (pkg.applicationInfo.isExternalAsec()) {
22766                currentAsec = true;
22767                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22768            } else if (pkg.applicationInfo.isForwardLocked()) {
22769                currentAsec = true;
22770                currentVolumeUuid = "forward_locked";
22771            } else {
22772                currentAsec = false;
22773                currentVolumeUuid = ps.volumeUuid;
22774
22775                final File probe = new File(pkg.codePath);
22776                final File probeOat = new File(probe, "oat");
22777                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22778                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22779                            "Move only supported for modern cluster style installs");
22780                }
22781            }
22782
22783            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22784                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22785                        "Package already moved to " + volumeUuid);
22786            }
22787            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22788                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22789                        "Device admin cannot be moved");
22790            }
22791
22792            if (mFrozenPackages.contains(packageName)) {
22793                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22794                        "Failed to move already frozen package");
22795            }
22796
22797            codeFile = new File(pkg.codePath);
22798            installerPackageName = ps.installerPackageName;
22799            packageAbiOverride = ps.cpuAbiOverrideString;
22800            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22801            seinfo = pkg.applicationInfo.seInfo;
22802            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22803            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22804            freezer = freezePackage(packageName, "movePackageInternal");
22805            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22806        }
22807
22808        final Bundle extras = new Bundle();
22809        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22810        extras.putString(Intent.EXTRA_TITLE, label);
22811        mMoveCallbacks.notifyCreated(moveId, extras);
22812
22813        int installFlags;
22814        final boolean moveCompleteApp;
22815        final File measurePath;
22816
22817        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22818            installFlags = INSTALL_INTERNAL;
22819            moveCompleteApp = !currentAsec;
22820            measurePath = Environment.getDataAppDirectory(volumeUuid);
22821        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22822            installFlags = INSTALL_EXTERNAL;
22823            moveCompleteApp = false;
22824            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22825        } else {
22826            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22827            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22828                    || !volume.isMountedWritable()) {
22829                freezer.close();
22830                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22831                        "Move location not mounted private volume");
22832            }
22833
22834            Preconditions.checkState(!currentAsec);
22835
22836            installFlags = INSTALL_INTERNAL;
22837            moveCompleteApp = true;
22838            measurePath = Environment.getDataAppDirectory(volumeUuid);
22839        }
22840
22841        // If we're moving app data around, we need all the users unlocked
22842        if (moveCompleteApp) {
22843            for (int userId : installedUserIds) {
22844                if (StorageManager.isFileEncryptedNativeOrEmulated()
22845                        && !StorageManager.isUserKeyUnlocked(userId)) {
22846                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22847                            "User " + userId + " must be unlocked");
22848                }
22849            }
22850        }
22851
22852        final PackageStats stats = new PackageStats(null, -1);
22853        synchronized (mInstaller) {
22854            for (int userId : installedUserIds) {
22855                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22856                    freezer.close();
22857                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22858                            "Failed to measure package size");
22859                }
22860            }
22861        }
22862
22863        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22864                + stats.dataSize);
22865
22866        final long startFreeBytes = measurePath.getUsableSpace();
22867        final long sizeBytes;
22868        if (moveCompleteApp) {
22869            sizeBytes = stats.codeSize + stats.dataSize;
22870        } else {
22871            sizeBytes = stats.codeSize;
22872        }
22873
22874        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22875            freezer.close();
22876            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22877                    "Not enough free space to move");
22878        }
22879
22880        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22881
22882        final CountDownLatch installedLatch = new CountDownLatch(1);
22883        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22884            @Override
22885            public void onUserActionRequired(Intent intent) throws RemoteException {
22886                throw new IllegalStateException();
22887            }
22888
22889            @Override
22890            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22891                    Bundle extras) throws RemoteException {
22892                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22893                        + PackageManager.installStatusToString(returnCode, msg));
22894
22895                installedLatch.countDown();
22896                freezer.close();
22897
22898                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22899                switch (status) {
22900                    case PackageInstaller.STATUS_SUCCESS:
22901                        mMoveCallbacks.notifyStatusChanged(moveId,
22902                                PackageManager.MOVE_SUCCEEDED);
22903                        break;
22904                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22905                        mMoveCallbacks.notifyStatusChanged(moveId,
22906                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22907                        break;
22908                    default:
22909                        mMoveCallbacks.notifyStatusChanged(moveId,
22910                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22911                        break;
22912                }
22913            }
22914        };
22915
22916        final MoveInfo move;
22917        if (moveCompleteApp) {
22918            // Kick off a thread to report progress estimates
22919            new Thread() {
22920                @Override
22921                public void run() {
22922                    while (true) {
22923                        try {
22924                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22925                                break;
22926                            }
22927                        } catch (InterruptedException ignored) {
22928                        }
22929
22930                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22931                        final int progress = 10 + (int) MathUtils.constrain(
22932                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22933                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22934                    }
22935                }
22936            }.start();
22937
22938            final String dataAppName = codeFile.getName();
22939            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22940                    dataAppName, appId, seinfo, targetSdkVersion);
22941        } else {
22942            move = null;
22943        }
22944
22945        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22946
22947        final Message msg = mHandler.obtainMessage(INIT_COPY);
22948        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22949        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22950                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22951                packageAbiOverride, null /*grantedPermissions*/,
22952                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22953        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22954        msg.obj = params;
22955
22956        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22957                System.identityHashCode(msg.obj));
22958        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22959                System.identityHashCode(msg.obj));
22960
22961        mHandler.sendMessage(msg);
22962    }
22963
22964    @Override
22965    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22966        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22967
22968        final int realMoveId = mNextMoveId.getAndIncrement();
22969        final Bundle extras = new Bundle();
22970        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22971        mMoveCallbacks.notifyCreated(realMoveId, extras);
22972
22973        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22974            @Override
22975            public void onCreated(int moveId, Bundle extras) {
22976                // Ignored
22977            }
22978
22979            @Override
22980            public void onStatusChanged(int moveId, int status, long estMillis) {
22981                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22982            }
22983        };
22984
22985        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22986        storage.setPrimaryStorageUuid(volumeUuid, callback);
22987        return realMoveId;
22988    }
22989
22990    @Override
22991    public int getMoveStatus(int moveId) {
22992        mContext.enforceCallingOrSelfPermission(
22993                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22994        return mMoveCallbacks.mLastStatus.get(moveId);
22995    }
22996
22997    @Override
22998    public void registerMoveCallback(IPackageMoveObserver callback) {
22999        mContext.enforceCallingOrSelfPermission(
23000                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23001        mMoveCallbacks.register(callback);
23002    }
23003
23004    @Override
23005    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23006        mContext.enforceCallingOrSelfPermission(
23007                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23008        mMoveCallbacks.unregister(callback);
23009    }
23010
23011    @Override
23012    public boolean setInstallLocation(int loc) {
23013        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23014                null);
23015        if (getInstallLocation() == loc) {
23016            return true;
23017        }
23018        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23019                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23020            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23021                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23022            return true;
23023        }
23024        return false;
23025   }
23026
23027    @Override
23028    public int getInstallLocation() {
23029        // allow instant app access
23030        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23031                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23032                PackageHelper.APP_INSTALL_AUTO);
23033    }
23034
23035    /** Called by UserManagerService */
23036    void cleanUpUser(UserManagerService userManager, int userHandle) {
23037        synchronized (mPackages) {
23038            mDirtyUsers.remove(userHandle);
23039            mUserNeedsBadging.delete(userHandle);
23040            mSettings.removeUserLPw(userHandle);
23041            mPendingBroadcasts.remove(userHandle);
23042            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23043            removeUnusedPackagesLPw(userManager, userHandle);
23044        }
23045    }
23046
23047    /**
23048     * We're removing userHandle and would like to remove any downloaded packages
23049     * that are no longer in use by any other user.
23050     * @param userHandle the user being removed
23051     */
23052    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23053        final boolean DEBUG_CLEAN_APKS = false;
23054        int [] users = userManager.getUserIds();
23055        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23056        while (psit.hasNext()) {
23057            PackageSetting ps = psit.next();
23058            if (ps.pkg == null) {
23059                continue;
23060            }
23061            final String packageName = ps.pkg.packageName;
23062            // Skip over if system app
23063            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23064                continue;
23065            }
23066            if (DEBUG_CLEAN_APKS) {
23067                Slog.i(TAG, "Checking package " + packageName);
23068            }
23069            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23070            if (keep) {
23071                if (DEBUG_CLEAN_APKS) {
23072                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23073                }
23074            } else {
23075                for (int i = 0; i < users.length; i++) {
23076                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23077                        keep = true;
23078                        if (DEBUG_CLEAN_APKS) {
23079                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23080                                    + users[i]);
23081                        }
23082                        break;
23083                    }
23084                }
23085            }
23086            if (!keep) {
23087                if (DEBUG_CLEAN_APKS) {
23088                    Slog.i(TAG, "  Removing package " + packageName);
23089                }
23090                mHandler.post(new Runnable() {
23091                    public void run() {
23092                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23093                                userHandle, 0);
23094                    } //end run
23095                });
23096            }
23097        }
23098    }
23099
23100    /** Called by UserManagerService */
23101    void createNewUser(int userId, String[] disallowedPackages) {
23102        synchronized (mInstallLock) {
23103            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23104        }
23105        synchronized (mPackages) {
23106            scheduleWritePackageRestrictionsLocked(userId);
23107            scheduleWritePackageListLocked(userId);
23108            applyFactoryDefaultBrowserLPw(userId);
23109            primeDomainVerificationsLPw(userId);
23110        }
23111    }
23112
23113    void onNewUserCreated(final int userId) {
23114        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23115        synchronized(mPackages) {
23116            // If permission review for legacy apps is required, we represent
23117            // dagerous permissions for such apps as always granted runtime
23118            // permissions to keep per user flag state whether review is needed.
23119            // Hence, if a new user is added we have to propagate dangerous
23120            // permission grants for these legacy apps.
23121            if (mSettings.mPermissions.mPermissionReviewRequired) {
23122// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
23123                mPermissionManager.updateAllPermissions(
23124                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
23125                        mPermissionCallback);
23126            }
23127        }
23128    }
23129
23130    @Override
23131    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23132        mContext.enforceCallingOrSelfPermission(
23133                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23134                "Only package verification agents can read the verifier device identity");
23135
23136        synchronized (mPackages) {
23137            return mSettings.getVerifierDeviceIdentityLPw();
23138        }
23139    }
23140
23141    @Override
23142    public void setPermissionEnforced(String permission, boolean enforced) {
23143        // TODO: Now that we no longer change GID for storage, this should to away.
23144        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23145                "setPermissionEnforced");
23146        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23147            synchronized (mPackages) {
23148                if (mSettings.mReadExternalStorageEnforced == null
23149                        || mSettings.mReadExternalStorageEnforced != enforced) {
23150                    mSettings.mReadExternalStorageEnforced =
23151                            enforced ? Boolean.TRUE : Boolean.FALSE;
23152                    mSettings.writeLPr();
23153                }
23154            }
23155            // kill any non-foreground processes so we restart them and
23156            // grant/revoke the GID.
23157            final IActivityManager am = ActivityManager.getService();
23158            if (am != null) {
23159                final long token = Binder.clearCallingIdentity();
23160                try {
23161                    am.killProcessesBelowForeground("setPermissionEnforcement");
23162                } catch (RemoteException e) {
23163                } finally {
23164                    Binder.restoreCallingIdentity(token);
23165                }
23166            }
23167        } else {
23168            throw new IllegalArgumentException("No selective enforcement for " + permission);
23169        }
23170    }
23171
23172    @Override
23173    @Deprecated
23174    public boolean isPermissionEnforced(String permission) {
23175        // allow instant applications
23176        return true;
23177    }
23178
23179    @Override
23180    public boolean isStorageLow() {
23181        // allow instant applications
23182        final long token = Binder.clearCallingIdentity();
23183        try {
23184            final DeviceStorageMonitorInternal
23185                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23186            if (dsm != null) {
23187                return dsm.isMemoryLow();
23188            } else {
23189                return false;
23190            }
23191        } finally {
23192            Binder.restoreCallingIdentity(token);
23193        }
23194    }
23195
23196    @Override
23197    public IPackageInstaller getPackageInstaller() {
23198        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23199            return null;
23200        }
23201        return mInstallerService;
23202    }
23203
23204    @Override
23205    public IArtManager getArtManager() {
23206        return mArtManagerService;
23207    }
23208
23209    private boolean userNeedsBadging(int userId) {
23210        int index = mUserNeedsBadging.indexOfKey(userId);
23211        if (index < 0) {
23212            final UserInfo userInfo;
23213            final long token = Binder.clearCallingIdentity();
23214            try {
23215                userInfo = sUserManager.getUserInfo(userId);
23216            } finally {
23217                Binder.restoreCallingIdentity(token);
23218            }
23219            final boolean b;
23220            if (userInfo != null && userInfo.isManagedProfile()) {
23221                b = true;
23222            } else {
23223                b = false;
23224            }
23225            mUserNeedsBadging.put(userId, b);
23226            return b;
23227        }
23228        return mUserNeedsBadging.valueAt(index);
23229    }
23230
23231    @Override
23232    public KeySet getKeySetByAlias(String packageName, String alias) {
23233        if (packageName == null || alias == null) {
23234            return null;
23235        }
23236        synchronized(mPackages) {
23237            final PackageParser.Package pkg = mPackages.get(packageName);
23238            if (pkg == null) {
23239                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23240                throw new IllegalArgumentException("Unknown package: " + packageName);
23241            }
23242            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23243            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23244                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23245                throw new IllegalArgumentException("Unknown package: " + packageName);
23246            }
23247            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23248            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23249        }
23250    }
23251
23252    @Override
23253    public KeySet getSigningKeySet(String packageName) {
23254        if (packageName == null) {
23255            return null;
23256        }
23257        synchronized(mPackages) {
23258            final int callingUid = Binder.getCallingUid();
23259            final int callingUserId = UserHandle.getUserId(callingUid);
23260            final PackageParser.Package pkg = mPackages.get(packageName);
23261            if (pkg == null) {
23262                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23263                throw new IllegalArgumentException("Unknown package: " + packageName);
23264            }
23265            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23266            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23267                // filter and pretend the package doesn't exist
23268                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23269                        + ", uid:" + callingUid);
23270                throw new IllegalArgumentException("Unknown package: " + packageName);
23271            }
23272            if (pkg.applicationInfo.uid != callingUid
23273                    && Process.SYSTEM_UID != callingUid) {
23274                throw new SecurityException("May not access signing KeySet of other apps.");
23275            }
23276            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23277            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23278        }
23279    }
23280
23281    @Override
23282    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23283        final int callingUid = Binder.getCallingUid();
23284        if (getInstantAppPackageName(callingUid) != null) {
23285            return false;
23286        }
23287        if (packageName == null || ks == null) {
23288            return false;
23289        }
23290        synchronized(mPackages) {
23291            final PackageParser.Package pkg = mPackages.get(packageName);
23292            if (pkg == null
23293                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23294                            UserHandle.getUserId(callingUid))) {
23295                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23296                throw new IllegalArgumentException("Unknown package: " + packageName);
23297            }
23298            IBinder ksh = ks.getToken();
23299            if (ksh instanceof KeySetHandle) {
23300                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23301                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23302            }
23303            return false;
23304        }
23305    }
23306
23307    @Override
23308    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23309        final int callingUid = Binder.getCallingUid();
23310        if (getInstantAppPackageName(callingUid) != null) {
23311            return false;
23312        }
23313        if (packageName == null || ks == null) {
23314            return false;
23315        }
23316        synchronized(mPackages) {
23317            final PackageParser.Package pkg = mPackages.get(packageName);
23318            if (pkg == null
23319                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23320                            UserHandle.getUserId(callingUid))) {
23321                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23322                throw new IllegalArgumentException("Unknown package: " + packageName);
23323            }
23324            IBinder ksh = ks.getToken();
23325            if (ksh instanceof KeySetHandle) {
23326                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23327                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23328            }
23329            return false;
23330        }
23331    }
23332
23333    private void deletePackageIfUnusedLPr(final String packageName) {
23334        PackageSetting ps = mSettings.mPackages.get(packageName);
23335        if (ps == null) {
23336            return;
23337        }
23338        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23339            // TODO Implement atomic delete if package is unused
23340            // It is currently possible that the package will be deleted even if it is installed
23341            // after this method returns.
23342            mHandler.post(new Runnable() {
23343                public void run() {
23344                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23345                            0, PackageManager.DELETE_ALL_USERS);
23346                }
23347            });
23348        }
23349    }
23350
23351    /**
23352     * Check and throw if the given before/after packages would be considered a
23353     * downgrade.
23354     */
23355    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23356            throws PackageManagerException {
23357        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23358            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23359                    "Update version code " + after.versionCode + " is older than current "
23360                    + before.getLongVersionCode());
23361        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23362            if (after.baseRevisionCode < before.baseRevisionCode) {
23363                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23364                        "Update base revision code " + after.baseRevisionCode
23365                        + " is older than current " + before.baseRevisionCode);
23366            }
23367
23368            if (!ArrayUtils.isEmpty(after.splitNames)) {
23369                for (int i = 0; i < after.splitNames.length; i++) {
23370                    final String splitName = after.splitNames[i];
23371                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23372                    if (j != -1) {
23373                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23374                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23375                                    "Update split " + splitName + " revision code "
23376                                    + after.splitRevisionCodes[i] + " is older than current "
23377                                    + before.splitRevisionCodes[j]);
23378                        }
23379                    }
23380                }
23381            }
23382        }
23383    }
23384
23385    private static class MoveCallbacks extends Handler {
23386        private static final int MSG_CREATED = 1;
23387        private static final int MSG_STATUS_CHANGED = 2;
23388
23389        private final RemoteCallbackList<IPackageMoveObserver>
23390                mCallbacks = new RemoteCallbackList<>();
23391
23392        private final SparseIntArray mLastStatus = new SparseIntArray();
23393
23394        public MoveCallbacks(Looper looper) {
23395            super(looper);
23396        }
23397
23398        public void register(IPackageMoveObserver callback) {
23399            mCallbacks.register(callback);
23400        }
23401
23402        public void unregister(IPackageMoveObserver callback) {
23403            mCallbacks.unregister(callback);
23404        }
23405
23406        @Override
23407        public void handleMessage(Message msg) {
23408            final SomeArgs args = (SomeArgs) msg.obj;
23409            final int n = mCallbacks.beginBroadcast();
23410            for (int i = 0; i < n; i++) {
23411                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23412                try {
23413                    invokeCallback(callback, msg.what, args);
23414                } catch (RemoteException ignored) {
23415                }
23416            }
23417            mCallbacks.finishBroadcast();
23418            args.recycle();
23419        }
23420
23421        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23422                throws RemoteException {
23423            switch (what) {
23424                case MSG_CREATED: {
23425                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23426                    break;
23427                }
23428                case MSG_STATUS_CHANGED: {
23429                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23430                    break;
23431                }
23432            }
23433        }
23434
23435        private void notifyCreated(int moveId, Bundle extras) {
23436            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23437
23438            final SomeArgs args = SomeArgs.obtain();
23439            args.argi1 = moveId;
23440            args.arg2 = extras;
23441            obtainMessage(MSG_CREATED, args).sendToTarget();
23442        }
23443
23444        private void notifyStatusChanged(int moveId, int status) {
23445            notifyStatusChanged(moveId, status, -1);
23446        }
23447
23448        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23449            Slog.v(TAG, "Move " + moveId + " status " + status);
23450
23451            final SomeArgs args = SomeArgs.obtain();
23452            args.argi1 = moveId;
23453            args.argi2 = status;
23454            args.arg3 = estMillis;
23455            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23456
23457            synchronized (mLastStatus) {
23458                mLastStatus.put(moveId, status);
23459            }
23460        }
23461    }
23462
23463    private final static class OnPermissionChangeListeners extends Handler {
23464        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23465
23466        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23467                new RemoteCallbackList<>();
23468
23469        public OnPermissionChangeListeners(Looper looper) {
23470            super(looper);
23471        }
23472
23473        @Override
23474        public void handleMessage(Message msg) {
23475            switch (msg.what) {
23476                case MSG_ON_PERMISSIONS_CHANGED: {
23477                    final int uid = msg.arg1;
23478                    handleOnPermissionsChanged(uid);
23479                } break;
23480            }
23481        }
23482
23483        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23484            mPermissionListeners.register(listener);
23485
23486        }
23487
23488        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23489            mPermissionListeners.unregister(listener);
23490        }
23491
23492        public void onPermissionsChanged(int uid) {
23493            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23494                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23495            }
23496        }
23497
23498        private void handleOnPermissionsChanged(int uid) {
23499            final int count = mPermissionListeners.beginBroadcast();
23500            try {
23501                for (int i = 0; i < count; i++) {
23502                    IOnPermissionsChangeListener callback = mPermissionListeners
23503                            .getBroadcastItem(i);
23504                    try {
23505                        callback.onPermissionsChanged(uid);
23506                    } catch (RemoteException e) {
23507                        Log.e(TAG, "Permission listener is dead", e);
23508                    }
23509                }
23510            } finally {
23511                mPermissionListeners.finishBroadcast();
23512            }
23513        }
23514    }
23515
23516    private class PackageManagerNative extends IPackageManagerNative.Stub {
23517        @Override
23518        public String[] getNamesForUids(int[] uids) throws RemoteException {
23519            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23520            // massage results so they can be parsed by the native binder
23521            for (int i = results.length - 1; i >= 0; --i) {
23522                if (results[i] == null) {
23523                    results[i] = "";
23524                }
23525            }
23526            return results;
23527        }
23528
23529        // NB: this differentiates between preloads and sideloads
23530        @Override
23531        public String getInstallerForPackage(String packageName) throws RemoteException {
23532            final String installerName = getInstallerPackageName(packageName);
23533            if (!TextUtils.isEmpty(installerName)) {
23534                return installerName;
23535            }
23536            // differentiate between preload and sideload
23537            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23538            ApplicationInfo appInfo = getApplicationInfo(packageName,
23539                                    /*flags*/ 0,
23540                                    /*userId*/ callingUser);
23541            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23542                return "preload";
23543            }
23544            return "";
23545        }
23546
23547        @Override
23548        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23549            try {
23550                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23551                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23552                if (pInfo != null) {
23553                    return pInfo.getLongVersionCode();
23554                }
23555            } catch (Exception e) {
23556            }
23557            return 0;
23558        }
23559    }
23560
23561    private class PackageManagerInternalImpl extends PackageManagerInternal {
23562        @Override
23563        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23564                int flagValues, int userId) {
23565            PackageManagerService.this.updatePermissionFlags(
23566                    permName, packageName, flagMask, flagValues, userId);
23567        }
23568
23569        @Override
23570        public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) {
23571            SigningDetails sd = getSigningDetails(packageName);
23572            if (sd == null) {
23573                return false;
23574            }
23575            return sd.hasSha256Certificate(restoringFromSigHash,
23576                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23577        }
23578
23579        @Override
23580        public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) {
23581            SigningDetails sd = getSigningDetails(packageName);
23582            if (sd == null) {
23583                return false;
23584            }
23585            return sd.hasCertificate(restoringFromSig,
23586                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23587        }
23588
23589        @Override
23590        public boolean hasSignatureCapability(int serverUid, int clientUid,
23591                @SigningDetails.CertCapabilities int capability) {
23592            SigningDetails serverSigningDetails = getSigningDetails(serverUid);
23593            SigningDetails clientSigningDetails = getSigningDetails(clientUid);
23594            return serverSigningDetails.checkCapability(clientSigningDetails, capability)
23595                    || clientSigningDetails.hasAncestorOrSelf(serverSigningDetails);
23596
23597        }
23598
23599        private SigningDetails getSigningDetails(@NonNull String packageName) {
23600            synchronized (mPackages) {
23601                PackageParser.Package p = mPackages.get(packageName);
23602                if (p == null) {
23603                    return null;
23604                }
23605                return p.mSigningDetails;
23606            }
23607        }
23608
23609        private SigningDetails getSigningDetails(int uid) {
23610            synchronized (mPackages) {
23611                final int appId = UserHandle.getAppId(uid);
23612                final Object obj = mSettings.getUserIdLPr(appId);
23613                if (obj != null) {
23614                    if (obj instanceof SharedUserSetting) {
23615                        return ((SharedUserSetting) obj).signatures.mSigningDetails;
23616                    } else if (obj instanceof PackageSetting) {
23617                        final PackageSetting ps = (PackageSetting) obj;
23618                        return ps.signatures.mSigningDetails;
23619                    }
23620                }
23621                return SigningDetails.UNKNOWN;
23622            }
23623        }
23624
23625        @Override
23626        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23627            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23628        }
23629
23630        @Override
23631        public boolean isInstantApp(String packageName, int userId) {
23632            return PackageManagerService.this.isInstantApp(packageName, userId);
23633        }
23634
23635        @Override
23636        public String getInstantAppPackageName(int uid) {
23637            return PackageManagerService.this.getInstantAppPackageName(uid);
23638        }
23639
23640        @Override
23641        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23642            synchronized (mPackages) {
23643                return PackageManagerService.this.filterAppAccessLPr(
23644                        (PackageSetting) pkg.mExtras, callingUid, userId);
23645            }
23646        }
23647
23648        @Override
23649        public PackageParser.Package getPackage(String packageName) {
23650            synchronized (mPackages) {
23651                packageName = resolveInternalPackageNameLPr(
23652                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23653                return mPackages.get(packageName);
23654            }
23655        }
23656
23657        @Override
23658        public PackageList getPackageList(PackageListObserver observer) {
23659            synchronized (mPackages) {
23660                final int N = mPackages.size();
23661                final ArrayList<String> list = new ArrayList<>(N);
23662                for (int i = 0; i < N; i++) {
23663                    list.add(mPackages.keyAt(i));
23664                }
23665                final PackageList packageList = new PackageList(list, observer);
23666                if (observer != null) {
23667                    mPackageListObservers.add(packageList);
23668                }
23669                return packageList;
23670            }
23671        }
23672
23673        @Override
23674        public void removePackageListObserver(PackageListObserver observer) {
23675            synchronized (mPackages) {
23676                mPackageListObservers.remove(observer);
23677            }
23678        }
23679
23680        @Override
23681        public PackageParser.Package getDisabledPackage(String packageName) {
23682            synchronized (mPackages) {
23683                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23684                return (ps != null) ? ps.pkg : null;
23685            }
23686        }
23687
23688        @Override
23689        public String getKnownPackageName(int knownPackage, int userId) {
23690            switch(knownPackage) {
23691                case PackageManagerInternal.PACKAGE_BROWSER:
23692                    return getDefaultBrowserPackageName(userId);
23693                case PackageManagerInternal.PACKAGE_INSTALLER:
23694                    return mRequiredInstallerPackage;
23695                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23696                    return mSetupWizardPackage;
23697                case PackageManagerInternal.PACKAGE_SYSTEM:
23698                    return "android";
23699                case PackageManagerInternal.PACKAGE_VERIFIER:
23700                    return mRequiredVerifierPackage;
23701                case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER:
23702                    return mSystemTextClassifierPackage;
23703            }
23704            return null;
23705        }
23706
23707        @Override
23708        public boolean isResolveActivityComponent(ComponentInfo component) {
23709            return mResolveActivity.packageName.equals(component.packageName)
23710                    && mResolveActivity.name.equals(component.name);
23711        }
23712
23713        @Override
23714        public void setLocationPackagesProvider(PackagesProvider provider) {
23715            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23716        }
23717
23718        @Override
23719        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23720            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23721        }
23722
23723        @Override
23724        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23725            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23726        }
23727
23728        @Override
23729        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23730            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23731        }
23732
23733        @Override
23734        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23735            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23736        }
23737
23738        @Override
23739        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23740            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23741        }
23742
23743        @Override
23744        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23745            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23746        }
23747
23748        @Override
23749        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23750            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23751        }
23752
23753        @Override
23754        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23755            synchronized (mPackages) {
23756                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23757            }
23758            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23759        }
23760
23761        @Override
23762        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23763            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23764                    packageName, userId);
23765        }
23766
23767        @Override
23768        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23769            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23770                    packageName, userId);
23771        }
23772
23773        @Override
23774        public void setKeepUninstalledPackages(final List<String> packageList) {
23775            Preconditions.checkNotNull(packageList);
23776            List<String> removedFromList = null;
23777            synchronized (mPackages) {
23778                if (mKeepUninstalledPackages != null) {
23779                    final int packagesCount = mKeepUninstalledPackages.size();
23780                    for (int i = 0; i < packagesCount; i++) {
23781                        String oldPackage = mKeepUninstalledPackages.get(i);
23782                        if (packageList != null && packageList.contains(oldPackage)) {
23783                            continue;
23784                        }
23785                        if (removedFromList == null) {
23786                            removedFromList = new ArrayList<>();
23787                        }
23788                        removedFromList.add(oldPackage);
23789                    }
23790                }
23791                mKeepUninstalledPackages = new ArrayList<>(packageList);
23792                if (removedFromList != null) {
23793                    final int removedCount = removedFromList.size();
23794                    for (int i = 0; i < removedCount; i++) {
23795                        deletePackageIfUnusedLPr(removedFromList.get(i));
23796                    }
23797                }
23798            }
23799        }
23800
23801        @Override
23802        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23803            synchronized (mPackages) {
23804                return mPermissionManager.isPermissionsReviewRequired(
23805                        mPackages.get(packageName), userId);
23806            }
23807        }
23808
23809        @Override
23810        public PackageInfo getPackageInfo(
23811                String packageName, int flags, int filterCallingUid, int userId) {
23812            return PackageManagerService.this
23813                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23814                            flags, filterCallingUid, userId);
23815        }
23816
23817        @Override
23818        public Bundle getSuspendedPackageLauncherExtras(String packageName, int userId) {
23819            synchronized (mPackages) {
23820                final PackageSetting ps = mSettings.mPackages.get(packageName);
23821                PersistableBundle launcherExtras = null;
23822                if (ps != null) {
23823                    launcherExtras = ps.readUserState(userId).suspendedLauncherExtras;
23824                }
23825                return (launcherExtras != null) ? new Bundle(launcherExtras.deepCopy()) : null;
23826            }
23827        }
23828
23829        @Override
23830        public boolean isPackageSuspended(String packageName, int userId) {
23831            synchronized (mPackages) {
23832                final PackageSetting ps = mSettings.mPackages.get(packageName);
23833                return (ps != null) ? ps.getSuspended(userId) : false;
23834            }
23835        }
23836
23837        @Override
23838        public String getSuspendingPackage(String suspendedPackage, int userId) {
23839            synchronized (mPackages) {
23840                final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
23841                return (ps != null) ? ps.readUserState(userId).suspendingPackage : null;
23842            }
23843        }
23844
23845        @Override
23846        public String getSuspendedDialogMessage(String suspendedPackage, int userId) {
23847            synchronized (mPackages) {
23848                final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
23849                return (ps != null) ? ps.readUserState(userId).dialogMessage : null;
23850            }
23851        }
23852
23853        @Override
23854        public int getPackageUid(String packageName, int flags, int userId) {
23855            return PackageManagerService.this
23856                    .getPackageUid(packageName, flags, userId);
23857        }
23858
23859        @Override
23860        public ApplicationInfo getApplicationInfo(
23861                String packageName, int flags, int filterCallingUid, int userId) {
23862            return PackageManagerService.this
23863                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23864        }
23865
23866        @Override
23867        public ActivityInfo getActivityInfo(
23868                ComponentName component, int flags, int filterCallingUid, int userId) {
23869            return PackageManagerService.this
23870                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23871        }
23872
23873        @Override
23874        public List<ResolveInfo> queryIntentActivities(
23875                Intent intent, int flags, int filterCallingUid, int userId) {
23876            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23877            return PackageManagerService.this
23878                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23879                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23880        }
23881
23882        @Override
23883        public List<ResolveInfo> queryIntentServices(
23884                Intent intent, int flags, int callingUid, int userId) {
23885            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23886            return PackageManagerService.this
23887                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23888                            false);
23889        }
23890
23891        @Override
23892        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23893                int userId) {
23894            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23895        }
23896
23897        @Override
23898        public ComponentName getDefaultHomeActivity(int userId) {
23899            return PackageManagerService.this.getDefaultHomeActivity(userId);
23900        }
23901
23902        @Override
23903        public void setDeviceAndProfileOwnerPackages(
23904                int deviceOwnerUserId, String deviceOwnerPackage,
23905                SparseArray<String> profileOwnerPackages) {
23906            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23907                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23908        }
23909
23910        @Override
23911        public boolean isPackageDataProtected(int userId, String packageName) {
23912            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23913        }
23914
23915        @Override
23916        public boolean isPackageStateProtected(String packageName, int userId) {
23917            return mProtectedPackages.isPackageStateProtected(userId, packageName);
23918        }
23919
23920        @Override
23921        public boolean isPackageEphemeral(int userId, String packageName) {
23922            synchronized (mPackages) {
23923                final PackageSetting ps = mSettings.mPackages.get(packageName);
23924                return ps != null ? ps.getInstantApp(userId) : false;
23925            }
23926        }
23927
23928        @Override
23929        public boolean wasPackageEverLaunched(String packageName, int userId) {
23930            synchronized (mPackages) {
23931                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23932            }
23933        }
23934
23935        @Override
23936        public void grantRuntimePermission(String packageName, String permName, int userId,
23937                boolean overridePolicy) {
23938            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23939                    permName, packageName, overridePolicy, getCallingUid(), userId,
23940                    mPermissionCallback);
23941        }
23942
23943        @Override
23944        public void revokeRuntimePermission(String packageName, String permName, int userId,
23945                boolean overridePolicy) {
23946            mPermissionManager.revokeRuntimePermission(
23947                    permName, packageName, overridePolicy, getCallingUid(), userId,
23948                    mPermissionCallback);
23949        }
23950
23951        @Override
23952        public String getNameForUid(int uid) {
23953            return PackageManagerService.this.getNameForUid(uid);
23954        }
23955
23956        @Override
23957        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23958                Intent origIntent, String resolvedType, String callingPackage,
23959                Bundle verificationBundle, int userId) {
23960            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23961                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23962                    userId);
23963        }
23964
23965        @Override
23966        public void grantEphemeralAccess(int userId, Intent intent,
23967                int targetAppId, int ephemeralAppId) {
23968            synchronized (mPackages) {
23969                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23970                        targetAppId, ephemeralAppId);
23971            }
23972        }
23973
23974        @Override
23975        public boolean isInstantAppInstallerComponent(ComponentName component) {
23976            synchronized (mPackages) {
23977                return mInstantAppInstallerActivity != null
23978                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23979            }
23980        }
23981
23982        @Override
23983        public void pruneInstantApps() {
23984            mInstantAppRegistry.pruneInstantApps();
23985        }
23986
23987        @Override
23988        public String getSetupWizardPackageName() {
23989            return mSetupWizardPackage;
23990        }
23991
23992        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23993            if (policy != null) {
23994                mExternalSourcesPolicy = policy;
23995            }
23996        }
23997
23998        @Override
23999        public boolean isPackagePersistent(String packageName) {
24000            synchronized (mPackages) {
24001                PackageParser.Package pkg = mPackages.get(packageName);
24002                return pkg != null
24003                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24004                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24005                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24006                        : false;
24007            }
24008        }
24009
24010        @Override
24011        public boolean isLegacySystemApp(Package pkg) {
24012            synchronized (mPackages) {
24013                final PackageSetting ps = (PackageSetting) pkg.mExtras;
24014                return mPromoteSystemApps
24015                        && ps.isSystem()
24016                        && mExistingSystemPackages.contains(ps.name);
24017            }
24018        }
24019
24020        @Override
24021        public List<PackageInfo> getOverlayPackages(int userId) {
24022            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24023            synchronized (mPackages) {
24024                for (PackageParser.Package p : mPackages.values()) {
24025                    if (p.mOverlayTarget != null) {
24026                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24027                        if (pkg != null) {
24028                            overlayPackages.add(pkg);
24029                        }
24030                    }
24031                }
24032            }
24033            return overlayPackages;
24034        }
24035
24036        @Override
24037        public List<String> getTargetPackageNames(int userId) {
24038            List<String> targetPackages = new ArrayList<>();
24039            synchronized (mPackages) {
24040                for (PackageParser.Package p : mPackages.values()) {
24041                    if (p.mOverlayTarget == null) {
24042                        targetPackages.add(p.packageName);
24043                    }
24044                }
24045            }
24046            return targetPackages;
24047        }
24048
24049        @Override
24050        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24051                @Nullable List<String> overlayPackageNames) {
24052            synchronized (mPackages) {
24053                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24054                    Slog.e(TAG, "failed to find package " + targetPackageName);
24055                    return false;
24056                }
24057                ArrayList<String> overlayPaths = null;
24058                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24059                    final int N = overlayPackageNames.size();
24060                    overlayPaths = new ArrayList<>(N);
24061                    for (int i = 0; i < N; i++) {
24062                        final String packageName = overlayPackageNames.get(i);
24063                        final PackageParser.Package pkg = mPackages.get(packageName);
24064                        if (pkg == null) {
24065                            Slog.e(TAG, "failed to find package " + packageName);
24066                            return false;
24067                        }
24068                        overlayPaths.add(pkg.baseCodePath);
24069                    }
24070                }
24071
24072                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24073                ps.setOverlayPaths(overlayPaths, userId);
24074                return true;
24075            }
24076        }
24077
24078        @Override
24079        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24080                int flags, int userId, boolean resolveForStart, int filterCallingUid) {
24081            return resolveIntentInternal(
24082                    intent, resolvedType, flags, userId, resolveForStart, filterCallingUid);
24083        }
24084
24085        @Override
24086        public ResolveInfo resolveService(Intent intent, String resolvedType,
24087                int flags, int userId, int callingUid) {
24088            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24089        }
24090
24091        @Override
24092        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
24093            return PackageManagerService.this.resolveContentProviderInternal(
24094                    name, flags, userId);
24095        }
24096
24097        @Override
24098        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24099            synchronized (mPackages) {
24100                mIsolatedOwners.put(isolatedUid, ownerUid);
24101            }
24102        }
24103
24104        @Override
24105        public void removeIsolatedUid(int isolatedUid) {
24106            synchronized (mPackages) {
24107                mIsolatedOwners.delete(isolatedUid);
24108            }
24109        }
24110
24111        @Override
24112        public int getUidTargetSdkVersion(int uid) {
24113            synchronized (mPackages) {
24114                return getUidTargetSdkVersionLockedLPr(uid);
24115            }
24116        }
24117
24118        @Override
24119        public int getPackageTargetSdkVersion(String packageName) {
24120            synchronized (mPackages) {
24121                return getPackageTargetSdkVersionLockedLPr(packageName);
24122            }
24123        }
24124
24125        @Override
24126        public boolean canAccessInstantApps(int callingUid, int userId) {
24127            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24128        }
24129
24130        @Override
24131        public boolean canAccessComponent(int callingUid, ComponentName component, int userId) {
24132            synchronized (mPackages) {
24133                final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
24134                return !PackageManagerService.this.filterAppAccessLPr(
24135                        ps, callingUid, component, TYPE_UNKNOWN, userId);
24136            }
24137        }
24138
24139        @Override
24140        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
24141            synchronized (mPackages) {
24142                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
24143            }
24144        }
24145
24146        @Override
24147        public void notifyPackageUse(String packageName, int reason) {
24148            synchronized (mPackages) {
24149                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
24150            }
24151        }
24152    }
24153
24154    @Override
24155    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24156        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24157        synchronized (mPackages) {
24158            final long identity = Binder.clearCallingIdentity();
24159            try {
24160                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
24161                        packageNames, userId);
24162            } finally {
24163                Binder.restoreCallingIdentity(identity);
24164            }
24165        }
24166    }
24167
24168    @Override
24169    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24170        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24171        synchronized (mPackages) {
24172            final long identity = Binder.clearCallingIdentity();
24173            try {
24174                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
24175                        packageNames, userId);
24176            } finally {
24177                Binder.restoreCallingIdentity(identity);
24178            }
24179        }
24180    }
24181
24182    @Override
24183    public void grantDefaultPermissionsToEnabledTelephonyDataServices(
24184            String[] packageNames, int userId) {
24185        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledTelephonyDataServices");
24186        synchronized (mPackages) {
24187            Binder.withCleanCallingIdentity( () -> {
24188                mDefaultPermissionPolicy.
24189                        grantDefaultPermissionsToEnabledTelephonyDataServices(
24190                                packageNames, userId);
24191            });
24192        }
24193    }
24194
24195    @Override
24196    public void revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24197            String[] packageNames, int userId) {
24198        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromDisabledTelephonyDataServices");
24199        synchronized (mPackages) {
24200            Binder.withCleanCallingIdentity( () -> {
24201                mDefaultPermissionPolicy.
24202                        revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24203                                packageNames, userId);
24204            });
24205        }
24206    }
24207
24208    @Override
24209    public void grantDefaultPermissionsToActiveLuiApp(String packageName, int userId) {
24210        enforceSystemOrPhoneCaller("grantDefaultPermissionsToActiveLuiApp");
24211        synchronized (mPackages) {
24212            final long identity = Binder.clearCallingIdentity();
24213            try {
24214                mDefaultPermissionPolicy.grantDefaultPermissionsToActiveLuiApp(
24215                        packageName, userId);
24216            } finally {
24217                Binder.restoreCallingIdentity(identity);
24218            }
24219        }
24220    }
24221
24222    @Override
24223    public void revokeDefaultPermissionsFromLuiApps(String[] packageNames, int userId) {
24224        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromLuiApps");
24225        synchronized (mPackages) {
24226            final long identity = Binder.clearCallingIdentity();
24227            try {
24228                mDefaultPermissionPolicy.revokeDefaultPermissionsFromLuiApps(packageNames, userId);
24229            } finally {
24230                Binder.restoreCallingIdentity(identity);
24231            }
24232        }
24233    }
24234
24235    private static void enforceSystemOrPhoneCaller(String tag) {
24236        int callingUid = Binder.getCallingUid();
24237        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24238            throw new SecurityException(
24239                    "Cannot call " + tag + " from UID " + callingUid);
24240        }
24241    }
24242
24243    boolean isHistoricalPackageUsageAvailable() {
24244        return mPackageUsage.isHistoricalPackageUsageAvailable();
24245    }
24246
24247    /**
24248     * Return a <b>copy</b> of the collection of packages known to the package manager.
24249     * @return A copy of the values of mPackages.
24250     */
24251    Collection<PackageParser.Package> getPackages() {
24252        synchronized (mPackages) {
24253            return new ArrayList<>(mPackages.values());
24254        }
24255    }
24256
24257    /**
24258     * Logs process start information (including base APK hash) to the security log.
24259     * @hide
24260     */
24261    @Override
24262    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24263            String apkFile, int pid) {
24264        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24265            return;
24266        }
24267        if (!SecurityLog.isLoggingEnabled()) {
24268            return;
24269        }
24270        Bundle data = new Bundle();
24271        data.putLong("startTimestamp", System.currentTimeMillis());
24272        data.putString("processName", processName);
24273        data.putInt("uid", uid);
24274        data.putString("seinfo", seinfo);
24275        data.putString("apkFile", apkFile);
24276        data.putInt("pid", pid);
24277        Message msg = mProcessLoggingHandler.obtainMessage(
24278                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24279        msg.setData(data);
24280        mProcessLoggingHandler.sendMessage(msg);
24281    }
24282
24283    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24284        return mCompilerStats.getPackageStats(pkgName);
24285    }
24286
24287    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24288        return getOrCreateCompilerPackageStats(pkg.packageName);
24289    }
24290
24291    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24292        return mCompilerStats.getOrCreatePackageStats(pkgName);
24293    }
24294
24295    public void deleteCompilerPackageStats(String pkgName) {
24296        mCompilerStats.deletePackageStats(pkgName);
24297    }
24298
24299    @Override
24300    public int getInstallReason(String packageName, int userId) {
24301        final int callingUid = Binder.getCallingUid();
24302        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24303                true /* requireFullPermission */, false /* checkShell */,
24304                "get install reason");
24305        synchronized (mPackages) {
24306            final PackageSetting ps = mSettings.mPackages.get(packageName);
24307            if (filterAppAccessLPr(ps, callingUid, userId)) {
24308                return PackageManager.INSTALL_REASON_UNKNOWN;
24309            }
24310            if (ps != null) {
24311                return ps.getInstallReason(userId);
24312            }
24313        }
24314        return PackageManager.INSTALL_REASON_UNKNOWN;
24315    }
24316
24317    @Override
24318    public boolean canRequestPackageInstalls(String packageName, int userId) {
24319        return canRequestPackageInstallsInternal(packageName, 0, userId,
24320                true /* throwIfPermNotDeclared*/);
24321    }
24322
24323    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24324            boolean throwIfPermNotDeclared) {
24325        int callingUid = Binder.getCallingUid();
24326        int uid = getPackageUid(packageName, 0, userId);
24327        if (callingUid != uid && callingUid != Process.ROOT_UID
24328                && callingUid != Process.SYSTEM_UID) {
24329            throw new SecurityException(
24330                    "Caller uid " + callingUid + " does not own package " + packageName);
24331        }
24332        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24333        if (info == null) {
24334            return false;
24335        }
24336        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24337            return false;
24338        }
24339        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24340        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24341        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24342            if (throwIfPermNotDeclared) {
24343                throw new SecurityException("Need to declare " + appOpPermission
24344                        + " to call this api");
24345            } else {
24346                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24347                return false;
24348            }
24349        }
24350        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24351            return false;
24352        }
24353        if (mExternalSourcesPolicy != null) {
24354            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24355            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24356                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24357            }
24358        }
24359        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24360    }
24361
24362    @Override
24363    public ComponentName getInstantAppResolverSettingsComponent() {
24364        return mInstantAppResolverSettingsComponent;
24365    }
24366
24367    @Override
24368    public ComponentName getInstantAppInstallerComponent() {
24369        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24370            return null;
24371        }
24372        return mInstantAppInstallerActivity == null
24373                ? null : mInstantAppInstallerActivity.getComponentName();
24374    }
24375
24376    @Override
24377    public String getInstantAppAndroidId(String packageName, int userId) {
24378        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24379                "getInstantAppAndroidId");
24380        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24381                true /* requireFullPermission */, false /* checkShell */,
24382                "getInstantAppAndroidId");
24383        // Make sure the target is an Instant App.
24384        if (!isInstantApp(packageName, userId)) {
24385            return null;
24386        }
24387        synchronized (mPackages) {
24388            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24389        }
24390    }
24391
24392    boolean canHaveOatDir(String packageName) {
24393        synchronized (mPackages) {
24394            PackageParser.Package p = mPackages.get(packageName);
24395            if (p == null) {
24396                return false;
24397            }
24398            return p.canHaveOatDir();
24399        }
24400    }
24401
24402    private String getOatDir(PackageParser.Package pkg) {
24403        if (!pkg.canHaveOatDir()) {
24404            return null;
24405        }
24406        File codePath = new File(pkg.codePath);
24407        if (codePath.isDirectory()) {
24408            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24409        }
24410        return null;
24411    }
24412
24413    void deleteOatArtifactsOfPackage(String packageName) {
24414        final String[] instructionSets;
24415        final List<String> codePaths;
24416        final String oatDir;
24417        final PackageParser.Package pkg;
24418        synchronized (mPackages) {
24419            pkg = mPackages.get(packageName);
24420        }
24421        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24422        codePaths = pkg.getAllCodePaths();
24423        oatDir = getOatDir(pkg);
24424
24425        for (String codePath : codePaths) {
24426            for (String isa : instructionSets) {
24427                try {
24428                    mInstaller.deleteOdex(codePath, isa, oatDir);
24429                } catch (InstallerException e) {
24430                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24431                }
24432            }
24433        }
24434    }
24435
24436    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24437        Set<String> unusedPackages = new HashSet<>();
24438        long currentTimeInMillis = System.currentTimeMillis();
24439        synchronized (mPackages) {
24440            for (PackageParser.Package pkg : mPackages.values()) {
24441                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24442                if (ps == null) {
24443                    continue;
24444                }
24445                PackageDexUsage.PackageUseInfo packageUseInfo =
24446                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24447                if (PackageManagerServiceUtils
24448                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24449                                downgradeTimeThresholdMillis, packageUseInfo,
24450                                pkg.getLatestPackageUseTimeInMills(),
24451                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24452                    unusedPackages.add(pkg.packageName);
24453                }
24454            }
24455        }
24456        return unusedPackages;
24457    }
24458
24459    @Override
24460    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24461            int userId) {
24462        final int callingUid = Binder.getCallingUid();
24463        final int callingAppId = UserHandle.getAppId(callingUid);
24464
24465        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24466                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24467
24468        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24469                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24470            throw new SecurityException("Caller must have the "
24471                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24472        }
24473
24474        synchronized(mPackages) {
24475            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24476            scheduleWritePackageRestrictionsLocked(userId);
24477        }
24478    }
24479
24480    @Nullable
24481    @Override
24482    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24483        final int callingUid = Binder.getCallingUid();
24484        final int callingAppId = UserHandle.getAppId(callingUid);
24485
24486        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24487                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24488
24489        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24490                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24491            throw new SecurityException("Caller must have the "
24492                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24493        }
24494
24495        synchronized(mPackages) {
24496            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24497        }
24498    }
24499
24500    @Override
24501    public boolean isPackageStateProtected(@NonNull String packageName, @UserIdInt int userId) {
24502        final int callingUid = Binder.getCallingUid();
24503        final int callingAppId = UserHandle.getAppId(callingUid);
24504
24505        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24506                false /*requireFullPermission*/, true /*checkShell*/, "isPackageStateProtected");
24507
24508        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID
24509                && checkUidPermission(MANAGE_DEVICE_ADMINS, callingUid) != PERMISSION_GRANTED) {
24510            throw new SecurityException("Caller must have the "
24511                    + MANAGE_DEVICE_ADMINS + " permission.");
24512        }
24513
24514        return mProtectedPackages.isPackageStateProtected(userId, packageName);
24515    }
24516}
24517
24518interface PackageSender {
24519    /**
24520     * @param userIds User IDs where the action occurred on a full application
24521     * @param instantUserIds User IDs where the action occurred on an instant application
24522     */
24523    void sendPackageBroadcast(final String action, final String pkg,
24524        final Bundle extras, final int flags, final String targetPkg,
24525        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24526    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24527        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24528    void notifyPackageAdded(String packageName);
24529    void notifyPackageRemoved(String packageName);
24530}
24531